且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在后台会话中下载 AlamoFire

更新时间:2021-07-14 22:11:59

更新

基于这个惊人的教程,我在 GitHub上整理了一个示例项目>.它有一个后台会话管理的例子.

Update

Based on this amazing tutorial, I have put together an example project available on GitHub. It has an example for background session management.

根据 Apple 的 URL 加载系统编程指南:

According to Apple's URL Loading System Programming Guide:

在 iOS 和 OS X 中,当用户重新启动您的应用时,您的应用应立即使用与任何有未完成任务的会话相同的标识符应用程序上次运行,然后为每个应用程序创建一个会话配置对象.这些新会话同样是自动的与正在进行的后台活动重新关联.

In both iOS and OS X, when the user relaunches your app, your app should immediately create background configuration objects with the same identifiers as any sessions that had outstanding tasks when your app was last running, then create a session for each of those configuration objects. These new sessions are similarly automatically reassociated with ongoing background activity.

显然,通过使用适当的后台会话配置实例,您的下载将永远不会不断变化".

So apparently by using the appropriate background session configuration instances, your downloads will never be "in flux".

我还发现这个答案真的很有帮助.

I have also found this answer really helpful.

来自 Alamofire 的 GitHub 页面:

From Alamofire's GitHub page:

应用程序可以创建后台管理器和临时管理器会话,以及自定义默认会话的新管理器配置,例如默认标头 (HTTPAdditionalHeaders) 或超时间隔(timeoutIntervalForRequest).

Applications can create managers for background and ephemeral sessions, as well as new managers that customize the default session configuration, such as for default headers (HTTPAdditionalHeaders) or timeout interval (timeoutIntervalForRequest).

默认情况下,***方法使用具有默认会话配置的共享 Manager 实例.但是,您可以创建具有后台会话配置的管理器,如下所示:

By default, top level methods use a shared Manager instance with default session configuration. You can however create a manager with background session configuration like so:

let configuration = NSURLSessionConfiguration.backgroundSessionConfigurationWithIdentifier("com.example.app.background")
let manager = Alamofire.Manager(configuration: configuration)

然后您可以使用此 Manager 实例发出请求.

You can then make requests using this Manager instance.

manager.startRequestsImmediately = true
let request = NSURLRequest(URL: NSURL(string: "your.url.here")!)
manager.request(request)

通过查看它的实现,它还有一个属性叫做backgroundCompletionHandler,所以你可以添加一个完成块:

By looking at its implementation, it also has a property called backgroundCompletionHandler, so you can add a completion block:

manager.backgroundCompletionHandler = {
        // do something when the request has finished
    }