2016-02-04 117 views
2

我想發出POST請求並傳遞一些參數。 我要傳遞的參數是:帶字符串參數和數組的POST請求

- Item : String 
- Length : String 
- Names : String Array 
- Age : String 

今天I'm這樣

var URL: NSURL = NSURL(string: "URL")! 
var request:NSMutableURLRequest = NSMutableURLRequest(URL:URL) 

request.HTTPMethod = "POST" 
request.HTTPBody = // parameters here? 
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()) { 
       (response, data, error) in 
       println(NSString(data: data, encoding: NSUTF8StringEncoding)) 
} 

如何通過在我的請求,上述參數誰能提供幫助?我不太確定如何做到這一點。

回答

0

添加一個變量爲您的參數:

var params: [String: AnyObject] = [:] 
params["item"] = "YOUR_STRING" 
params["length"] = "YOUR_STRING" 
params["names"] = ["YOUR_STRING1", "YOUR_STRING2"] 
params["age"] = "YOUR_STRING" 

假設POST是JSON請求,將它們添加到HTTPBody這樣:

request.HTTPBody = try NSJSONSerialization.dataWithJSONObject(params, options: []) 
2

的事情是HTTPBody期待NSData對象,因此您可以使用@dsk在此答案中解釋所需的數據創建Dictionary,然後將其轉換爲JSON以使用dataWithJSONObject函數作爲參數傳遞,如下面的w AY:

var request:NSMutableURLRequest = NSMutableURLRequest(URL:URL) 
request.HTTPMethod = "POST" 
request.setValue("application/json", forHTTPHeaderField: "Content-Type") 

var values: [String: AnyObject] = [:] 
values["item"] = "value" 
values["length"] = "value" 
values["names"] = ["value1", "value2"] 
values["age"] = "value" 

request.HTTPBody = try! NSJSONSerialization.dataWithJSONObject(values, options: []) 

不過我強烈建議你使用Alamofire更輕鬆地處理所有的聯網過程。

我希望這對你有所幫助。