每當我的應用程序打開連接時,都會導致錯誤。我認爲我正確投射值爲[String: String]
,但不是。解決這個問題的正確方法是什麼?Swift中的Firebase。無法將類型'NSNull'的值轉換爲'NSDictionary'
class func info(forUserID: String, completion: @escaping (User) -> Swift.Void) {
FIRDatabase.database().reference().child("users").child(forUserID).child("credentials").observeSingleEvent(of: .value, with: { (snapshot) in
//This line is the reason of the problem.
let data = snapshot.value as! [String: String]
let name = data["name"]!
let email = data["email"]!
let link = URL.init(string: data["profile"]!)
URLSession.shared.dataTask(with: link!, completionHandler: { (data, response, error) in
if error == nil {
let profilePic = UIImage.init(data: data!)
let user = User.init(name: name, email: email, id: forUserID, profilePic: profilePic!)
completion(user)
}
}).resume()
})
}
錯誤說
無法投類型的值 'NSNull'(0x1ae148588)爲 'NSDictionary的' (0x1ae148128)。
那麼你的JSON結構是什麼樣子? – mjr
在強制解包之前記錄快照的值。另外,避免在一般情況下使用強制解包 - 使用'if let'或'guard'語句代替 –
錯誤消息表明'snapshot.value'爲''(與'nil'不同),並且轉換爲字典失敗。 –
vadian