本文介绍了NSURLSessionDataTask 完成处理程序未在命令行项目中执行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我查看了多个关于此问题的堆栈溢出帖子,并尝试实施这些修复但无济于事.这个问题的前两个答案都没有工作NSURLSessionDataTask 不执行完成处理程序块

I have looked on multiple stack overflow posts regarding this issue and attempted to implement those fixes to no avail. Neither of the top two answers from this question worked NSURLSessionDataTask not executing the completion handler block

这是我的非常简单的代码

Here is my very simple code

#import <Foundation/Foundation.h>

int main(int argc, const char * argv[]) {
@autoreleasepool {
    NSURLSession* session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
    NSURLSessionDataTask *dataTask = [session dataTaskWithURL:[NSURL URLWithString:@"https://itunes.apple.com/search?term=apple&media=software"] completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
        NSLog(@"%@", json);
    }];

    [dataTask resume];
}
return 0;
}

我从来没有得到任何控制台输出.

I'm never getting any console output.

我尝试以不同的方式实例化会话,例如

I have tried instantiating the session in different ways, like

 [NSURLSession sharedSession]

没有用,

以及尝试在不同线程中执行完成块中的代码

as well as trying to execute the code in the completion block in a different thread

 dispatch_sync(dispatch_get_main_queue(), ^{
   // Completion code goes here
 });

这也不起作用.

我也尝试过不同的 URL.我不知道为什么它不起作用.

I've also tried different URL's. I have no idea why it's not working.

推荐答案

命令行界面默认没有 runloop,因此异步任务无法工作.

A command line interface does not have a runloop by default so asynchronous tasks cannot work.

你必须明确地启动和停止运行循环

You have to start and stop the runloop explicitly

#import <Foundation/Foundation.h>

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        CFRunLoopRef runloop = CFRunLoopGetCurrent();
        NSURLSession* session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
        NSURLSessionDataTask *dataTask = [session dataTaskWithURL:[NSURL URLWithString:@"https://itunes.apple.com/search?term=apple&media=software"] completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
            NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
            NSLog(@"%@", json);
            CFRunLoopStop(runloop);
        }];

        [dataTask resume];
        CFRunLoopRun();
    }
    return 0;
}

您应该处理 dataTask 错误以退出值 != 0

You should handle the dataTask error to exit with a value != 0

这篇关于NSURLSessionDataTask 完成处理程序未在命令行项目中执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-05 23:06