上传数据并发送HTTP请求时,应用程序崩溃

时间:2017-05-08 16:19:01

标签: objective-c

我在Obj-C中非常虚伪。我打电话给callServer,同时我上传了一些数据,如图片,文件...

 -(void) callServer
{
 dispatch_async(dispatchQueue, ^{
        [ServerHandler sendRequest];
    });   
 }    

以下是sendRequest方法,即使用NSURLSession的基本HTTP调用:

+ (void) sendRequest
{

    NSString *url = @"zzz";        

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:escapedURL]];
    [request setHTTPMethod:@"POST"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [request setHTTPBody:postData];


    NSURLSession *session = [NSURLSession sharedSession];

    NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {

        if (error) {
            //...
            }
        } else {

            // ...
        }
    }];
    [postDataTask resume];
}

有时我会崩溃:

#2 Crashed: NSOperationQueue 0x17403e500 :: NSOperation 0x184446990 (QOS: DEFAULT)
   0  libobjc.A.dylib    0x184ee315c objc_msgSend + 25
   1  YOYO               0x100766218 __82-[MyProg callServer]_block_invoke.804 + 383424
   2  YOYO               0x1007679cc __94+[ServerHandler sendRequest]_block_invoke + 389492
   3  CFNetwork          0x186a781fc __75-[__NSURLSessionLocal taskForClass:request:uploadFile:bodyData:completion:]_block_invoke + 32
   4  CFNetwork          0x186a8fef8 __49-[__NSCFLocalSessionTask _task_onqueue_didFinish]_block_invoke + 148

我无法更改上传流程代码,但我可以更改上述代码。

所以问题是如何使我的代码安全a.e.

dispatch_async(dispatchQueue, ^{
        [ServerHandler sendRequest];
    });   
 } 

为什么上传数据(来自Swift)和HTTP请求都保留在同一个线程上?

1 个答案:

答案 0 :(得分:0)

您使用NSURLSessionDataTask而不是URLSessionUploadTask的任何原因 - SesionUploadTask允许在后台上传? https://developer.apple.com/reference/foundation/urlsessionuploadtask