Search code examples
iosobjective-cnsurlsessionnsurlrequest

cURL request works, but not an equivalent NSURLSession request


This cURL gives me a good result on the console:

curl -H "Accept: application/json" https://myusername:[email protected]/someroute

But this iOS code generates a 404

NSURL *URL = [NSURL urlWithString:@"https://myusername:[email protected]/someroute"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
request.HTTPMethod = @"GET";
[request addValue:@"application/json" forHTTPHeaderField:@"Accept"];

NSURLSession *session = [NSURLSession sharedSession];
[[session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
    // here, data is nil, there's no error, but the api returns 404
}] resume];

I know about transport security settings in iOS, but I thought those pertain only to http requests. Can someone suggest what I might be doing wrong in iOS given that the cURL works fine?


Solution

  • Basic authentication credentials should be attached in the header.

    Swift3:

    let raw = "myusername:mypassword"
    let encoded = raw.data(using: String.Encoding.ascii)!
    let value = "Basic \(encoded.base64EncodedString())"
    

    ObjC (not tested)

    NSString *raw = @"myusername:mypassword";
    NSData *encoded = [raw dataUsingEncoding:NSASCIIStringEncoding];
    NSString *value = [NSString stringWithFormat:@"Basic %@", [encoded base64EncodedStringWithOptions:0]];
    [request setValue:value forHTTPHeaderField:@"Authorization"];
    

    Alternatively you can also verify the Authorization header using curl -H "Accept: application/json" -H "authorization: <value>" https://somehost.com/someroute