NSURLSessionDataTask not executing the completion handler block

后端 未结 2 1357
广开言路
广开言路 2021-01-04 20:46

I am trying to pull some data from my local node server. The server is getting the get request and logging it, but for some reason my iOS app will not execute any of the cod

2条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-04 21:45

    try this magic:

    static NSURLSession* sharedSessionMainQueue = nil;
    if(!sharedSessionMainQueue){
        sharedSessionMainQueue = [NSURLSession sessionWithConfiguration:nil delegate:nil delegateQueue:[NSOperationQueue mainQueue]];
    }
    
    NSURLSessionDataTask *dataTask =
    [sharedSessionMainQueue dataTaskWithURL:url completionHandler:^(NSData *data,
                                  NSURLResponse *response,
                                  NSError *error){
        //now will be on main thread
    }];
    [dataTask resume];
    

    This gives you the original behavior of NSURLConnection with the completing handler on the main thread so you are safe to update the UI. However, say you would like to parse the download or do some heavy processing, in that case you might benefit from the completion handler on the operation queue's background thread and then using dispatch_sync to the main thread as a final step.

提交回复
热议问题