2017-10-21 159 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

不能達到你正在嘗試做的。最好的辦法是兩種方法。 Get和Set並且get方法將會有一個'completionHandler'。 – Torewin

回答

0

您正在返回你的arrayasync通話結束。您應該將數組填充到異步調用中,然後調用另一種提供結果的方法。

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爲了回報某物 –