【问题标题】:How to use NSMutableURLRequest or Alamofire [closed]如何使用 NSMutableURLRequest 或 Alamofire [关闭]
【发布时间】:2016-08-17 23:21:54
【问题描述】:

我有 body 令牌和 customer_id。我想进入身体。我还想传递包含 x-access-token 的标头。这是我现在的代码

func sendToken(token:PSTCKToken, customer_id: Int){

    let url = NSURL(string: "urlGoesHERE")!
    let request = NSMutableURLRequest(URL: url)
    request.HTTPMethod = "POST"

    request.setValue("x-access-token", forHTTPHeaderField: "Bearer xxxxxxxxxxxx")

    let postBody = "token=\(token)&customer_id=\(customer_id)"

    let postData = postBody.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)

    let session = NSURLSession.sharedSession()

    session.uploadTaskWithRequest(request, fromData: postData, completionHandler: { data, response, error in
        let successfulResponse = (response as? NSHTTPURLResponse)?.statusCode == 200
        if successfulResponse && error == nil && data != nil{
            // All was well
            let newStr = NSString(data: data!, encoding: NSUTF8StringEncoding)
            print(newStr) // All we did here is log it to the output window
        } else {
            if let e=error {
                print(e.description)
            } else {
                // There was no error returned though status code was not 200
                print("There was an error communicating with  payment backend.")
                // All we did here is log it to the output window
            }

        }
    }).resume()
}

这是我使用 NSMutableURLRequest 的代码 我如何使用 NSMutableURLRequest 或 Alamofire 来做到这一点

【问题讨论】:

    标签: ios json swift alamofire nsurlrequest


    【解决方案1】:
    pod 'Alamofire'
    

    创建一个通用的POST请求方法

    // MARK: Common Request
    func PostApiRequest(method: Alamofire.Method, url: String, apiData: [String : AnyObject], completion:(finished: Bool, response: AnyObject?) ->Void) {
        let headers = ["x-access-token": "Bearer xxxxxxxxxxxx"]
    
        Alamofire.request(method, url, parameters: apiData, encoding: .JSON, headers: headers).responseJSON{ response in
            if let JSON = response.result.value {
                completion(finished: true, response: JSON)
            } else {
                completion(finished: false, response:response.result.error)
            }
        }
    }
    

    调用上面的泛型方法如下:-

    let param = ["token":"token value here", "customer_id":"123456"]
        self.PostApiRequest(.POST, url: API_LOGIN, apiData: params) { (finished, response) in
        if(finished)
        {
        print(response)
        }
        else{
    
        }
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-09-28
      • 1970-01-01
      • 2019-11-19
      • 2021-11-02
      • 2019-09-06
      • 2017-07-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多