当我切换到发布构建配置时,NSURLSessionDataTaskcompletionHandler不再执行

发布于 2025-01-09 05:31:12 字数 2802 浏览 2 评论 0原文

我构建了一个简单的命令行工具,它使用 NSURLSessionDataTask 获取一些数据。现在我已经完成编码,我发现当我切换到 Xcode 中的发布构建配置时,可执行文件挂起。我正在使用 while 循环等待 NSURLSessionData finishHandler 完成。 while 循环适用于 Debug,但不适用于 Release。相反,如果我使用 [NSThread sleepForTimeInterval:2.0f] 暂停代码以等待completionHandler 完成,则在发布和调试中一切正常,但我更喜欢使用 while 循环,因为它更快、更符合逻辑。

这是相关代码:

// Configure Session
NSURLSessionConfiguration *config = [NSURLSessionConfiguration ephemeralSessionConfiguration];
// Authentication for the session
NSString *auth = [[[NSString stringWithFormat:@"%@:%@",cpanelUser, WxWaPpIUPA] dataUsingEncoding:NSUTF8StringEncoding] base64EncodedStringWithOptions:0];
config.HTTPAdditionalHeaders = @{@"Authorization":[NSString stringWithFormat:@"Basic %@",auth]};
NSURLSession *session = [NSURLSession sessionWithConfiguration:config];

// Run Data Task
__block BOOL taskComplete = NO;
NSURLSessionDataTask *task = [session dataTaskWithURL:urlComponents.URL
                                        completionHandler:
    ^(NSData *data, NSURLResponse *response, NSError *error) {
    
    if(error) {
        // *HTTP response failed
        NSInteger statusCode = [(NSHTTPURLResponse *)response statusCode];
        [result addEntriesFromDictionary:queryReturn(EMAIL_TYPE_ERROR, [NSString stringWithFormat:@"There was a connection issue with the session data task.<br><br>Error: %@ HTTP Status Code for the <a href='%@'>URL</a> requested: %li.",error,urlComponents.URL,statusCode])];
    } else {
        NSError *jsonError;
        NSDictionary *jsonObject = (NSDictionary *)[NSJSONSerialization JSONObjectWithData:data
        options:NSJSONReadingAllowFragments
          error: &jsonError];
        
        if(!jsonObject){
            // *JSON parsing Error
            [result addEntriesFromDictionary:queryReturn(EMAIL_TYPE_ERROR, [NSString stringWithFormat:@"There was an error while parsing the JSON data returned from cPanel.<br><br>Error: %@",jsonError])];
        } else {
            if([jsonObject[@"cpanelresult"] objectForKey:@"error"] != nil) {
                // *cPanel API returned an Error
                NSString *cpanelError = [NSString stringWithFormat:@"%@",[jsonObject[@"cpanelresult"] objectForKey:@"error"]];
                if(verbose) NSLog(@"cPanel API 2 Error: %@\n", cpanelError);
                [result addEntriesFromDictionary:queryReturn(EMAIL_TYPE_ERROR, [NSString stringWithFormat:@"cPanel API 2 returned an error while executing function '%@'.<br><br>Error: %@",funct, cpanelError])];
            } else {
                [result addEntriesFromDictionary:jsonObject];
            }
        }
    }
    taskComplete = YES;
}];
[task resume];

// Wait for task to complete
while(!taskComplete);
//[NSThread sleepForTimeInterval:2.0f];

I built a simple command line tool that fetches some data using an NSURLSessionDataTask. Now that I'm done coding, I find that the executable hangs when I switch to the Release build configuration in Xcode. I'm using a while loop that waits for the NSURLSessionData completionHandler to complete. The while loop works with Debug, but not with Release. If instead I use [NSThread sleepForTimeInterval:2.0f] to pause the code to wait for the completionHandler to complete, everything works fine in both Release and Debug, however I'd prefer to use the while loop as it is quicker and more logical.

Here is the relevant code:

// Configure Session
NSURLSessionConfiguration *config = [NSURLSessionConfiguration ephemeralSessionConfiguration];
// Authentication for the session
NSString *auth = [[[NSString stringWithFormat:@"%@:%@",cpanelUser, WxWaPpIUPA] dataUsingEncoding:NSUTF8StringEncoding] base64EncodedStringWithOptions:0];
config.HTTPAdditionalHeaders = @{@"Authorization":[NSString stringWithFormat:@"Basic %@",auth]};
NSURLSession *session = [NSURLSession sessionWithConfiguration:config];

// Run Data Task
__block BOOL taskComplete = NO;
NSURLSessionDataTask *task = [session dataTaskWithURL:urlComponents.URL
                                        completionHandler:
    ^(NSData *data, NSURLResponse *response, NSError *error) {
    
    if(error) {
        // *HTTP response failed
        NSInteger statusCode = [(NSHTTPURLResponse *)response statusCode];
        [result addEntriesFromDictionary:queryReturn(EMAIL_TYPE_ERROR, [NSString stringWithFormat:@"There was a connection issue with the session data task.<br><br>Error: %@ HTTP Status Code for the <a href='%@'>URL</a> requested: %li.",error,urlComponents.URL,statusCode])];
    } else {
        NSError *jsonError;
        NSDictionary *jsonObject = (NSDictionary *)[NSJSONSerialization JSONObjectWithData:data
        options:NSJSONReadingAllowFragments
          error: &jsonError];
        
        if(!jsonObject){
            // *JSON parsing Error
            [result addEntriesFromDictionary:queryReturn(EMAIL_TYPE_ERROR, [NSString stringWithFormat:@"There was an error while parsing the JSON data returned from cPanel.<br><br>Error: %@",jsonError])];
        } else {
            if([jsonObject[@"cpanelresult"] objectForKey:@"error"] != nil) {
                // *cPanel API returned an Error
                NSString *cpanelError = [NSString stringWithFormat:@"%@",[jsonObject[@"cpanelresult"] objectForKey:@"error"]];
                if(verbose) NSLog(@"cPanel API 2 Error: %@\n", cpanelError);
                [result addEntriesFromDictionary:queryReturn(EMAIL_TYPE_ERROR, [NSString stringWithFormat:@"cPanel API 2 returned an error while executing function '%@'.<br><br>Error: %@",funct, cpanelError])];
            } else {
                [result addEntriesFromDictionary:jsonObject];
            }
        }
    }
    taskComplete = YES;
}];
[task resume];

// Wait for task to complete
while(!taskComplete);
//[NSThread sleepForTimeInterval:2.0f];

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文