iOS 后台任务(beginBackgroundTask)使用不当导致APP被kill

beginBackgroundTask方法的作用:

为你的app申请额外的后台时间,这是Apple的官方说明:This method requests additional background execution time for your app.

Call this method when leaving a task unfinished might be detrimental to your app’s user experience. 

坑:

先看Apple的文档说明:Each call to this method must be balanced by a matching call to the endBackgroundTask: method.

If you don't call endBackgroundTask: for each task before time expires, the system kills the app. 

意思就是,每次使用beginBackgroundTask,必须配对一个endBackgroundTask,不然app会被杀死。

正确做法:

在开启时,保存UIBackgroundTaskIdentifier,在适时调用endBackgroundTask;另外为了保险,最好在ExpirationHandler:中也调用一次endBackgroundTask。

代码示例:

  __block UIBackgroundTaskIdentifier bgTask = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{

        [[UIApplication sharedApplication] endBackgroundTask:bgTask];

    }];

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容