Search code examples
iosafnetworking-2

AFNetworking 2.0 - request doesn't go into success block when app in background


  • I am using AFNetworking 2.0 for my project. It's simple that I just send some request to the server and the server return some JSON for me.
  • For testing it, I marked some debug mark in success block of AFNetworking POST method. The problem is when the app is in the foreground and when the app receive the response from the server, xCode can stop at the debug marks in the success and failure block. But when I make the request then bring the app to background (press Home button), the debug never go into the blocks.
  • It seems like that they paused when the app is in background, because when the app is in foreground again, the debug immediately go into the block and I got the response.

Am I missing something? Cause I want the app to receive the response and do some stuffs even if it's in the background. Here's what I use in my app:

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSDictionary *parameters = /*generate the parameters*/;
NSURL *filePath = [NSURL fileURLWithPath:@"imageName.png"];
[manager POST:@"http://example.com/resources.json" parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
    [formData appendPartWithFileURL:filePath name:@"image" error:nil];
} success:^(AFHTTPRequestOperation *operation, id responseObject) {
    NSLog(@"Success: %@", responseObject);

//debug here
//Told the app to stop the Loading View, save response to DB

} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    NSLog(@"Error: %@", error);

//debug here
//Told the app to stop the Loading View and try again sometimes

}];

Solution

  • It's my bad. I forgot to tell the app to keep running when it enter background. I added these codes into my project:

    UIBackgroundTaskIdentifier backgroundTask = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
        [[UIApplication sharedApplication] endBackgroundTask:backgroundTask];
    }];
    

    And when the app go into background:

    [[UIApplicatioz sharedApplication] endBackgroundTask:backgroundTask];