2017-10-21 6 views
0

Firebaseデータベースを検索する次の関数を記述しました。また、デバッグステートメントを使用して調べ、ブレークポイントでテストして、この関数が正しいデータを取得していることを確認しました。しかし、最後に配列を返すと、配列は空です。私が理解する限り、これはfirebaseの非同期性のためです。この機能は、データがアレイに追加される前に終了しています。どのようにしてこれを修正して意図したとおりに動作させることができるのか、他の機能に使うことができるアイテムの配列を返したい。Firebaseを非同期に扱うには?奇妙な結果をもたらすデータベースの読み込み

static func SearchPostsByTags(tags: [String]) -> [Post]{ 
    var result = [Post]() 

    let dbref = FIRDatabase.database().reference().child("posts") 

    dbref.observeSingleEvent(of: .value, with: { snap in 
     let comps = snap.value as! [String : AnyObject] 

     for(_, value) in comps { 
      let rawTags = value["tags"] as? NSArray 

      let compTags = rawTags as? [String] 

      if compTags != nil { 

       for cTag in compTags! { 
        for tag in tags { 
         if (tag == cTag) { 
          let foundPost = Post() 
          foundPost.postID = value["postID"] as! String 
          foundPost.title = value["title"] as! String 

          result.append(foundPost) 
         } 
        } 
       } 
      } 
     } 
    }) 
    return result 
} 

}

+0

迅速に完了ハンドラ/コールバックを検索してください。これはあなたの問題を解決すると思います。 – 3stud1ant3

+0

あなたは何をしようとしているのか達成できません。これを行う最善の方法は2つの方法です。取得して設定すると、getメソッドはその上に 'completionHandler'を持ちます。 – Torewin

答えて

0

asyncコールが終了する前に、あなたはあなたのarrayに戻ってきています。非同期呼び出しの中で配列を塗りつぶし、別のメソッドを呼び出して結果を提供する必要があります。

static func SearchPostsByTags(tags: [String]) { 
    let dbref = FIRDatabase.database().reference().child("posts") 
    dbref.observeSingleEvent(of: .value, with: { snap in 
     let comps = snap.value as! [String : AnyObject] 
     var result = [Post]() 
     for(_, value) in comps { 
      let rawTags = value["tags"] as? NSArray 

      let compTags = rawTags as? [String] 

      if compTags != nil { 

       for cTag in compTags! { 
        for tag in tags { 
         if (tag == cTag) { 
          let foundPost = Post() 
          foundPost.postID = value["postID"] as! String 
          foundPost.title = value["title"] as! String 

          result.append(foundPost) 
         } 
        } 
       } 
      } 
     } 
     // Call some func to deliver the finished result array 
     // You can also work with completion handlers - if you want to try have a look at callbacks/completion handler section of apples documentation 
     provideTheFinishedArr(result) 
    }) 
} 
+0

どうだろう、このprvideTheFinishedArr機能を見ているだけで、それだけで provideTheFinishedArr(結果)から構成されている場合も、データベースクエリの前に完了してしまうではないでしょうので、私は返すためにSearchPostsByTagsを呼ぶだろうか。また、{ リターン結果 } 何か –

関連する問題