2017-10-21 169 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为了回报某物 –