下载完成后从错误的线程访问领域 Swift 3
Posted
技术标签:
【中文标题】下载完成后从错误的线程访问领域 Swift 3【英文标题】:Realm accessed from incorrect thread after download completed Swift 3 【发布时间】:2016-12-27 04:00:51 【问题描述】:我有一个应用程序,用户可以下载 pdf 文件。我最近搬到了 alamofire 4 和 swift 3。我尝试在下载完成后查看 pdf 文件,但它抛出 Realm accessed from incorrect thread.
这是我的代码:
Alamofire.download(url, method: .get, encoding: JSONEncoding.default, to: destination)
.downloadProgress(queue: DispatchQueue.global(qos: .utility)) progress in
DispatchQueue.main.async
magazineObject.progressBarDownload = self.percentProgress
magazineObject.progressBarTitle = self.percentProgressNext.cleanValue
.validate request, response, temporaryURL, destinationURL in
self.localPath = destinationURL
magazineObject.pathDatabase = String(describing: self.localPath!)
magazineObject.progressBarDownload = Double(self.percentProgressFinal)
magazineObject.progressBarTitle = Float(self.displayFinalLabelPercent).cleanValue
magazineObject.statusDarkViewAfterRelaunch = 1
magazineObject.statusDownload = self.statusDatabase
try! realm.write
realm.add(magazineObject)
return .success
【问题讨论】:
【参考方案1】:尝试在validate
块内创建另一个领域线程对象
.validate request, response, temporaryURL, destinationURL in
self.localPath = destinationURL
magazineObject.pathDatabase = String(describing: self.localPath!)
magazineObject.progressBarDownload = Double(self.percentProgressFinal)
magazineObject.progressBarTitle = Float(self.displayFinalLabelPercent).cleanValue
magazineObject.statusDarkViewAfterRelaunch = 1
magazineObject.statusDownload = self.statusDatabase
// create new object here
let realm = try! Realm()
try! realm.write
realm.add(magazineObject)
return .success
您可以在领域文档https://realm.io/docs/swift/latest/#using-a-realm-across-threads查看详细信息
【讨论】:
以上是关于下载完成后从错误的线程访问领域 Swift 3的主要内容,如果未能解决你的问题,请参考以下文章
仅在完成操作IOS Swift 3后才使用户访问视图[关闭]
Swift 3.0:使用 URLSessionDownloadDelegate 完成下载后如何在不同的视图控制器中打开 PDF