-1

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

1 回答 1

0

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

不要忘记执行

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

在 App 委托和适当的会话委托中。

于 2015-02-04T10:16:29.700 回答