13

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 ?

Aymenworks
  • 423
  • 7
  • 21

1 Answers1

7

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.

Neeku
  • 3,646
  • 8
  • 33
  • 43
  • HTTP newbie here... What happens if I issue a `dataTaskWithRequest()`, passing a request configured to `POST`? I am sending credentials to the server over https for the first time, in order to get a token. I appended the credentials (JSON) to the request's body, and set the Authroization header for the whole `NSURLSession`. The sample code in your answer for upload task uses an image payload. I don't know if it applies to my case, but I still want to use `POST`. – Nicolas Miari Jul 24 '15 at 06:57
  • 1
    @NicolasMiari: "Data tasks send and receive data using NSData objects. Data tasks are intended for short, often interactive requests from your app to a server. Data tasks can return data to your app one piece at a time after each piece of data is received, or all at once through a completion handler." see https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/URLLoadingSystem/Articles/UsingNSURLSession.html so yeah you can use it. – scrrr Jan 21 '16 at 12:30
  • 4
    I don't think the question is ambiguous at all. The question is for the exact code posted and whether or not there is a difference in passing the JSON body data in the URLRequest with a dataTask vs passing the JSON body data in an uploadTask. Nothing from the Apple docs definitively answer if there is a difference or suggestion in which route to take here. – Adam Johns Nov 04 '19 at 20:35