2016-06-30 2 views
0

CloudKit을 사용하여 iCloud에서 데이터를 검색하려고합니다. 이 작업은 한 번만 수행하기 때문에 코드를 AppDelegate.swift 파일의 didFinishLaunchingWithOptions에 넣습니다.AppDelegate에서 CKQuery 실행 - 완료 될 때까지 기다림

주 스레드에서이 코드를 실행하려고합니다. 따라서 첫 번째 ViewController에있는 코드는 데이터를 가져올 때까지 호출되지 않습니다.

func getPeople() { 
    let query = CKQuery(recordType: "Person", predicate: Predicate(format: "TRUEPREDICATE", argumentArray: nil)) 
    CKContainer.default().privateCloudDatabase.perform(query, inZoneWith: nil) { (records, error) in 
     if error == nil { 
      names.removeAll() 
      messages.removeAll() 
      pictures.removeAll() 
      recordIds.removeAll() 

      for record in records! { 

       names.append(record.object(forKey: "name") as! String) 
       messages.append(record.object(forKey: "message") as! String) 
       pictures.append(UIImage(data: record.object(forKey: "picture") as! NSData as Data)!) 
       recordIds.append(record.recordID) 

      } 

      print("done") 

     } else { 

      print(error) 
      print(error?.code) 

     } 

    } 

} 

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { 
    performSelector(onMainThread: #selector(getPeople), with: nil, waitUntilDone: true) 

    return true 
} 

그러나 이것은 작동하지 않는 것 같습니다. print("done")은 내 ViewController에서 viewDidLoad 뒤에 호출됩니다. 전에 멀티 스레딩을 사용하지 않았으며 쿼리가 완료 될 때까지 다른 코드가 호출되는 것을 어떻게 막을 수 있는지 알고 싶습니다. 감사!

답변

0

데이터가로드 될 때까지 기다리지 마십시오. 검색하는 데 몇 초가 걸릴 수 있으며 사용자 인터페이스는 반응이 없습니다. 너무 오랫동안 응답하지 않으면 시스템에서 앱을 종료 할 수도 있습니다. 대신 데이터가 도착한 후에 뷰를 업데이트하십시오. NSNotificationCenter.defaultCenter().addObserver을 사용하여 데이터 변경을 관찰 할 수 있습니다.

관련 문제