Swift:Realm - 在向DB添加数据时更新UI(进度)

时间:2017-10-25 08:00:59

标签: swift realm progress

我想下载一个7MB的JSON文件,之后我想将数据(30000数据集)添加到领域。

在循环数据集时,无法更新UI(标签或其他内容)

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

如何更改显示百分比进度的标签?

1 个答案:

答案 0 :(得分:1)

我在这里可以看到两个问题。首先,保存到领域是在主线程上完成的,因为你需要在后台线程中移动代码。其次,领域对象是逐个保存的,这不是在磁盘上保存数据的优化方法

以下是您可以用for循环替换的代码(带注释)。

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