在后台下载并完成后唤醒应用 [英] Downloading in background and waking app when finished

查看:130
本文介绍了在后台下载并完成后唤醒应用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用配置为后台会话的URLSession下载一些文件.下载完成后,我将使用:

I use URLSession configured as background session to download some files. When download finishes I use:

func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL)

移动下载的文件.一切正常,除了当应用程序在后台运行时不调用此函数.在应用程序还原到前台后立即调用它,但是我希望系统在文件下载后唤醒我的应用程序.有什么方法可以做到这一点?

to move downloaded file. Everything works fine, except that when app is in the background this function is not being called. It's called right after app is restored to foreground, but I would like the system to wake my app after file is downloaded. Is there some way to do this?

推荐答案

确实有:)

您可能需要在设置中进行一些更改.

You probably need to change a few things in your setup.

首先,您使用的URLSessionConfiguration应该是background类型,如下所示:

First the URLSessionConfiguration you use should be of type background like so:

URLSessionConfiguration.background(withIdentifier: "your.unique.id.here")

然后,在您的AppDelegate中,您需要实现此方法:

Then, in your AppDelegate you need to implement this method:

func application(_ application: UIApplication, handleEventsForBackgroundURLSession identifier: String, completionHandler: @escaping () -> Void)

在其中进行存储completionHandler之类的操作,以便以后可以使用.

Where you do something like store the completionHandler so it can be used later on.

最后,通常在哪里进行完成下载"魔术...通常在这里:

And finally, where you normally do your "done downloading" magic... typically here:

 func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL)

您需要检查completionHandler是否存在,如果存在,请调用它.

You need to check for the presence of a completionHandler and if present, invoke that.

上面的最后两位似乎有点...呵呵???所以这是一个例子.

The last two bits of the above may seem a bit...huh?? so here is an example.

AppDelegate中,您可以为completionHandler定义一个可选内容,以便以后将其存储:

In your AppDelegate you can define an optional for the completionHandler so you can store it for later on:

var backgroundSessionCompletionHandler: (() -> Void)?

然后该方法如下所示:

func application(_ application: UIApplication, handleEventsForBackgroundURLSession identifier: String, completionHandler: @escaping () -> Void) {
    if identifier == "your.unique.id.here" {
        backgroundSessionCompletionHandler = completionHandler
    }
}

然后您公正"需要在处理完下载的文件后致电给您,您可以这样操作:

And then you "just" need to call that once you are done processing the downloaded file, which you can do like this:

if  let appDelegate = UIApplication.shared.delegate as? AppDelegate,
    let completionHandler = appDelegate.backgroundSessionCompletionHandler {
        appDelegate.backgroundSessionCompletionHandler = nil
        OperationQueue.main.addOperation {
            completionHandler()
        }
    }

另外,请查看本教程.

希望对您有帮助.

这篇关于在后台下载并完成后唤醒应用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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