NSDictionary DictionaryWithContentsOfURL 超时?
我编写了一个简单的代码来从网络服务器获取字符串值,现在我想设置超时,例如,执行 getData 10 秒,然后如果服务器在 10 秒后没有响应,则取消获取数据并执行“noConnect”。知道我该怎么做吗?
-(void)getData {
NSURL *url = [NSURL URLWithString: [NSString stringWithFormat:
@"http://exaple.com/example.plist"]];
NSDictionary *data = [NSDictionary dictionaryWithContentsOfURL:url];
NSString *aKey = [chamUpdateData objectForKey:@"count"];
}
-(void)noConnect{}
I writed a simple code to get string value from a web server, now I wanna to set timeout, like, do getData 10 sec then if server not responding after 10 second cancel getting data and do "noConnect". any idea how can I do that?
-(void)getData {
NSURL *url = [NSURL URLWithString: [NSString stringWithFormat:
@"http://exaple.com/example.plist"]];
NSDictionary *data = [NSDictionary dictionaryWithContentsOfURL:url];
NSString *aKey = [chamUpdateData objectForKey:@"count"];
}
-(void)noConnect{}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以将对
dictionaryWith...
的调用包装在NSOperation
以便异步执行;然后启动一个 NSTimer 以便它触发,您可以检查 NSOperation 的状态;如果它仍在运行,那么您可以取消它。请记住,一旦发送网络请求,据我所知,没有办法真正停止该请求。因此,当连接时间超过该时间时,您只需设置一个超时来管理这种情况。如果响应在一分钟内到达,您将忽略该数据。
You could wrap the call to
dictionaryWith...
in anNSOperation
in order to execute it asynchronously; then start anNSTimer
so that then it fires, you can check the status of theNSOperation
; if it is stillrunning
, then you cancel it.Keep in mind that there is no way I know of to actually stop the network request, once you have sent it. So, you simply have a timeout to manage the case when the connection takes longer than that. If the response arrives in 1 minute, you will simply ignore that data.
创建一个 10 秒的 NSTimer 并调用该函数来检查服务器是否没有响应,并相应地停止获取数据。
如果应用程序位于 cocos2d 中,则不能使用 NSTimer。相反,以 1 秒的间隔安排一个函数,只增加该函数中的计数并检查该函数中的计数是否为 10,如果计数为 10,则调用 stopGettingData 函数。
Create an NSTimer of 10 seconds and call the function which will check whether server is not responding or not and accordingly stop getting data.
If the application is in cocos2d then you can not use NSTimer. Instead schedule a function with an interval of 1 second and just increment a count in that function and check if it is 10 in the same, and if count is 10 then call your stopGettingData function.