Search code examples
iosobjective-capple-push-notificationsbackground-processnsurlsession

iOS: NSURLSession is not working everytime when launched in background (with silent push nofitication)


If I call the NSURLSession when the app is in the background with push notification, the response is received may be only one time a three.

 NSLog(@"SEND: LAUNCH FUNCTION!!!!");
    NSURLSession *session = [NSURLSession sharedSession];
    [[session dataTaskWithURL:[NSURL URLWithString:url_string]
            completionHandler:^(NSData *data,
                                NSURLResponse *response,
                                NSError *error) {
                // handle response
if (error == nil) {
        NSLog(@"SEND: RESPONSE FUNCTION GOOD!!!!");
        NSMutableArray* responseArray = [NSJSONSerialization JSONObjectWithData:data options:0 error:NULL];
        dispatch_async(dispatch_get_main_queue(), ^{
            [self parseAndAddLovAll:responseArray toArray:self.objects];
        });
    }
    else
    {
        NSLog(@"SEND: RESPONSE FUNCTION BAD!!!!");
    }
            }] resume];

(If I call the NSURLSession when the app is active, no problem, it works every time).

EDIT:

We can see in that video that when I push the 1ST time, it launches the NSURLSession, without answer. If I click a 2ND time, the answer of the 1ST appears, followed by the answer of the 2ND one.

*SEND: LAUNCH FUNCTION!!!!* =>** launch the NSURLSession.  
*SEND: RESPONSE FUNCTION GOOD!!!!*** => Response ok from the NSURLSession.  
*SEND: RESPONSE FUNCTION BAD!!!!*** => Response not ok from the NSURLSession.  
*SEND: FINISHED!!!!*** => Download execution finished with success. 

I put a demo in a video:

Video

EDIT:

Call of the function:  
      dispatch_queue_t downloadQueue = dispatch_queue_create("downloader", NULL);
      dispatch_async(downloadQueue, ^{
                  ListOfValueSync * lovSync = [[ListOfValueSync alloc] init];

            // Synchronization
            BOOL ret = [lovSync getAllListOfValueAll];
            });

What could cause that problem?


Solution

  • I think you have a problem with your call of the function. You cannot use your download queue in this case.

    Instead of this, please use dispatch_main