Background downloading even if the phone gets locked

折月煮酒 提交于 2019-12-02 10:20:27

问题


I am trying to implement an application for iPhone that should simply download some content out of the web. This download is quite big, so I implemented the download as a background task to give the user the chance to do some other stuff with his phone while downloading. My problem is that if the user pushes the lock button (or if auto lock kicks in) the applicationWillResignActive: in the AppDelegate is called and after about ten seconds the download is aborted because the phone does not enter background and just stays inactive.

My question is what am I doing wrong? How can I ensure that the download is continued, even if the phone is locked?

Thanks in advance.


回答1:


You need to surround the downloading code with background task block like this:

UIApplication* app = [UIApplication sharedApplication];
        UIBackgroundTaskIdentifier bgTask = [app beginBackgroundTaskWithExpirationHandler:^{
            //here you need to finish what you are doing evven if you've not finished yet, otherwise your app will be killed
            [app endBackgroundTask:bgTask];
        }];

        //here comes your downloading code

        [app endBackgroundTask:bgTask];

This will give you 10 minutes(according to some other posts) to execute code in background...



来源:https://stackoverflow.com/questions/8294735/background-downloading-even-if-the-phone-gets-locked

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!