ios - 在主线程上运行 NSURLSession 完成处理程序

标签 ios multithreading cocoa ios7

我正在使用 NSURLSession 来获取填充 TableView 的值。我正在更新完成处理程序中的 TableView,但是使用 [[NSThread currentThread] isMainThread] 告诉我完成处理程序没有在主线程中运行。因为我应该只从主线程更新 UI,所以我知道这是不正确的。有没有办法从完成处理程序触发主线程上的操作?还是使用 NSURLSession 是解决此问题的错误方法?

NSURLSession *session = [NSURLSession sharedSession];
[[session dataTaskWithURL:[NSURL URLWithString:@"http://myurl"]
        completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
            NSError *jsonError = nil;
            NSArray* jsonUsers = [NSJSONSerialization JSONObjectWithData:data options:0 error:&jsonError];
            if (jsonError) {
                NSLog(@"error is %@", [jsonError localizedDescription]);
                // Handle Error and return
                return;
            }
            self.userArray = jsonUsers;
            [self.userTableView reloadData];
            if ([[NSThread currentThread] isMainThread]){
                NSLog(@"In main thread--completion handler");
            }
            else{
                NSLog(@"Not in main thread--completion handler");
            }
}] resume];

最佳答案

是的,只需使用 GCD 分派(dispatch)您的主线程内容:

 NSURLSession *session = [NSURLSession sharedSession];
    [[session dataTaskWithURL:[NSURL URLWithString:@"http://myurl"]
            completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
                NSError *jsonError = nil;
                NSArray* jsonUsers = [NSJSONSerialization JSONObjectWithData:data options:0 error:&jsonError];
                if (jsonError) {
                    NSLog(@"error is %@", [jsonError localizedDescription]);
                    // Handle Error and return
                    return;
                }

                dispatch_async(dispatch_get_main_queue(), ^{
                    self.userArray = jsonUsers;
                    [self.userTableView reloadData];
                    if ([[NSThread currentThread] isMainThread]){
                        NSLog(@"In main thread--completion handler");
                    }
                    else{
                        NSLog(@"Not in main thread--completion handler");
                    }
                });

            }] resume];

关于ios - 在主线程上运行 NSURLSession 完成处理程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20052682/

相关文章:

ios - Xcode 9.2 - “Fixed Width Constraints May Cause Clipping” 警告

javascript - IOS : control/prevent selection toolbar? 上可编辑

java - Java中作为函数参数的函数

Java线程: Automatic Termination

macos - NSTokenField 的灵活替代方案?

objective-c - 使用 .plist 中的键在数组中创建 <dict> (Cocoa/iPhone SDK)

cocoa - 如何将日期字符串转换为字符串(yyyy-MM-dd)。这样做时,我得到空值?

ios - React Native iOS - 未找到 GoogleToolboxforMac

ios - UIView 框架在滚动时自动重置

java - 如何在多线程 HTTP Client 环境中使用基本身份验证?