我想在后台下载/上传之后提出一个额外的HTTP请求,以确认应用程序完成了下载/上载。让我给你们举个简单的例子。
首先,我们需要创建下载/上传任务。
let configuration = URLSessionConfiguration.background(withIdentifier: UUID().uuidString)
configuration.sessionSendsLaunchEvents = true
configuration.isDiscretionary = true
let session = URLSession(configuration: configuration, delegate: self, delegateQueue: nil)
session.downloadTask(with: largeFileURL).resume()然后,我们需要在下载/上传完成后触发一些额外的请求。为了防止应用程序被挂起,我使用后台任务。
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
backgroundTaskIdentifier = UIApplication.shared.beginBackgroundTask(expirationHandler: { [weak self] in
finishBackgroundTask()
})
let task = URLSession.shared.dataTask(with: someURL) { data, response, error in
// Process response.
finishBackgroundTask()
}
task.resume()
}
private func finishBackgroundTask() {
UIApplication.shared.endBackgroundTask(backgroundTaskIdentifier)
backgroundTaskIdentifier = .invalid
}最后一件事是实现应用程序委托方法:
func application(_ application: UIApplication, handleEventsForBackgroundURLSession identifier: String, completionHandler: @escaping () -> Void) {
}问题
在背景转移之后,这是一种合适的工作方式吗?
发布于 2018-12-27 18:56:24
如果内存可用,最好的方法是在调用完成块之前启动新请求。但是,请注意,不管您如何做,如果您重复发出简短的请求,操作系统将迅速增加后台下载完成时和应用程序在后台重新启动以处理会话事件之间的延迟。
发布于 2019-01-02 14:11:26
我建议在您的completionHandler中创建一个AppDelegate
var backgroundSessionCompletionHandler: (() -> Void)?然后在handleEventsForBackgroundURLSession UIApplicationDelegate的方法中定义完成处理程序
func application(_ application: UIApplication, handleEventsForBackgroundURLSession
identifier: String, completionHandler: @escaping () -> Void) {
backgroundSessionCompletionHandler = {
// Execute your additional HTTP request
}
}最后一步是在下载完成后调用此完成处理程序。
func urlSessionDidFinishEvents(forBackgroundURLSession session: URLSession) {
if let appDelegate = UIApplication.shared.delegate as? AppDelegate {
if let completionHandler = appDelegate.backgroundSessionCompletionHandler {
appDelegate.backgroundSessionCompletionHandler = nil
DispatchQueue.main.async(execute: {
completionHandler()
})
}
}
}我希望这能帮到你。
https://stackoverflow.com/questions/53947424
复制相似问题