我在我的应用程序中有一个情况,我需要上传几个文件,范围从 10-50+-(小尺寸,约 5 mb),并且如果需要还需要支持在后台继续。此时,我可以在应用程序处于前台时完美上传,但一旦应用程序进入后台,当前正在运行的上传将继续运行并在后台完成,但由于某种原因,其余操作永远不会被调用。
这是我的代码
后台队列初始化:
private var _backgroundUploadQueue = OperationQueue()
后台队列设置:
self._backgroundUploadQueue.maxConcurrentOperationCount = 4
self._backgroundUploadQueue.name = "Background Queue"
self._backgroundUploadQueue.qualityOfService = .background
创建操作:
private func _createUploadOperation(from action: S3UploadAction) -> AsyncBlockOperation {
let operation = AsyncBlockOperation({ [weak self] operation in
guard !operation.isCancelled else {
operation.finish()
return
}
self?._s3SinglePartUploader.upload(
action: action,
completion: { [weak self] result in
self?._handleUploadCompletion(operation: operation, action: action, result: result)
}
)
self?._singlePartUploadStarted(action: action)
})
operation.name = "\(action.recordingSetVersion)_\(action.partNumber)"
return operation
}
添加操作:
private func _startBackgroundUploading() {
for (_, actions) in self._uploadActions.enumerated() {
for action in actions.value {
let uploadOperation = self._createUploadOperation(from: action)
self._backgroundUploadQueue.addOperation(uploadOperation)
}
}
}
在 AppDelegate 中,我添加了以下代码:
func application(
_ application: UIApplication,
handleEventsForBackgroundURLSession identifier: String,
completionHandler: @escaping () -> Void
) {
S3Uploader.shared.setBackgourndSessionCompletion(backgroundTaskCompletion: completionHandler)
AWSS3TransferUtility.interceptApplication(
application,
handleEventsForBackgroundURLSession: identifier,
completionHandler: completionHandler
)
}