我有收藏视图,用户可以点击下载pdf文件。如果下载完成,它会显示pdf文件。但经过PDF出现了,回去然后再次点击细胞再次显示PDF格式,它抛出Realm accessed from incorrect thread.
当尝试再次查看pdf文件时,从不正确的线程访问的领域Swift 3
这里是我的代码来下载文件:
func downloadData(_ magazineObject: Magazine, cell: magazineCell) {
Alamofire.download(magazineObject.urlMagazine, method: .get, encoding: JSONEncoding.default, to: destination)
.downloadProgress(queue: DispatchQueue.global(qos: .utility)) { progress in
DispatchQueue.main.async() {
self.percentProgressFinal = Float(progress.fractionCompleted)
magazineObject.progressBarDownload = progress.fractionCompleted.roundToPlaces(places: 2)
magazineObject.progressBarTitle = Float(self.displayFinalLabelPercent).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
let mainStoryBoard:UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let vc:PDFKBasicPDFViewer = mainStoryBoard.instantiateViewController(withIdentifier: "NEXT") as! PDFKBasicPDFViewer
let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
let filePath = "\(documentsPath)/\(magazineObject.title).pdf"
let document: PDFKDocument = PDFKDocument(contentsOfFile: filePath, password: nil)
vc.loadDocument(document)
self.navigationController?.pushViewController(vc, animated: true)
magazineObject.statusDownload = self.statusDatabase
let realm = try! Realm()
try! realm.write {
realm.add(magazineObject)
}
return .success
}
}
,并显示该文件,如果已经下载:
if statusGlobal {
if magazineObject.statusDownload == 0 {
magazineObject.statusDownload = 1
//Alamofire Request
downloadData(magazineObject, cell: cell)
cell.progressDownload.isHidden = false
cell.progressLabel.isHidden = false
} else {
let mainStoryBoard:UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let vc:PDFKBasicPDFViewer = mainStoryBoard.instantiateViewController(withIdentifier: "NEXT") as! PDFKBasicPDFViewer
let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
let filePath = "\(documentsPath)/\(magazineObject.title).pdf"
let document: PDFKDocument = PDFKDocument(contentsOfFile: filePath, password: nil)
vc.loadDocument(document)
self.navigationController?.pushViewController(vc, animated: true)
}
}
}
但如果我重新运行模拟器,它可以显示我的pdf文件。
是你的代码上面你得到一个'Realm'和使用它的_only_地方提供解决呢? – AustinZ
是的,这是我获得Realm并使用它的唯一地方 –