我有一个完美的下载功能,点击我的按钮,文件正在正确下载。
我想要实现的目标,如果我将应用程序置于后台或在下载文件时更改屏幕,我希望继续下载。目前,如果应用程序处于后台,则下载停止并且用户需要从零重新启动它。
这怎么可能?下面是我的下载功能,我试图添加后台下载但没有成功。
<!DOCTYPE html>
<html>
<head>
<button onclick="generate();">Generate password</button>
</head>
<body>
<p id="pw">
<!-- password should go here -->
</p>
</body>
</html>
和
func createDownloadTask() {
let downloadRequest = URLRequest(url: URL(string: "\(posts[selectedIndexPath].link)")!)
let session = Foundation.URLSession(configuration: URLSessionConfiguration.default, delegate: self, delegateQueue: OperationQueue.main)
downloadTask = session.downloadTask(with: downloadRequest)
downloadTask!.resume()
}
答案 0 :(得分:2)
您需要使用UIBackgroundTaskIdentifier。您可以使用beginBackgroundTask在后台启动一些任务,请参阅: https://developer.apple.com/reference/uikit/uiapplication/1623031-beginbackgroundtask。 系统会给你一些时间,你可以完成你的任务。如果时间到期,您将收到处理程序。请参阅我用于上传图像的示例
static var backgroundUpload:UIBackgroundTaskIdentifier?
static func praiseCollegue(praiseCollegueId:Int,image:UIImageView,praisedBy:Int,praiseText:String,praiseCategory:Int,successBlock: (()->())?,errorBlock: (()->())?){
backgroundUpload = UIApplication.shared.beginBackgroundTask(expirationHandler: {
if let task = self.backgroundUpload{
UIApplication.shared.endBackgroundTask(task)
}
})
let url = NSURL(string: "someUrl")
let request = NSMutableURLRequest(url: url! as URL)
request.httpMethod = "POST"
request.setValue(InfoManager.sharedInstance.tokenInfo?.accessToken, forHTTPHeaderField: "AccessToken")
let session = URLSession.shared
let task = session.dataTask(with: request as URLRequest) {
(
data, response, error) in
if let responseData = data{
do {
if let dict = try JSONSerialization.jsonObject(with: responseData, options: []) as? [String: AnyObject]{
if let errorCode = dict["errorCode"] as? Int{
if(errorCode == 1){
successBlock?()
if let task = self.backgroundUpload{
UIApplication.shared.endBackgroundTask(task)
}
}
else{
errorBlock?()
if let task = self.backgroundUpload{
UIApplication.shared.endBackgroundTask(task)
}
}
}
}
}
}
}
task.resume()
}