1

以前在 iOS7 中,当我们尝试在后台使用流请求上传时,会出现以下异常

由于未捕获的异常“NSGenericException”而终止应用程序,原因:“后台会话中的上传任务必须来自文件”

但是在 iOS8 中,当我们尝试在后台使用流上传时也不例外。

现在我的问题是

1)iOS8中是否允许使用uploadTaskWithStreamedRequest进行backgourd上传?

2) 在 iOS8 中,我使用背景 NSURLConfiguration 和uploadTaskWithStreamedRequest。我正在使用-(void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task needNewBodyStream:(void (^)(NSInputStream *))completionHandler向 NSUrlSession 提供流。当应用程序处于前台时,它工作正常并将我的文件上传到服务器。但是一旦应用程序在后台运行,流就会结束并且 NSURLSession 完成并出现以下错误

错误域=NSURLErrorDomain 代码=-997“丢失与后台传输服务的连接”

我认为当应用程序进入后台时,我的流就结束了。现在我的问题是我应该在哪个 runloop 中安排我的 Stream 或者让我知道我的理解是否有任何错误。

-(void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task needNewBodyStream:(void (^)(NSInputStream *))completionHandler
{
    // Open producer/consumer streams.  We open the producerStream straight
    // away.  We leave the consumerStream alone; NSURLConnection will deal
    // with it.
    NSLog(@"%@", [NSThread currentThread]);
    NSInputStream *consStream;
    NSOutputStream *prodStream;
    [NSStream createBoundInputStream:&consStream outputStream:&prodStream bufferSize:SFAMaxBufferLength];
    assert(consStream != nil);
    assert(prodStream != nil);
    self.consumerStream = consStream;
    self.producerStream = prodStream;
    self.producerStream.delegate = self;
    [self.producerStream scheduleInRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];
    [self.producerStream open];
    // Set up our state to send the body prefix first.
    self.buffer = [self.bodyPrefixData bytes];
    self.bufferLimit = [self.bodyPrefixData length];
    completionHandler(self.consumerStream);
}
4

2 回答 2

2

您无法使用后台配置上传流式任务。我仅在两种情况下成功上传数据:

  1. 使用存储在请求正文中的数据下载任务。
  2. 从文件上传任务。在这种情况下,您将不会收到响应正文。
于 2015-02-10T16:41:40.283 回答
0

您可以在后台上传多部分文件 - 只是这不是直截了当的。参考:uploadTaskWithStreamedRequest 中的 AFNetworking 错误

于 2015-08-18T04:34:03.123 回答