IOS-Swift开发基础——后台下载

使用Alamofire下载某文件:// download to default pathlet destination = Alamofire.Request.suggestedDownloadDestination()let url = "http://7xi8t0.com2.z0.glb.clouddn.com/o_1ah8n9j7c1ltmo7g1hpn3asi9m.

使用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