NSURLConnection 和 NSTIMER 问题

发布于 2024-11-29 08:49:24 字数 699 浏览 2 评论 0原文

我目前正在尝试在发出异步请求时将时间控制在 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 技术交流群。

扫码二维码加入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.

空城缀染半城烟沙 2024-12-06 08:49:24

是关于如何设置简单的 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!

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文