快速将Json数据保存在Realm中

时间:2019-04-02 08:12:37

标签: json swift realm

我想将json数据快速保存在Realm中。但是我遇到了类似的错误:

  

由于未捕获的异常'RLMException'终止了应用程序,
原因:'从错误的线程访问了领域'“

在这种情况下,使用什么-“ GCD”或“操作”

我在这里添加代码

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()
}

我的保存功能是:

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")
        }
    }

}

1 个答案:

答案 0 :(得分:0)

如果您在主队列中创建了Realm实例,则只能在主队列上使用它。在您的代码中,您试图在后台队列中将数据写入Realm,但是您已经在主队列中创建了Realm实例。

如果要在后台队列中将数据写入Realm,请使用Realm文档中的以下代码:

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"
        }
    }
}