在后台使用 uploadTaskWithRequest from File 进行多文件上传



我正在尝试使用 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 Delegate

接收第一个请求响应

 - (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
}  

可能你没有等到下一个任务开始。根据WiFi和电池状态,用户活动等不同因素,您在后台排队的下一个任务可能会在几分钟内开始。或几个小时。顺便说一句,我没有看到与completionHandler实现相关的代码。

不要忘记实施

- (void)application:(UIApplication *)application handleEventsForBackgroundURLSession:(NSString *)identifier completionHandler:(void (^)())completionHandler

在应用委托和相应的会话委托中。

相关内容

  • 没有找到相关文章

最新更新