我从服务器下载了一些文件。下载完成后,我应该解压它们,在此之后,我显示显示结果的本地推送通知。为了不阻塞UI,我添加了观察器,用于显示没有活动指示器的自定义进度线,并根据状态更新此线。
我想给用户一个机会,使这一切在后台。
为了进行下载,我使用bg配置创建了URLSession,如下所示:
private lazy var urlSession: URLSession = {
let config = URLSessionConfiguration.background(withIdentifier: "MySession")
config.isDiscretionary = true
config.sessionSendsLaunchEvents = true
return URLSession(configuration: config, delegate: self, delegateQueue: nil)
}()而且所有的下载工作都很好。但是我的解包功能仍然只在前台工作。我如何在后台使用它?
对于解包,我使用lib ZIPFoundation。代码如下:
public func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
downloadService.update(state: .unpacking, for: downloadTask)
do {
let documentsDir = try self.fileManager.url(
for: .documentDirectory,
in: .userDomainMask,
appropriateFor: nil,
create: false
)
let newLocation = documentsDir.appendingPathComponent(location.lastPathComponent)
try fileManager.moveItem(at: location, to: newLocation)
DispatchQueue.global(qos: .background).async { [weak self] in
guard let self = self else { return }
do {
let path = try self.fileManager.url(
for: .documentDirectory,
in: .userDomainMask,
appropriateFor: nil,
create: false
)
.appendingPathComponent("store")
try self.fileManager.unzipItem(at: newLocation, to: path, progress: downloadTask.progress)
try self.fileManager.removeItem(at: newLocation)
DispatchQueue.main.async {
self.notificationCenter.add(.languageIsDownloaded)
self.downloadService.update(state: .finished, for: downloadTask)
}
} catch {
DispatchQueue.main.async {
self.errorHandler.handle(error)
self.downloadService.update(state: .failed, for: downloadTask)
}
}
}
} catch {
errorHandler.handle(error)
downloadService.update(state: .failed, for: downloadTask)
}
}发布于 2020-01-09 17:45:31
如果您正在执行一些可能会耗费时间的操作,并且您不想终止它,那么您可以通过在UIBackground任务中执行来延长操作的时间
{
UIBackgroundTaskIdentifier taskId = 0;
taskId = [application beginBackgroundTaskWithExpirationHandler:^{
taskId = UIBackgroundTaskInvalid;
}];
// Execute long process. This process will have 10 mins even if your app goes in background mode.
}名为"handler“的块参数是后台任务到期(10分钟)时将发生的事情。以下是指向documentation的链接
https://stackoverflow.com/questions/59661013
复制相似问题