Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSURLSession post : difference between uploadTask and dataTask

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 the 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 these twos examples and what about the better for my case ( simple post and reception )

The two are in background no ? So ?

like image 277
Aymenworks Avatar asked Aug 26 '14 11:08

Aymenworks


1 Answers

From NSURLSession Class Reference:

dataTaskWithRequest:

Creates an HTTP request based on the specified URL request object. - (NSURLSessionDataTask *)dataTaskWithRequest:(NSURLRequest *)request Parameters

request

An object that provides request-specific information such as the URL, cache policy, request type, and body data or body stream.

Return Value

The new session data task.

Discussion

After you create the task, you must start it by calling its resume method.

Availability

Available in iOS 7.0 and later.

Declared In

NSURLSession.h


uploadTaskWithRequest:fromData:

Creates an HTTP request for the specified URL request object and uploads the provided data object. - (NSURLSessionUploadTask *)uploadTaskWithRequest:(NSURLRequest *)request fromData:(NSData *)bodyData Parameters

request

An NSURLRequest object that provides the URL, cache policy, request type, and so on. The body stream and body data in this request object are ignored.

bodyData

The body data for the request.

Return Value

The new session upload task.

Discussion

After you create the task, you must start it by calling its resume method.

Availability

Available in iOS 7.0 and later.

Declared In

NSURLSession.h

And additionally, Ray Wenderlich says:

NSURLSessionDataTask

This task issues HTTP GET requests to pull down data from servers. The data is returned in form of NSData. You would then convert this data to the correct type XML, JSON, UIImage, plist, etc.

NSURLSessionDataTask *jsonData = [session dataTaskWithURL:yourNSURL
      completionHandler:^(NSData *data,
                          NSURLResponse *response,
                          NSError *error) {
        // handle NSData
}];

NSURLSessionUploadTask

Use this class when you need to upload something to a web service using HTTP POST or PUT commands. The delegate for tasks also allows you to watch the network traffic while it's being transmitted.

Upload an image:

NSData *imageData = UIImageJPEGRepresentation(image, 0.6);

NSURLSessionUploadTask *uploadTask =
  [upLoadSession uploadTaskWithRequest:request
                              fromData:imageData];

Here the task is created from a session and the image is uploaded as NSData. There are also methods to upload using a file or a stream.

However your question remains quite ambiguous and too broad, since you haven't explained an explicit, specific problem and you could easily find this information by searching a little bit.

like image 128
Neeku Avatar answered Oct 21 '22 11:10

Neeku