iphone - 当我在后台运行 NSURLConnection 错误时......我该如何修复?

标签 iphone objective-c ios nsurlconnection

我有这段代码,但我不明白为什么我必须在主线程上运行它。 如果我在后台运行它,它不会执行发布请求。这是一个错误吗? 我该如何解决这个问题?

- (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/

相关文章:

ios - 无法在我的 iPhone 应用程序中显示 playhaven 全屏广告

iphone - 我应该如何构建我的 .plist 数组和字典?

ios - UIView::addSubView 遮挡了原本位于顶部的导航栏

ios - SwiftUI:允许导航栏仅出现在主页/第一页上

objective-c - 如何知道一个对象可以响应的所有消息?

iphone - 我如何从 iOS 框架中删除或重命名符号?

iphone - 更改 VIewControllers 停止动画

iphone - 如果不满足功能,则阻止用户安装我的应用程序

iphone - Apple Mach-O 链接器 (Id) 错误

ios - 如何像屏保一样改变CAGradientLayer的颜色?