使用NSURLSessionUploadTask从资产库上传多张照片的最佳方法是什么?
我现在使用NSURLSession后台上传。下面是我使用的代码:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0]; //getting path of documents directory.
NSString *documentsPath = [documentsDirectory stringByAppendingPathComponent:@"tempFile.dat"]; //appending file name to documents path.
ALAssetsLibraryAssetForURLResultBlock resultblock = ^(ALAsset *myasset)
{
ALAssetRepresentation *rep = [myasset defaultRepresentation];
Byte *buffer = (Byte*)malloc(rep.size);
NSUInteger buffered = [rep getBytes:buffer fromOffset:0.0 length:rep.size error:nil];
NSData *data = [NSData dataWithBytesNoCopy:buffer length:buffered freeWhenDone:YES];
_totalBytesToSend += buffered;
[_dataArray addObject:data];
};
ALAssetsLibraryAccessFailureBlock failureblock = ^(NSError *myerror)
{
DLog(@"Can't get image - %@",[myerror localizedDescription]);
};
ALAssetsLibrary* assetslibrary = [[ALAssetsLibrary alloc] init];
//work needed here
for (NSURL *url in _urlArray) {
if(url != nil)
{
[assetslibrary assetForURL:url
resultBlock:resultblock
failureBlock:failureblock];
}
}
dispatch_async(dispatch_get_main_queue(), ^(void){
for (NSData *data in _dataArray) {
if(![data writeToFile:documentsPath atomically:YES])
{
DLog(@"Saving image failed");
}
//Prepare upload request
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"my url here"]];
[request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
[request setHTTPMethod:@"POST"];
[request addValue:[[DTETokenManager sharedManager] loginToken] forHTTPHeaderField: @"X-CSRF-Token"];
_uploadTask = [_session uploadTaskWithRequest:request fromFile:[NSURL URLWithString:[NSString stringWithFormat:@"file://%@", documentsPath]]];
[_uploadTask resume];
}
});
这是一个好方法吗?我面临的一个问题是,我无法正确地更新进度条,我打算在其中显示整个上传过程的进度。我使用下面的代码:
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didSendBodyData:(int64_t)bytesSent totalBytesSent:(int64_t)totalBytesSent totalBytesExpectedToSend:(int64_t)totalBytesExpectedToSend
{
//Progress reportpo
_totalByteSent += totalBytesSent;
if(_totalBytesToSend && _totalByteSent)
{
[[NSNotificationCenter defaultCenter] postNotificationName:kBytesUploaded object:nil userInfo:[NSDictionary dictionaryWithObject:[NSNumber numberWithDouble:(double)totalBytesSent/(double)totalBytesExpectedToSend] forKey:NOTIFICATION_PAYLOAD]];
}
}
正如预期的那样,进度更新根本不合适:)
请指出一个更好的方法,因为我发现很难找到合适的教程来处理上传。还有很多解释后台下载的原因
由于我没有从这里得到任何响应,我最终将进度条全部转储在一起,并添加一个活动指示器,当所有下载完成时停止旋转