Reputation: 21091
I need to send many variables to server. Previously I was using construction like this:
let myURL = NSURL(string: "http://example.com");
let request = NSMutableURLRequest(URL:myURL!);
request.HTTPMethod = "POST";
let postString = "param1=\(var1)¶m2=\(var2)"
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding);
Now I need to send not only variables like param1 and param2 but few arrays. I know that there is library called Alamofire but it is not supporting iOS 7.
Upvotes: 0
Views: 671
Reputation: 27428
You can do something like this,
let mapDict = [ "a":"First", "b":"Second"]
let json = [ "title":"kk" , "dict": mapDict ]
let jsonData = NSJSONSerialization.dataWithJSONObject(json, options: .PrettyPrinted, error: nil)
// create post request
let url = NSURL(string: "http://example.com/post")!
let request = NSMutableURLRequest(URL: url)
request.HTTPMethod = "POST"
// insert json data to the request
request.HTTPBody = jsonData
let task = NSURLSession.sharedSession().dataTaskWithRequest(request){ data,response,error in
if error != nil{
println(error.localizedDescription)
return
}
if let responseJSON = NSJSONSerialization.JSONObjectWithData(data, options: nil, error: nil) as? [String:AnyObject]{
println(responseJSON)
}
}
task.resume()
You can use array instead of dictionary as per your requirement. hope this will help. :)
Upvotes: 1