2016-08-17 5 views
0

私はbody tokenとcustomer_idを持っています。私は体に渡りたい。私はまた、x-access-tokenを含むヘッダーを渡したいと思う。ここに私のコードは今NSMutableURLRequestまたはAlamofireの使用方法

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またはAlamofireでこれを行うことができますどのようにNSMutableURLRequest を使用している

答えて

2
pod 'Alamofire' 

// 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) 
     } 
    } 
} 

共通POSTリクエストメソッドを作成します。上記の一般的な方法を以下のように呼び出します。 -

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{ 

    } 
    } 
+0

ありがとうございました! – lordxxx

関連する問題