How keep NSTimer when application entering background?

后端 未结 3 1956
执笔经年
执笔经年 2020-12-15 11:53

I\'m here because a didn\'t find any solutions for my issue :(

I\'m doing an simple application in which i have to send (by socket) some informations to a server (li

3条回答
  •  执念已碎
    2020-12-15 12:25

    You need to read the guide on how to run tasks in the background:

    Background Execution and Multitasking

    Here is my applicationDidEnterBackground for one of my apps. When I put it to the background, it does some disk cache maintenance:

    - (void)applicationDidEnterBackground:(UIApplication *)application {
    
    //As we are going into the background, I want to start a background task to clean up the disk caches
    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                
    
                //I do what i need to do here.... synchronously...                
    
                [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
            });
        }
    }
    

    }

提交回复
热议问题