iosnetwork-programmingios-background-mode

No response from localhost in iOS Background Mode


The application runs on a iOS mobile device (iPhone\iPad) local server on localhost:25989, when go to the browser, we send a few request http://localhost:25989 but server (application) does not send a response until we return to the application.

This situation is shown in the picture down below

enter image description here

UPD: Application already configure for work in Background enter image description here

Question: How to organize the application code for that working in Background Mode the server can return an answer from localhost:25989?


Solution

  • NOTE: Code is Broken for iOS 13+, many part now deprecated by Apple. BGTaskSheduler new class replacing UIBackground.

    I solved my problem, by use the following code in my AppDelegate.m file to keep the server running in the background:

    ...
    bool *isBackground = NO;
    
    - (void)extendBackgroundRunningTime
    {
        if (isBackground != UIBackgroundTaskInvalid)
            return;
    
        NSLog(@"Attempting to extend background running time");
        __block Boolean self_terminate = NO; //Do not suspend the application in the background
    
        isBackground = [[UIApplication sharedApplication] 
        beginBackgroundTaskWithName:@"BackgroundTask" expirationHandler:^
        {
            if (self_terminate)
            {
                NSLog(@"Background task expired by iOS");
                [[UIApplication sharedApplication] endBackgroundTask:isBackground];
                isBackground = UIBackgroundTaskInvalid;
            }
        }];
    
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0),^    
        {
            NSLog(@"Background task started");
            while (true)
            {
                if(!isBackground)
                {
                    [[UIApplication sharedApplication] endBackgroundTask:isBackground];
                    isBackground = UIBackgroundTaskInvalid;
                    break;
                }
                if(self_terminate)
                    NSLog(@"background time remaining: %8.2f", [UIApplication sharedApplication].backgroundTimeRemaining);
                [NSThread sleepForTimeInterval:2];
            }
        });
    }
    
    - (void)applicationDidEnterBackground:(UIApplication *)application {   
        NSLog(@"applicationDidEnterBackground");
        [self extendBackgroundRunningTime];  //Call function for upadte time
        NSLog(@"Time Remaining: %f", [[UIApplication sharedApplication] backgroundTimeRemaining]);
    }
    
    
    - (void)applicationWillEnterForeground:(UIApplication *)application {
        isBackground = NO;
        NSLog(@"Enter Foreground");
    }
    

    Now application server can send response from Foreground\Background correctly

    Result: enter image description here