使用AFNetworking 2.0时,我遇到了一些关于流媒体请求的挑战.
我想将大量文件(~50MB)上传到服务器,并且请求必须要流式传输. (否则app会因内存压力而崩溃)
我已尝试过各种方法在AFNetworking 2.0中做到这一点而没有任何成功.
这就是我目前正在做的事情:
NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:baseServiceUrl parameters:nil constructingBodyWithBlock:^(id formData) {
int imageIndex = 0;
for (NSURL *tempFileUrl in tempFilesUrlList) {
NSString* fileName = [NSString stringWithFormat:@"image%d",imageIndex];
NSError *appendError = nil;
[formData appendPartWithFileURL:tempFileUrl name:fileName error:&appendError];
imageIndex++;
}
} error:&error];
AFHTTPRequestOperation *requestOperation = nil;
requestOperation = [manager HTTPRequestOperationWithRequest:request success:^(AFHTTPRequestOperation *operation,id responSEObject) {
DLog(@"Uploading files completed: %@\n %@",operation,responSEObject);
} failure:^(AFHTTPRequestOperation *operation,NSError *error) {
DLog(@"Error: %@",error);
}];
[requestOperation setUploadProgressBlock:^(NSUInteger bytesWritten,long long totalBytesWritten,long long totalBytesExpectedToWrite) {
double percentDone = (double)totalBytesWritten / (double)totalBytesExpectedToWrite;
DLog(@"progress updated(percentDone) : %f",percentDone);
}];
[requestOperation start];
这工作正常,但它不流.如果请求太大,它准备内存中的请求可能会崩溃.我曾尝试使用原生套接字和流,但Apple表示他们可能因此而拒绝该应用.
我尝试过的另一种方法是:
AFHTTPSessionManager* manager = [AFHTTPSessionManager manager];
NSString *appID = [[NSBundle mainBundle] bundleIdentifier];
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration backgroundSessionConfiguration:appID];
NSURL* serviceUrl = [NSURL URLWithString:baseServiceUrl];
manager = [manager initWithBaseURL:serviceUrl sessionConfiguration:configuration];
NSURLSessionDataTask *uploadFilesTask = [manager POST:baseServiceUrl parameters:nil constructingBodyWithBlock:^(id formData) {
int imageIndex = 0;
for (NSURL *tempFileUrl in tempFilesUrlList) {
NSString* fileName = [NSString stringWithFormat:@"image%d",imageIndex];
NSError *appendError = nil;
[formData appendPartWithFileURL:tempFileUrl name:fileName error:&appendError];
imageIndex++;
}
} success:^(NSURLSessionDataTask *task,id responSEObject) {
DLog(@"Files uploaded successfully: %@\n %@",task,responSEObject);
} failure:^(NSURLSessionDataTask *task,error);
}];
[progressBar setProgressWithUploadProgressOfTask:uploadFilesTask animated:true];
但这给了我运行时错误说:
Terminating app due to uncaught exception ‘NSGenericException’,
reason: ‘Upload tasks in background sessions must be from a file’
*** First throw call stack: ( 0 CoreFoundation 0x02cc75e4 __exceptionPreprocess + 180 1 libobjc.A.dylib
0x02a4a8b6 objc_exception_throw + 44 2 CFNetwork
0x0459eb6c -[__NSCFBackgroundSessionBridge
uploadTaskForRequest:uploadFile:bodyData:completion:] + 994 3
CFNetwork 0x045f2f37 -[__NSCFURLSession
uploadTaskWithStreamedRequest:] + 73
(必须是流媒体,并且能够在后台继续)