2017-10-25 16 views
0

7MB JSON 파일을 다운로드하고 그 후에 영역에 데이터 (30000 데이터 집합)를 추가하고 싶습니다.스위프트 : 영역 - DB에 데이터를 추가하는 동안 UI (진행) 업데이트

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

나는 퍼센트의 진행을 표시하는 라벨을 변경하기 위해 무엇을 할 수 있는가?

+0

먼저 30000 개의 트랜잭션 대신 30 개의 트랜잭션에 30000 개의 항목을 추가 할 수 있습니다. 성능 향상에 도움이 될 것입니다. – EpicPandaForce

+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) 
    } 
    } 
} 
+0

tryed하지만 그 결과는 *** 잡히지 않은 예외 'RLMException'으로 인해 응용 프로그램을 종료합니다. 이유 : '잘못된 스레드에서 액세스 한 영역'. – Marc

+0

그러면 dispatch 블록에 영역 객체를 만들어야한다고 생각합니다. 코드를 업데이트하십시오. –

+0

죄송합니다. 실제로 작동하지 않습니다. 레이블이 값을 한 두 번 변경하면 두 번 고정됩니다. – Marc