I want to save json data in Realm in swift . But I am getting error like:
Terminating app due to uncaught exception 'RLMException',
reason: 'Realm accessed from incorrect thread'"
In this situation what to use - "GCD" or "operation"
I am adding my code here
func getDataFromServer(){
let personData = Person()
let headers = [
"user_id": "1",
"access_token": "5ae39568b47d3edf12345dc7ccddf519",
]
let request = NSMutableURLRequest(url: NSURL(string: "http://prvy.in/sme/assgnment_ios/api/user/data")! as URL)
request.httpMethod = "POST"
request.allHTTPHeaderFields = headers
let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
if (error != nil) {
} else {
if let data = data {
do{
guard let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? NSDictionary else{
return
}
if let resultArray = json["data"] as? NSArray{
for allData in resultArray {
if let resultData = allData as? NSDictionary{
let regdId = resultData[REGD_ID] as? String
if let firstName = resultData[FIRST_NAME] as? String{
print(firstName)
personData.firstName = firstName
}
self.saveReamData(personData)
}
}
}catch{
print("error loading data")
}
}
}
})
dataTask.resume()
}
My save function is:
func saveReamData(_ person: Person) {
let backgroundQueue = DispatchQueue(label: ".realm", qos: .background)
backgroundQueue.async {
do {
try self.realm?.write {
self.realm?.add(person)
}
} catch {
print("error saving to realm")
}
}
}
If you created Realm instance in the main queue you can use it only on the main queue. In your code you are trying to write data to Realm in the background queue but you have created Realm instance in the main queue.
If you want to write data to Realm in the background queue use this code from Realm documentation:
DispatchQueue(label: "background").async {
autoreleasepool {
let realm = try! Realm()
guard let person = realm.resolve(personRef) else {
return // person was deleted
}
try! realm.write {
person.name = "Jane Doe"
}
}
}