2017-08-13 40 views
1

我試圖找出處理函數完成的最佳方法。當firebase完成時,添加完成功能,iOS,Swift

該函數調用firebase中的數據並將它們添加到字典數組中。因爲這是針對地圖和添加註釋的,所以在到達最終附加版本之前,循環會添加大量數據,以便在同一位置投擲大量註釋。我想知道是否可以在完成循環時調用完成,然後調用ShowSightings()函數。

func getDatafromFB() { 
    DataService.ds.REF_POSTS.child("postCodes").observeSingleEvent(of: .value, with: { (snapshot) in 

     let value = snapshot.value as? NSDictionary 
     let postsIds = value?.allKeys as! [String] 
     for postId in postsIds { 
      let refToPost = Database.database().reference(withPath: "posts/" + "postCodes/" + postId) 
      refToPost.observe(.value, with: { snapshot in 
       if snapshot.exists() { 

        let postDict = snapshot.value as? [String: AnyObject] 

        print("Tony: before append post \(self.posts)") 
        self.posts.append(postDict!) 
        print("Tony: post \(self.posts)") 


       }else { 
        print("Tony: Couldn't get the data") 
       } 
      }) 
     } 
     print("Tony: The compleetion result \(self.posts)") 
    }) 

} 

回答

1

你可以試試這個:

func doAsyncTask(completionHandler:@escaping (Bool) ->()){ 
//do async tasks 
completionHandler(true) //<- call this when the data is retrieved 
//so in your case, see below 
} 

override func viewDidLoad{ 
    doAsyncTask(){ succes in 
    //succes gives true or false 
    } 
} 

//your case 
}else { 
    print("Tony: Couldn't get the data") 
} 
completionHandler(true) //<- right there 

這是1個異步任務。我看到你想要使用多個異步任務。這是派遣組的工作。我改變了我的一些函數來獲取參數。看看這個:

func doAsyncTask(postID: String, completionHandler:@escaping (Bool) ->()){ 
//do async tasks 
completionHandler(true) 

} 

override func viewDidLoad{ 
var arrPostIDs = [String]() 
//append to arrPostIDs here 
let postIDDispatchGroup = DispatchGroup() 
for postID in arrPostIDs{ 
postIDDispatchGroup.enter() 
    doAsyncTask(postID: postID){ succes in 
    //succes gives true or false 
    postIDDispatchGroup.leave() 
    } 
    } 
postIDDispatchGroup.notify(queue: .main) { 
//everything completed :), do whatever you want 
    } 
} 
+0

謝謝你回答@ j.Doe,我試圖從Firebase建立一個字典數組。目前我正在將它們修改爲post [[string:Any]]()設置的每個帖子,postsID中的每個postID都用於發佈帖子。我應該用什麼來附加arrPostIds?是否有帖子? –

+0

爲此我乾杯能夠編輯它並應用於我的代碼 –