即使手机被锁定也可以进行后台下载 [英] Background downloading even if the phone gets locked

查看:114
本文介绍了即使手机被锁定也可以进行后台下载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为iPhone实现一个应用程序,该应用程序应该简单地从网络上下载一些内容.该下载量很大,因此我将下载实现为后台任务,以使用户有机会在下载时用手机进行其他操作.我的问题是,如果用户按下锁定按钮(或自动锁定启动),则会调用AppDelegate中的applicationWillResignActive:,并且大约十秒钟后,下载将被中止,因为手机没有进入后台,而是保持不活动状态. >

我的问题是我做错了什么?即使手机已锁定,如何确保下载继续进行?

提前谢谢.

解决方案

您需要使用后台任务块来包围下载代码,如下所示:

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

根据其他一些帖子,这将给您10分钟的时间在后台执行代码...

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.

解决方案

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...

这篇关于即使手机被锁定也可以进行后台下载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆