2016-07-14 4 views
4

Firebase에서 데이터를 검색하고 해당 데이터를 검색하는 클로저 외부에 해당 데이터를 저장하려고합니다.Firebase에서 데이터를 가져 오는 클로저에서 데이터 가져 오기

var stringNames = [String]() 
    ref?.observeEventType(.Value, withBlock: { snapshot in 
     var newNames: [String] = [] 
     for item in snapshot.children { 
      if let item = item as? FIRDataSnapshot { 
       let postDict = item.value as! [String: String] 
       newNames.append(postDict["name"]!) 
      } 
     } 
     stringNames = newNames 
    }) 
    print(stringNames) 

stringNames는 비어 있지만, 내부에서 클로저로 인쇄 할 때 올바른 데이터를 갖습니다. 어떤 도움이라도 대단히 감사 할 것입니다, 감사합니다!

답변

6

Firebase에서 데이터를 가져 오면 호출이 비동기이기 때문입니다. 할 수있는 일 :

옵션 1 - 논리를 클로저 안에 설정합니다 (예 : 클로저 안에 var를 인쇄하는 것과 같습니다). -

옵션 2와 같은 데이터를 받으려고 자신의 폐쇄 정의 :

func myMethod(success:([String])->Void){ 

    ref?.observeEventType(.Value, withBlock: { snapshot in 
     var newNames: [String] = [] 
     for item in snapshot.children { 
      if let item = item as? FIRDataSnapshot { 
       let postDict = item.value as! [String: String] 
       newNames.append(postDict["name"]!) 
      } 
     } 
     success(newNames) 
    }) 
} 

옵션 3 - 사용 위임 패턴

protocol MyDelegate{ 
    func didFetchData(data:[String]) 
} 

class MyController : UIViewController, MyDelegate{ 

    func myMethod(success:([String])->Void){ 
     ref?.observeEventType(.Value, withBlock: { snapshot in 
      var newNames: [String] = [] 
      for item in snapshot.children { 
       if let item = item as? FIRDataSnapshot { 
        let postDict = item.value as! [String: String] 
        newNames.append(postDict["name"]!) 
       } 
      } 
      self.didFetchData(newNames) 
     }) 
    } 

    func didFetchData(data:[String]){ 
     //Do what you want 
    } 

} 
+0

을 위임 패턴 I가 원하는 것을 정말 잘했다 데이터로해라, 고마워! –

관련 문제