Friday, 5 October 2018

ApplicationWillTerminate NSURLSession Possible?

I am attempting to do a quick POST via NSURLSession at application termination. Application termination is defined as the user swipes it out when on home screen. Furthermore, applicationWillTerminate is demonstratively called (so thats not in question).

My intent is to inform the server that this user is now going offline.

This however, does not work .. as I don't receive a POST on my backend. I am trying to figure out why this doesn't work.. or even if it should? According to apple docs, this should work if it can execute within 5 seconds.. although I don't even have a completion handler so it should be executed. Any help or advice will be greatly appreciated.

My implementation is as follows (for reference).

- (void)applicationWillTerminate:(UIApplication *)application {

    NSMutableDictionary * gatherAllInputs = [[NSMutableDictionary alloc] initWithObjectsAndKeys:
                                             @"blah@df.com, @"emailEntry",
                                             @"False", @"isPersonAvailable",
                                             nil];

    NSError *error;
    NSData *gatherAllInputsJSON = [NSJSONSerialization dataWithJSONObject:gatherAllInputs options:0 error:&error];

    NSString* theDataSentToServer;
    theDataSentToServer = [[NSString alloc] initWithData:gatherAllInputsJSON encoding:NSUTF8StringEncoding];

    NSURLSessionConfiguration *sessionConfiguration = [NSURLSessionConfiguration defaultSessionConfiguration];
    NSURLSession *postingSession = [NSURLSession sessionWithConfiguration:sessionConfiguration];

    NSURL *url = [NSURL URLWithString:@"https://blahblahblah.com/someblah"];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];

    [request setHTTPMethod:@"POST"];
    [request setHTTPBody:[theDataSentToServer dataUsingEncoding:NSUTF8StringEncoding]];

    NSURLSessionDataTask *postSomething = [postingSession dataTaskWithRequest:request];
    [postSomething resume]; 
    NSLog(@"Got here!"); //<-- THIS GETS OUTPUTTED.. SO I KNOW THIS CODE IS BEING CALLED!

}



from ApplicationWillTerminate NSURLSession Possible?

No comments:

Post a Comment