Search code examples
iosobjective-cnsurlconnectionnsurlsession

Migrating to NSURLSession from NSURLConnection incompatible pointer types


I'm moving from NSURLConnection to NSURLSession and running into a problem with the NSMutableURLRequest that holds values for the URL request.

Any ideas on how to retain this info in the NSURLSession without getting this error:

incompatible pointer types sending nsmutableurlrequest to parameter of type nesting * _nonull nsurl urlwithstring

I see that this line [NSURL URLWithString:myRequest] wants a NSString, but how to I still pass the other info that is on my NSMutableURLRequest?

NSMutableURLRequest *myRequest = [NSMutableURLRequest requestWithURL: myURL];
[acquisitionRequest setValue:userAgent forHTTPHeaderField:@"User-Agent"];

NSURLSession *session = [NSURLSession sharedSession];
[[session dataTaskWithURL:[NSURL URLWithString:myRequest]
            completionHandler:^(NSData *data,
                                NSURLResponse *response,
                                NSError *error) {                
            }] resume];

Solution

  • You should use dataTaskWithRequest:completionHandler: instead of dataTaskWithURL:completionHandler:. This way you can pass the whole request in. If it complains about being mutable, you can copy it to get rid of the mutable state.

    NSMutableURLRequest *myRequest = [NSMutableURLRequest requestWithURL: myURL]; 
    [acquisitionRequest setValue:userAgent forHTTPHeaderField:@"User-Agent"];
    
    NSURLSession *session = [NSURLSession sharedSession];
    
    [[session dataTaskWithRequest:[myRequest copy]
                completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
                    // completion stuff
    }] resume];