2017-06-15 56 views
2

我需要從Firebase獲取一些信息才能在UIViewCell上找到它。但問題是,在他獲得所有價值之前,函數會返回。我知道那是因爲它是異步的,我試圖做一個完成處理這樣的:如何使用Firebase Swift製作CompletionHandler 3

static func hardProcessingWithString(input: String, completion: @escaping (_ result: String) -> Void) { 
    Database.database().reference().child("Player_1").observe(.value) { 
     (firDataSnapshot) in 
     completion((firDataSnapshot.value as? String)!)  
    } 
} 

這是我嘗試獲得價值:

var myVar: String! 
hardProcessingWithString(input: "commands"){ 
     (result: String) in 
     myVar = result 
} 

當我打電話的功能我得到這個錯誤:

無法將'__NSDictionaryM'(0x102e292b0)類型的值轉換爲'NSString'(0x102434c60)。

這裏是我的火力地堡數據庫:

DataBase from Firebase

或者,如果你知道如何使火力地堡許諾讓我知道!

+0

告訴我們孩子的數據庫結構法 「PLAYER_1」。錯誤不在完成處理程序中,但在類型中。像db –

+0

的屏幕截圖是firDataSnapshot.value實際上是一個字符串?你能調試這個值嗎? – petul

+0

@petul是的,它是一個字符串! – Max0u

回答

1

第1步:

創建一個像Constant.swift這樣的swift文件。然後將下面的代碼裏面

typealias DownloadComplete =() ->() 

第2步:

創建您想要的功能。

func hardProcessingWithString(completed: @escaping DownloadComplete) { 
Database.database().reference().child("Player_1").observe (.value, with: { (firDataSnapshot) in 

// put your code here 

completed() 
}) 
} 

第3步:

,當你在你的代碼中調用上述方法

hardProcessingWithString() { 
    // you can get the result here 
} 
+0

閱讀他的「不能轉換值鍵入'__NSDictionaryM'(0x102e292b0)爲'NSString'(0x102434c60)。「。問題不在於完成處理器組織。 –

+0

@Alwin但是我怎樣才能返回功能的價值?我想獲得firDataSnapshot的值 – Max0u

+0

創建一個全局變量並設置getters和setters – Alwin

相關問題