0

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)
        }
Ahsan Aasim
  • 1,177
  • 3
  • 14
  • 40
  • You are getting this in `downloadProgress` or `response` block ? – Dinesh Balasubramanian May 12 '18 at 06:46
  • this object `self.reciter` How to fill it in any thread ? – a.masri May 12 '18 at 07:21
  • There are at least half a dozen links to check before putting up this question. Have you tried any of them? If so, put that in your question. https://www.google.com.au/search?q=realm+accessed+from+incorrect+thread+site:stackoverflow.com&sa=X&ved=0ahUKEwify9GM8f_aAhUPPrwKHbq3CRwQrQIIPygEMAE&biw=1280&bih=755 – App Dev Guy May 12 '18 at 09:43
  • Most likely `self.reciter.item[index].progress = 1.0` and `self.reciter.item[index].isDownloaded = true` are UI-thread bound, learn to use NotificationToken over Results instead. – EpicPandaForce May 12 '18 at 10:24
  • See https://stackoverflow.com/a/43753450/2413303 – EpicPandaForce May 12 '18 at 12:30

0 Answers0