Loading background when requesting a stream using NSUrlSession in iOS8

Earlier in iOS7, when we try to load a request with a stream in the background, we get the following exception

Application termination due to an uncaught exception "NSGenericException", reason: "Loading tasks into background sessions must be from a file

But in iOS8 there is no exception when we try to download a stream in the background.

Now my question

1) Is loading backgourd with uploadTaskWithStreamedRequest: allowed in iOS8?

2) In iOS8, I use background NSURLConfiguration with uploadTaskWithStreamedRequest . I am using the session task - (void) URLSession: (NSURLSession *): (NSURLSessionTask *) requireNewBodyStream: (void (^) (NSInputStream *)) completeHandler to provide a stream for NSUrlSession. When the application is in the foreground, it works fine and uploads my file to the server. But as soon as the application starts running in the background, the thread terminates and the NSURLSession completes the following error:

Domain Error = NSURLErrorDomain Code = -997 "Lost Connection to Background Transfer Service"

I think that when the application exits in the background, my thread ends. Now my question is, in which runloop should I schedule my Stream or tell me if there is any error in my understanding.

-(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);
}
+1
source share
2 answers

You cannot load streaming tasks using Background Configuration. I only successfully upload data in two cases:

  • Download a task with data stored in the request body.
  • Loading a task from a file. In this case, you will not receive the response body.
+1
source

All Articles