NSData dataWithContentsOfURL:不返回浏览器中显示的URL的数据 [英] NSData dataWithContentsOfURL: not returning data for URL that shows in browser

查看:159
本文介绍了NSData dataWithContentsOfURL:不返回浏览器中显示的URL的数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为Stack Exchange API制作一个iOS客户端.经过漫长的争执,我终于设法实现了身份验证-这给了我一个粘贴在URL中的令牌.当令牌有效时,URL如下所示:

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_:)_____

,当有效时,它将带我进入网页中的JSON:

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},...

然后我用以下代码获得正确的JSON:

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];
}

但是,当我手动使令牌无效时,URL仍然看起来相同,并且浏览器中的页面显示如下:

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."}

但是, dataWithContentsOfURL:始终为空.为什么?我在做什么错了?

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

我确实返回了NSError:

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))}

推荐答案

NSCocoaErrorDomain代码= 256实际上意味着原因不明的文件系统或文件I/O相关错误".

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

为什么会出现此错误,可能是因为使用dataWithContentsOfURL:不适用于该远程URL-或可能是因为包含验证和令牌的查询参数.因此,您会收到怪异"错误.

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.

通常,NSData的dataWithContentsOfURL:仅应用于访问本地文件资源.

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:

+ (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使您能够实现和使用以下重要功能

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

  • 取消
  • 在各个方面自定义身份验证
  • 将正文数据加载到文件
  • 同时处理收到的数据块
  • 在队列中执行多个请求,该队列控制同时连接的数量

还有更多

方法2通常是作为NSOperation的子类实现的,并且封装了NSURLConnection 对象(您需要取消连接).

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

您将找到有关如何在实现代理的异步模式下使用NSURLConnection的答案.另外,还有第三方解决方案.

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

您可能还会发现官方文档非常宝贵: 使用NSURLConnection

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

为了快速入门,您可以看一下我在Gist上的简单GET请求"类:

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

SimpleGetHTTPRequest

此类并非基于NSOperation,但可以轻松对其进行修改.请查阅NSOperation的官方文档,了解如何制作子类.这基本上很容易,但是有一些重要的事情(KVO),您应该正确无误.

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.

这篇关于NSData dataWithContentsOfURL:不返回浏览器中显示的URL的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆