I am trying update my realm database after downloading a specific file. But when i try to update my realm database i get the following error
Terminating app due to uncaught exception 'RLMException', reason: 'Realm accessed from incorrect thread.'
I am using Alamofire to download a file and after finishing downloading i am trying to update a value in my realm database.
func initiateDownloadTaskForSelectedSurah(surah: Surah, index: Int) {
// basit/001.zip
do {
let fileName = String(format: "%03d", surah.index)
let destination: DownloadRequest.DownloadFileDestination = { _, _ in
let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
let fileURL = documentsURL.appendingPathComponent("\(self.reciter.downloadUrl)").appendingPathComponent("\(fileName).zip")
return (fileURL, [.removePreviousFile, .createIntermediateDirectories])
}
Alamofire.download(
"\(ApiEndpoints.audioBase)\(reciter.downloadUrl)/\(fileName).zip",
method: .get,
encoding: JSONEncoding.default,
headers: nil,
to: destination).downloadProgress(closure: { (progress) in
//progress closure
print(progress)
DispatchQueue.main.async {
do {
let realm = try Realm()
let item = realm.objects(ReciterItem.self).filter("id == '\(self.reciter.item[index].id)'").first!
try realm.write {
item.progress = Float(progress.fractionCompleted)
}
} catch {
print("Unexpected error: \(error).")
}
self.tableView.reloadRows(at: [IndexPath(row: index, section: 0)], with: .none)
}
}).response(completionHandler: { (DefaultDownloadResponse) in
DispatchQueue.main.async {
do {
let realm = try Realm()
let item = realm.objects(ReciterItem.self).filter("id == '\(self.reciter.item[index].id)'").first!
try realm.write {
item.progress = 1.0
item.isDownloaded = true
self.reciter.item[index].progress = 1.0
self.reciter.item[index].isDownloaded = true
}
} catch {
print("Unexpected error: \(error).")
}
self.tableView.reloadRows(at: [IndexPath(row: index, section: 0)], with: .none)
}
})
} catch {
print(error)
}