iOS 后台任务 BackgroundTask

iOS app在被用户切换到后台的时候就会处于挂起状态,如果这时你的应用正在进行一个任务中并且需要额外的时间来完成这个任务。你可以使用UIApplication的beginBackgroundTaskWithName:expirationHandler: 或者beginBackgroundTaskWithExpirationHandler:方法来申请一些额外的时间。

调用两个方法里面的任何一个方法来延迟系统暂停你的应用,并申请额外的时间来完成未完成的任务。注意,当你完成任务后,必须调用endBackgroundTask:方法来告诉系统任务完成了,可以暂停应用了。或者,当你的应用回到前台了,就必须要结束这个任务了。

官方文档

static UIBackgroundTaskIdentifier bgTask;

    bgTask = [application beginBackgroundTaskWithName:@"MyTask" expirationHandler:^{

        // Clean up any unfinished task business by marking where you

        // stopped or ending the task outright.

        [application endBackgroundTask:bgTask];

        bgTask = UIBackgroundTaskInvalid;

    }];

    // Start the long-running task and return immediately.

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

        // Do the work associated with the task, preferably in chunks.

        [application endBackgroundTask:bgTask];

        bgTask = UIBackgroundTaskInvalid;

    });

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容