NSData dataWithContentsOfURL: not returning data for URL that shows in browser

I am making an iOS client for the Stack Exchange API. After a long, drawn out fight I finally managed to implement authentication – which gives me a token I stick into a URL. When the token is valid, the URL looks like this:

https://api.stackexchange.com/2.1/me/associated?key=_____MY_SECRET_KEY______&access_token=_____ACCESS_TOKEN_:)_____

which, when valid, brings me to this JSON in a webpage:

  • How did Whatsapp app removed app's compatibility for iPad?
  • iOS start Background Thread
  • How do I get the current version of my iOS project in code?
  • How to reload all tableview cells, while editing a textfield in a tableview cell - iOS Swift
  • cordova&jquery:value sent to another static html page
  • What does the NS prefix mean?
  • {"items":[{"site_name":"Stack Overflow","site_url":"http://stackoverflow.com","user_id":1849664,"reputation":4220,"account_id":1703573,"creation_date":1353769269,"badge_counts":{"gold":8,"silver":12,"bronze":36},"last_access_date":1375455434,"answer_count":242,"question_count":26},{"site_name":"Server Fault","site_url":"http://serverfault.com","user_id":162327,"reputation":117,"account_id":1703573,"creation_date":1362072291,"badge_counts":{"gold":0,"silver":0,"bronze":9},"last_access_date":1374722580,"answer_count":0,"question_count":4},...
    

    And I get the correct JSON with this code:

    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"https://api.stackexchange.com/2.1/me/associated?key=__SECRET_KEY_:)__&access_token=%@", [[NSUserDefaults standardUserDefaults] objectForKey:@"token"]]];
    NSData *jsonData = [NSData dataWithContentsOfURL:url];
    if (jsonData)
    {
        NSDictionary *JSON = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:nil];
    }
    

    When I manually invalidate the token, however, the URL still looks the same, and the page in a browser displays this:

    {"error_id":403,"error_name":"access_denied","error_message":"`key` is not valid for passed `access_token`, token not found."}
    

    However, dataWithContentsOfURL: is always nil. Why? What am I doing wrong?

    I do get an NSError returned:

    Error Domain=NSCocoaErrorDomain Code=256 "The operation couldn’t be completed. (Cocoa error 256.)" UserInfo=0x1dd1e9f0 {NSURL=https://api.stackexchange.com/2.1/me/associated?key=key((&access_token=to‌​ken))}
    

    5 Solutions Collect From Internet About “NSData dataWithContentsOfURL: not returning data for URL that shows in browser”

    NSCocoaErrorDomain Code=256 actually means a “file system or file I/O related error whose reason is unknown”.

    Why you get this error is likely because using dataWithContentsOfURL: will not work with that remote URL – or maybe because of the query params which contain the authentication and the token. Thus, you get the “weird” error.

    In general, NSData’s dataWithContentsOfURL: should only be use to access local file resources.

    In order to solve your problem, you should improve your code in two steps:

    1) Use NSURLConnection’s convenient class method

    + (void)sendAsynchronousRequest:(NSURLRequest *)request queue:(NSOperationQueue *)queue completionHandler:(void (^)(NSURLResponse*, NSData*, NSError*))handler

    The block defines what to do with the response data when the request finished. Generally, first check the error parameter, then status code of the response and Content-type – in this order.

    2) Replace the former with your own instance method (or one from a third party) with a similar signature but which is much more sophisticated.

    Approach #2 enables you to implement and use the following important features

    • Cancellation
    • customize authentication in every aspects
    • load body data to files
    • process received chunks simultaneous
    • perform multiple requests in a queue which controls the number of simultaneous connections

    and a couple more.

    Approach #2 is oftentimes implemented as a subclass of NSOperation and encapsulates a NSURLConnection object (which you need to cancel the connection).

    You’ll find answers of how to use NSURLConnection in asynchronous mode implementing the delegates. Also, there are third party solutions.

    You might find the official documentation invaluable, too:
    Using NSURLConnection

    For a quick start, you may take a look at my “Simple GET request” class on Gist:

    SimpleGetHTTPRequest

    This class is NOT based on NSOperation, but it can be modified easily. Consult the official documentation of NSOperation how to make a subclass. This is basically easy, but has a few important things (KVO) which you should get correct.

    In my case, adding AppTransportSecuritySettings dictionary into info.plist and setting key AllowArbitraryLoads to true.

    Fixed my problem…

    Hope it helps new developers.

    Your URL might be having a space that’s why it returns nil.Just replace the space in URL with a ‘+’ :

    stringByReplacingOccurrencesOfString:@" " withString:@"+"
    

    I had this problem when I changed my folder structure. It gave me other NSError codes such as 512 and 4 for any file operations (local and web). The solution was to delete my IOS Simulator folders (Library\Developer\CoreSimulator).

    If you are trying to access a remote url via HTTP and using XCode 7 or later you may get a NSCocoaErrorDomain returned from [NSData dataWithContentsOfURL:].

    The root cause of this may actually be your “App Transport Security Settings”. By default iOS doesn’t allow arbitrary loading of URLS.