Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

ios - 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:

{"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))}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...