2015-04-02 78 views
0

錯誤AFNetworking錯誤

Terminating app due to uncaught exception 'NSGenericException', reason: 'Upload tasks in background sessions must be from a file' 

當我嘗試

NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration]; 

configurationNSURLSession做工精細,但當我用波紋管configuration然後應用程序崩潰,並給我的錯誤。

NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration backgroundSessionConfiguration:kBackgroundSessionIdentifier]; 

回答

0

「在後臺會話中上傳任務必須來自文件」的例外本身就是這個問題的答案。

以下行創建後臺會話配置。

[NSURLSessionConfiguration backgroundSessionConfiguration:kBackgroundSessionIdentifier]; 

其慣於支持uploadTaskWithStreamedRequest:,但來自蘋果文檔的背景與上傳文件只工作與uploadTaskWithRequest:request fromFile:

工作。 如果您想要在後臺上傳,請將您的數據寫入文件,然後將URL傳遞給您的後臺會話

+0

當我使用uploadTaskWithRequest:請求fromFile然後回覆是無 – Lalji 2015-04-03 04:24:46

2

您應該使用uploadTaskWithRequest:request fromFile:only。這裏的問題在於你必須將多部分請求內容寫入臨時文件,然後上傳該文件。

您應該使用AFHTTPRequestSerializer:requestWithMultipartFormRequest:writingStreamContentsToFile:completionHandler :. 參考https://github.com/AFNetworking/AFNetworking/issues/1874 - 蘭辛的回答

這裏是爲我工作的示例代碼:

的NSString *文件路徑= [NSTemporaryDirectory()stringByAppendingPathComponent:TEMP_DATA_FILE]。 [data writeToFile:filePath atomically:YES]; NSURL * filepathURL = [NSURL fileURLWithPath:filePath];

NSString *tempFile = [NSTemporaryDirectory() stringByAppendingPathComponent:TEMP_MULTI_PART_REQUEST_FILE]; 
NSURL *filePathtemp = [NSURL fileURLWithPath:tempFile]; 


AFHTTPRequestSerializer *serializer = [AFHTTPRequestSerializer serializer]; 
NSError *error = nil; 

NSMutableURLRequest *request = 
[serializer multipartFormRequestWithMethod:@"POST" URLString:AppendStrings(HOST_FOR_SERVICE_ACCESS, SERVICE_FOR_MULTIPART_UPLOAD) 
           parameters:parameters 
       constructingBodyWithBlock:^(id<AFMultipartFormData> formData) 
{[formData appendPartWithFileURL:filepathURL name:@"data" error:nil];} 
            error:&error ]; 

__block NSProgress *progress = nil; 
[serializer requestWithMultipartFormRequest:request writingStreamContentsToFile:filePathtemp completionHandler:^(NSError *error) { 

    NSURLSessionUploadTask *uploadTask = [self.sessionManager uploadTaskWithRequest:request fromFile:filePathtemp progress:&progress completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {}]; 

[uploadTask resume];

請記住在事後清理臨時文件。

+0

謝謝你,希望我能給你100票! – 2016-06-06 03:17:21