使用Alamofire下载某文件:
// download to default path
let 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
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。