socket connection killed after iOS app goes to background

爱⌒轻易说出口 提交于 2019-11-29 07:16:28
Pushpak Narasimhan

You can get a max time of 600 sec(10 min) by using making use of following code in applicationDidEnterBackground:

if ([[UIDevice currentDevice] respondsToSelector:@selector(isMultitaskingSupported)]) { //Check if our iOS version supports multitasking I.E iOS 4
if ([[UIDevice currentDevice] isMultitaskingSupported]) { //Check if device supports mulitasking
    UIApplication *application = [UIApplication sharedApplication]; //Get the shared application instance
    __block UIBackgroundTaskIdentifier background_task; //Create a task object
    background_task = [application beginBackgroundTaskWithExpirationHandler: ^ {
        [application endBackgroundTask: background_task]; //Tell the system that we are done with the tasks
        background_task = UIBackgroundTaskInvalid; //Set the task to be invalid
        //System will be shutting down the app at any point in time now
    }];
    //Background tasks require you to use asyncrous tasks
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        //Perform your tasks that your application requires
        NSLog(@"\n\nRunning in the background!\n\n");
        [application endBackgroundTask: background_task]; //End the task so the system knows that you are done with what you need to perform
        background_task = UIBackgroundTaskInvalid; //Invalidate the background_task
    });
  }
}

Documentation can be found here http://disanji.net/iOS_Doc/#documentation/iPhone/Conceptual/iPhoneOSProgrammingGuide/BackgroundExecution/BackgroundExecution.html

I just implemented the backgroundTaskIdentifier object and Invalidate the background_task to check the time, app was alive and was running 600sec. You can even get the remaining time by using this

NSLog(@"Time remaining: %f", application.backgroundTimeRemaining);

From Apple's IOS Programming Guide

Most applications that enter the background state are moved to the suspended state shortly thereafter. While in this state, the application does not execute any code and may be removed from memory at any time. Applications that provide specific services to the user can request background execution time in order to provide those services.

That at least explains, why the app stops executing. Why your server is still able to communicate with your app for 5 minutes may be, because you set an extra long time out and are not closing the socket connection explicitly on your app entering the background.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!