我在新应用程序中使用Alamofire(基于Alamofire的下载管理器示例)我需要对使用后台会话下载文件进行一些澄清。 我需要覆盖SessionDelegate以使其有效吗? 或者只是 backgroundCompletionHandler ?
I am using Alamofire within a new app (A Download Manager Sample based on Alamofire) I need some clarifications about downloading files using the background session. I need to override SessionDelegate to get it works? Or just backgroundCompletionHandler?
通常使用Alamofire处理后台下载的步骤是什么? 我如何处理我的应用程序相关的情况,下载量不断变化。 谢谢和问候。
Typically what are the steps to handle downloads in background using Alamofire? And how can I handle the case where my app is relauch, with downloads in flux. Thanks and regards.
推荐答案更新
基于在这个惊人的教程,我已经在 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加载系统编程指南:
在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)或超时interval(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 ins使用默认会话配置。但是,您可以创建一个具有后台会话配置的经理,如下所示:
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 }更多推荐
AlamoFire下载后台会话
发布评论