我有这段代码,但我不明白为什么我必须在主线程上运行它。 如果我在后台运行它,它不会执行发布请求。这是一个错误吗? 我该如何解决这个问题?
- (void)setRead:(MWFeedItem *)entry
{ [self getToken:YES];
NSString *url=[NSString stringWithFormat:@"https://www.google.com/reader/api/0/edit-tag?a=user/-/state/com.google/read&i=%@&T=%@", entry.identifier, token];
[self postRequestWithURLState:url];
}
- (void)postRequestWithURLState:(NSString *)url
{
NSString *bodyRequest = nil;
NSURL *requestURL = [NSURL URLWithString:url];
NSMutableURLRequest *theRequest = [[NSMutableURLRequest alloc] init];
//NSLog(@"-------------- bodyRequest: %@", bodyRequest);
[theRequest setURL:requestURL];
[theRequest setTimeoutInterval:0.5];
[theRequest setHTTPMethod:@"POST"];
[theRequest setHTTPBody:[bodyRequest dataUsingEncoding:NSASCIIStringEncoding]];
[self.oauthAuthentication authorizeRequest:theRequest];
[NSURLConnection connectionWithRequest:theRequest delegate:self];
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
}
这是我的电话:
-(void)segnaLettura:(MWFeedItem *)item{
[reader setRead:item];
}
- (void) segnaread:(MWFeedItem *)item{
[self performSelectorOnMainThread:@selector(segnaLettura:) withObject:item waitUntilDone:NO];
}
最佳答案
为了使异步 NSURLConnection
发挥作用,它需要处理线程的运行循环。虽然新线程会自动获得运行循环,但运行它取决于您。
您可以在 Threading Programming Guide 中了解如何执行此操作,我可以解释更多,但大多数时候这不是你想要的。大多数时候,在 iOS 中,后台线程应该使用 NSOperation 或 GCD 进行管理。一般来说,如果您在 iOS 4+ 上手动生成线程,那么您就做错了。也有异常(exception),但并不常见。
这里的第一个问题应该是“为什么我要有一个后台线程?”
如果您确实需要后台线程,那么您执行 segnaread
的方式可能就可以了。
关于iphone - 当我在后台运行 NSURLConnection 错误时......我该如何修复?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9445359/