斯威夫特的Firebase。无法施放类型的值NSNull'来自NSDictionary'

时间:2017-01-19 14:39:17

标签: ios swift firebase firebase-realtime-database

每次打开我的应用程序时,都会导致错误。我认为我正在将值正确地投射为[String: String]但不是。解决这个问题的正确方法是什么?

 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)。

2 个答案:

答案 0 :(得分:1)

当webservice返回值<null>时,它将被表示为NSNull个对象。这是一个实际的对象,将其与nil进行比较将返回false

这就是我的所作所为:

if let json = snapshot.value as? [String: String] {
    //if it's possible to cast snapshot.value to type [String: String]
    //this will execute
}

答案 1 :(得分:1)

FIRDataSnapshot成功请求后应返回Any?,失败时返回nullas!因为我们不知道请求何时成功或失败,所以我们需要安全地打开这个可选项。在您的错误中,您强制转发([String: String]),如果快照数据未作为null返回,则会崩溃,即如果您的请求返回as?。如果您的快照数据不是nil类型

,则有条件地向下转发([String: String])会安全返回// So rather than let data = snapshot.value as! [String: String] // Conditionally downcast if let data = snapshot.value as? [String: String] { // Do stuff with data } // Or.. guard let data = snapshot.value as? [String: String] else { return } // Do stuff with data

TL; DR - 您需要有条件地保持低调

fragmentManager.findFragmentByTag("tag");
fragmentManager.findFragmentById(id);