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];
}];