You are much more flexible when you use methods that take NSURLRequest
like for example dataTaskWithRequest:
method. That way you can customize HTTP method, request body, headers, basically every parameter of the NSURLRequest
because it is you that creates it.
Methods that take NSURL
create the NSURLRequest
for you under the hood so you cannot modify the request afterwards. For example dataTaskWithURL:
method creates an HTTP GET
request for the specified URL
and you cannot change it to POST
.
Example of creating a task with NSURLRequest
. You can see you can be very flexible here:
// Create a simple JSON data.
NSData *JSONData = [NSJSONSerialization dataWithJSONObject:@{ @"numbers" : @[@1, @2, @3] } options:0 error:nil];
// Create a POST request with our JSON as a request body.
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
// Set HTTP method.
request.HTTPMethod = @"POST";
// Set request body.
request.HTTPBody = JSONData;
// Create a task.
NSURLSessionDataTask *task = [[NSURLSession sharedSession] dataTaskWithRequest:request
completionHandler:^(NSData *data,
NSURLResponse *response,
NSError *error)
{
...
}];
Example of creating a task using NSURL
. Here you cannot modify the request. It is created for you.
// Create a GET task.
NSURLSessionDataTask *task = [[NSURLSession sharedSession] dataTaskWithURL:url
completionHandler:^(NSData *data,
NSURLResponse *response,
NSError *error)
{
...
}];