【发布时间】:2015-01-26 04:50:00
【问题描述】:
我正在尝试使用 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
}
【问题讨论】:
-
你试过用for循环来调用所有的请求吗??? question about my problem with loop
-
我正在尝试实现相同的目标 - 在应用程序处于后台时上传多个文件。这看起来接近应该工作的东西。已经两年了,你有没有得到这个工作?无论哪种情况,请更新此内容。
标签: ios objective-c nsurlsessionuploadtask