Can we call the method after the application has been minimized?

前端 未结 1 2021
后悔当初
后悔当初 2021-01-05 07:52

iOS

Can we call the method after the application has been minimized?

For example, 5 seconds after was called applicationDidEnterBackground:.

相关标签:
1条回答
  • 2021-01-05 08:20

    You can use the background task APIs to call a method after you've been backgrounded (as long as your task doesn't take too long - usually ~10 mins is the max allowed time).

    iOS doesn't let timers fire when the app is backgrounded, so I've found that dispatching a background thread before the app is backgrounded, then putting that thread to sleep, has the same effect as a timer.

    Put the following code in your app delegate's - (void)applicationWillResignActive:(UIApplication *)application method:

    // Dispatch to a background queue
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
    
        // Tell the system that you want to start a background task
        UIBackgroundTaskIdentifier taskID = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
            // Cleanup before system kills the app
        }];
    
        // Sleep the block for 5 seconds
        [NSThread sleepForTimeInterval:5.0];
    
        // Call the method if the app is backgrounded (and not just inactive)
        if (application.applicationState == UIApplicationStateBackground)
            [self performSelector:@selector(test)];  // Or, you could just call [self test]; here
    
        // Tell the system that the task has ended.
        if (taskID != UIBackgroundTaskInvalid) {
            [[UIApplication sharedApplication] endBackgroundTask:taskID];
        }
    
    });
    
    0 讨论(0)
提交回复
热议问题