IOS-Swift开发基础——后台下载
使用Alamofire下载某文件:
// download to default pathlet destination = Alamofire.Request.suggestedDownloadDestination()let url = "http://7xi8t0.com2.z0.glb.clouddn.com/o_1ah8n9j7c1ltmo7g1hpn3asi9m.apk"Alamofire.download(.GET, url, destination: destination).progress { (bytes, totalBytes, totalBytesExpected) in print(bytes, totalBytes, totalBytesExpected) let percent: Float = Float(totalBytes) / Float(totalBytesExpected) print(">> ", percent) dispatch_async(dispatch_get_main_queue(), { self.downloadProgress.progress = percent });}.response { (request, response, _, error) in if let error = error { print("Error:", error) self.sendLocalNotification("Download Error!") } else { print("Success:", response) self.sendLocalNotification("Download Success!") }}
正常程序进入后台后,会在几秒内停止工作;要想申请更长的时间,(最长10分钟),需要用到beginBackgroundTaskWithExpirationHandler/endBackgroundTask
AppDelegate中添加:
var backgroundTask: UIBackgroundTaskIdentifier!func applicationDidEnterBackground(application: UIApplication) { if self.backgroundTask != nil { application.endBackgroundTask(self.backgroundTask) self.backgroundTask = UIBackgroundTaskInvalid } application.beginBackgroundTaskWithExpirationHandler { application.endBackgroundTask(self.backgroundTask) self.backgroundTask = UIBackgroundTaskInvalid }}
具体代码:github
关键字:swift, alamofire
版权声明
本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处。如若内容有涉嫌抄袭侵权/违法违规/事实不符,请点击 举报 进行投诉反馈!