我正在尝试使用NSURLSession上传多个图像。当应用程序在前台运行时工作正常。当应用程序进入后台时,上传过程在上传当前任务后停止。我想在应用程序处于后台时上传所有文件。任何帮助将不胜感激。这是我的代码。
//后台任务配置
-(void) uploadOneByOne:(NSString *)individualpath{
NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:mutableUrlString]];
NSString *requestURL = [NSString stringWithFormat:@"http://myservice/Service.svc/UploadOrdersToDrive?orderFolder=%@",OrderFolderID];
NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:requestURL]];
[request setHTTPMethod:@"POST"];
NSURL *filePath =[NSURL fileURLWithPath:individualpath];
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration backgroundSessionConfiguration:kSessionIdentifier];
defaultSession= [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
NSURLSessionUploadTask *uploadTask =
[defaultSession uploadTaskWithRequest:request
fromFile:filePath];
[uploadTask resume];
}
NSURLSession委派
收到第一个请求回复
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask
didReceiveData:(NSData *)data
{
NSString * str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"Received String %@",str);
NSDictionary *jsonResponseData = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
//FolderID to create next image in same folder.
OrderFolderID =[jsonResponseData
objectForKey:@"OrderFolderID"];
}
创建下一个请求
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task
didCompleteWithError:(NSError *)error
{
if(error == nil)
{
//Remove DetailFist
[orderDetailarray removeObjectAtIndex:0];
if (orderDetailarray.count >0){
ChosenImages *item = [orderDetailarray objectAtIndex:0];
[self uploadOneByOne:item.path ];
}
}
//更新进度条
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task
didSendBodyData:(int64_t)bytesSent
totalBytesSent:(int64_t)totalBytesSent
totalBytesExpectedToSend:(int64_t)totalBytesExpectedToSend{
//update progress bar
}
答案 0 :(得分:0)
可能你没有等到下一个任务开始。根据WiFi和电池状态,用户活动等不同的东西,您在后台排队的下一个任务可以在几分钟......或几个小时内开始。
顺便说一下,我没有看到与completionHandler
实施相关的代码。
不要忘记实施
- (void)application:(UIApplication *)application handleEventsForBackgroundURLSession:(NSString *)identifier completionHandler:(void (^)())completionHandler
在App委托和适当的会话委托中。