NSURLConnection 和 NSTIMER 问题
我目前正在尝试在发出异步请求时将时间控制在 20 秒以内。
我遇到的问题是 NSURLconnection 在主线程上运行,因此,如果我运行 NSTIMER 来计算已经过去的秒数,它永远不会触发选择器,因为 NSURLconnection 阻塞了主线程。我可能可以在不同的线程上运行 NSURLconnection,因为它是线程安全的,但我有一些奇怪的问题,我的代表没有被调用等等......任何帮助都是值得赞赏的。
以下是我的片段:
NSURL *requestURL = [NSURL URLWithString:SERVER];
NSMutableURLRequest *req = [[[NSMutableURLRequest alloc] initWithURL:requestURL] autorelease];
theConnection = [[NSURLConnection alloc]initWithRequest:req delegate:self];
if (!timeoutTimer) {
NSLog(@"Create timer");
timeoutTimer = [NSTimer scheduledTimerWithTimeInterval:TIMEOUT target:self selector:@selector(cancelURLConnection) userInfo:nil repeats:YES];
}
I am currently trying to have a time out of 20 second when making an async request.
The issue am having is that the NSURLconnection runs on the main thread and therefore, if I run an NSTIMER to count the number of seconds that has passed, it never fires the selector since the NSURLconnection is blocking the main thread. I can probably run the NSURLconnection on a different thread since it is thread safe but I have weird issues with my delegates not being called etc.. any help is appreciated.
Below is my sniplet:
NSURL *requestURL = [NSURL URLWithString:SERVER];
NSMutableURLRequest *req = [[[NSMutableURLRequest alloc] initWithURL:requestURL] autorelease];
theConnection = [[NSURLConnection alloc]initWithRequest:req delegate:self];
if (!timeoutTimer) {
NSLog(@"Create timer");
timeoutTimer = [NSTimer scheduledTimerWithTimeInterval:TIMEOUT target:self selector:@selector(cancelURLConnection) userInfo:nil repeats:YES];
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
NSURLConnection
的异步方法不会阻塞主线程。如果您的计时器没有启动,则还有其他原因。在后台线程上使用它的问题是由于后台线程默认没有运行循环这一事实造成的。The asynchronous methods of
NSURLConnection
do not block the main thread. If your timer isn't firing, this has other reasons. Your problems with using it on a background thread result from the fact that a background thread doesn't have a runloop by default.这是关于如何设置简单的 NSOperation 以在单独的线程上运行方法的精彩教程。我会根据你提到的内容开始。希望有帮助!
This is a great tutorial on how to set up a simple NSOperation to run a method on a separate thread. I'd start with this based on what you have mentioned. Hope that helps!