我有以下Model將資料回傳到我的View Controller:
func getRecipeSelected(docId: String, completionHandler: @escaping () -> Void) {
db.collection("recipes").document(docId).getDocument { document, error in
if let error = error as NSError? {
}
else {
if let document = document {
do {
self.recipe = try document.data(as: Recipe.self)
let recipeFromFirestore = Recipe(
id: docId,
title: self.recipe!.title ?? "",
analyzedInstructions: self.recipe!.analyzedInstructions!)
DispatchQueue.main.async {
self.delegateSpecificRecipe?.recipeSpecificRetrieved(recipeSelected: recipeFromFirestore)
}
}
catch {
print("Error: \(error)")
}
}
}
}
completionHandler()
}
這是在我的View Controller:
var entireRecipe: Recipe? = nil
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
documentID = recipeDocIdArray[indexPath.row]
model.getRecipeSelected(docId: documentID) {
print("ISSUE HERE: \(self.entireRecipe)") // FIXME: THIS IS NIL THE FIRST TIME IT IS CALLED
}
}
我的問題是沒有從我的視圖控制器的完成處理程式中entireRecipe分配資料。model如果我要第二次點擊該單元格,那么第一次點擊的資料將在該完成處理程式中分配。
如何在第entireRecipe一次點擊時將回傳的資料分配給該范圍內的資料?
uj5u.com熱心網友回復:
您正在呼叫委托方法而不是呼叫completionHandler。而且您還在異步塊中呼叫委托方法,該方法在完成處理程式之后呼叫。不需要連續兩個。您可以使用 completionHandler 像:
func getRecipeSelected(docId: String, completionHandler: @escaping (Recipe?) -> Void) {
db.collection("recipes").document(docId).getDocument { document, error in
if let error = error as NSError? {
}
else {
if let document = document {
do {
self.recipe = try document.data(as: Recipe.self)
let recipeFromFirestore = Recipe(
id: docId,
title: self.recipe!.title ?? "",
analyzedInstructions: self.recipe!.analyzedInstructions!)
completionHandler(recipeFromFirestore)
}
catch {
print("Error: \(error)")
completionHandler(nil)
}
}
}
}
}
var entireRecipe: Recipe?
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
documentID = recipeDocIdArray[indexPath.row]
model.getRecipeSelected(docId: documentID) { [weak self] model in
self?.entireRecipe = model
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/437288.html
