These are my two examples:
let config = NSURLSessionConfiguration.defaultSessionConfiguration() config.HTTPAdditionalHeaders = ["Accept": "application/json", "Content-Type": "application/json", "User-Agent": UIDevice.currentDevice().model] var request = NSMutableURLRequest(URL: NSURL(string: "http://XXX")) request.HTTPMethod = "POST" let valuesToSend = ["key":value, "key2":value] var error: NSError? let data = NSJSONSerialization.dataWithJSONObject(valuesToSend, options:NSJSONWritingOptions.PrettyPrinted, error: &error) request.HTTPBody = data if error == nil { let task = NSURLSession(configuration: config).dataTaskWithRequest(request, completionHandler: {data, response, error in if error == nil { println("received == \(NSString(data: data, encoding: NSUTF8StringEncoding))") } }) task.resume() } else { println("Oups error \(error)") }
And second
let config = NSURLSessionConfiguration.defaultSessionConfiguration() config.HTTPAdditionalHeaders = ["Accept": "application/json", "Content-Type": "application/json", "User-Agent": UIDevice.currentDevice().model] var request = NSMutableURLRequest(URL: NSURL(string: "http://XXX")) request.HTTPMethod = "POST" let valuesToSend = ["key":value, "key2":value] var error: NSError? let data = NSJSONSerialization.dataWithJSONObject(valuesToSend, options:NSJSONWritingOptions.PrettyPrinted, error: &error) if error == nil { let task = NSURLSession(configuration: config).uploadTaskWithRequest(request, fromData: data, completionHandler: {data, response, error in if error == nil { println("received == \(NSString(data: data, encoding: NSUTF8StringEncoding))") } }) task.resume() } else { println("Oups error \(error)") }
So, I wonder: what are the differences between the two examples and what is the best for my case (simple post and reception)
Are both in the background? So?
Aymenworks
source share