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

本文介绍如何使用Alamofire进行文件下载,并展示如何配置应用以支持长时间后台下载任务,确保下载过程不会因应用转到后台而中断。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值