当我的应用程序进入后台时,Swift 后台下载任务被暂停
我正在尝试创建一个下载任务,即使应用程序位于后台,该任务也将继续下载视频。
所以我按照苹果文档创建了一个 url 会话作为背景。 当我通过点击按钮开始下载过程时,我将打印下载进度。 但是,当应用程序进入后台时,应用程序将停止打印进度。
我想知道我错过了什么,或者误解了什么。
class ViewController: UIViewController {
private lazy var urlSession: URLSession = {
let config = URLSessionConfiguration.background(withIdentifier: "MySession")
config.isDiscretionary = true
config.sessionSendsLaunchEvents = true
return URLSession(configuration: config, delegate: self, delegateQueue:
OperationQueue())
}()
var downloadUrl = "https://archive.rthk.hk/mp4/tv/2021/THKCCT2021M06000036.mp4"
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func downloadButtonTapped(_ sender: UIButton) {
print("DownloadButton Tapped")
let url = URL(string: downloadUrl)
guard let url = url else {
print("Invalid URL")
return
}
let downloadTask = urlSession.downloadTask(with: url)
downloadTask.resume()
}
}
extension ViewController: URLSessionDownloadDelegate, URLSessionDelegate {
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask,
didFinishDownloadingTo location: URL) {
print("Downloaded, location: \(location.path)")
}
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask,
didWriteData bytesWritten: Int64, totalBytesWritten: Int64,
totalBytesExpectedToWrite: Int64) {
let progress = Float(totalBytesWritten) / Float(totalBytesExpectedToWrite)
print("Progress: \(progress)")
}
}
I am trying to create a download task that will continue to download a video even when the application is in the background.
So I followed the apple documentation to create a url session as background.
When I started the download process by tapped a button, I will print the progress of the download.
However, the application stops printing the progress when the application goes into background.
I wonder what did I miss, or misunderstand.
class ViewController: UIViewController {
private lazy var urlSession: URLSession = {
let config = URLSessionConfiguration.background(withIdentifier: "MySession")
config.isDiscretionary = true
config.sessionSendsLaunchEvents = true
return URLSession(configuration: config, delegate: self, delegateQueue:
OperationQueue())
}()
var downloadUrl = "https://archive.rthk.hk/mp4/tv/2021/THKCCT2021M06000036.mp4"
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func downloadButtonTapped(_ sender: UIButton) {
print("DownloadButton Tapped")
let url = URL(string: downloadUrl)
guard let url = url else {
print("Invalid URL")
return
}
let downloadTask = urlSession.downloadTask(with: url)
downloadTask.resume()
}
}
extension ViewController: URLSessionDownloadDelegate, URLSessionDelegate {
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask,
didFinishDownloadingTo location: URL) {
print("Downloaded, location: \(location.path)")
}
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask,
didWriteData bytesWritten: Int64, totalBytesWritten: Int64,
totalBytesExpectedToWrite: Int64) {
let progress = Float(totalBytesWritten) / Float(totalBytesExpectedToWrite)
print("Progress: \(progress)")
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您需要配置后台任务才能正常工作。
有关配置后台任务的更多详细信息,请查看此官方 Apple 开发人员文档
https://developer. apple.com/documentation/foundation/url_loading_system/downloading_files_in_the_background
You need to configure the background tasks to make that work properly.
For more details to configure background tasks please check this official apple developer documentation
https://developer.apple.com/documentation/foundation/url_loading_system/downloading_files_in_the_background
你说:
正确的是,当您的应用程序暂停时,不会调用您的下载进度更新,因为数据任务已移交给进程外守护程序。但这很好。当用户离开您的应用程序时,您确实不需要/不希望调用委托方法。我们希望最大限度地减少用户电池的消耗。
请注意,请求将在您的应用程序暂停后继续进行。如果应用程序在其自然生命周期过程中终止,它们甚至会继续。 (但是,如果用户强制退出您的应用程序,则相关的后台网络请求将不会继续。)
显然,当下载完成后,您的应用程序将被唤醒(在后台),让您知道下载已完成。
顺便说一句,正如在后台下载文件中所述,请记住:
application(_:handleEventsForBackgroundURLSession:completionHandler:)
。URLSessionDelegate
中实现urlSessionDidFinishEvents(forBackgroundURLSession:)
。You said:
Correct, your download progress updates will not be called when your app is suspended, as the data task has been handed off to an out-of-process daemon. But this is fine. When the user leaves your app, you really do not need/want the delegate methods being called. We want to minimize the drain on the users’ battery.
Note, the requests will proceed after your app has been suspended. They will even continue if the app is terminated in the course of its natural life cycle. (However, if the user force-quits your app, the associated background network request will not proceed.)
Obviously, when the download is done, your app will be awakened (in the background) to let you know that the download is done.
By the way, as noted in Downloading Files in the Background, remember to:
application(_:handleEventsForBackgroundURLSession:completionHandler:)
in your app delegate.urlSessionDidFinishEvents(forBackgroundURLSession:)
in yourURLSessionDelegate
.