Swift: Realm - Update UI (Progress) while adding Data to DB

痴心易碎 提交于 2019-12-25 11:56:29

问题


I want to download a 7MB JSON-File and after that I want to add the Data (30000 Datasets) to realm.

while looping through the Datasets it is not possible to update the UI (Label or something)

   let manager = Alamofire.SessionManager.default
    manager.session.configuration.timeoutIntervalForRequest = 20


    manager.request( "http://myURL.json")
        .downloadProgress { progress in

            self.TitelLabel.text =  "loading File :\(String(format: "%.0f", progress.fractionCompleted * 100))%"


        }
        .responseJSON { response in
            print(response.request! as Any)
            switch response.result {
            case .success:

               if let value = response.result.value {
                    self.jsonObj = JSON(value)
                    print(self.jsonObj.count)


                    for i in 0..<self.jsonbj.count{
                    self.TitelLabel.text = "..adding " + i + " article" 
                            let article = Articles()
    articles.price = self.jsonObj[i]["price"].stringValue.replacingOccurrences(of: "'", with: "´")
    article.title = self.jsonObj[i]["title"].stringValue.replacingOccurrences(of: "'", with: "´")
    article.path = self.jsonObj[i]["path"].stringValue
    article.name = self.jsonObj[i]["name"].stringValue
    article.weight = self.jsonObj[i]["weight"].stringValue

     try! realm.write {
            realm.add(article)
        }
                    }
                }

            default:
                break
            }
    }
}

What can I do to change a Label showing the Progress in percent??


回答1:


I can see two issues here. First, the saving to realm is done on main thread, for that you need to move the code inside the background thread. Second the realm object is saved one by one and that's not an optimised way to save data on disk

Below is the code (with comments) that you can replace with your for loop.

// This is to do the task on background
DispatchQueue.global(qos: .background).async {
  // Moved realm.write out of for to improve the performance
  let realm = try? Realm()
  try! realm.write {
    for i in 0..<self.jsonbj.count {
      // Since this is bg thread so UI task should be done on UI thread
      DispatchQueue.main.async {
        self.TitelLabel.text = "..adding " + i + " article"
        // If you want it in percentage then use the below code
        //self.TitelLabel.text = "Adding " + (i*100.0/self.jsonbj.count) + "%"
      }
      let article = Articles()
      articles.price = self.jsonObj[i]["price"].stringValue.replacingOccurrences(of: "'", with: "´")
      article.title = self.jsonObj[i]["title"].stringValue.replacingOccurrences(of: "'", with: "´")
      article.path = self.jsonObj[i]["path"].stringValue
      article.name = self.jsonObj[i]["name"].stringValue
      article.weight = self.jsonObj[i]["weight"].stringValue

      realm.add(article)
    }
  }
}


来源:https://stackoverflow.com/questions/46927028/swift-realm-update-ui-progress-while-adding-data-to-db

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!