每次打开我的应用程序时,都会导致错误。我认为我正在将值正确地投射为[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)。
答案 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?
,失败时返回null
。as!
因为我们不知道请求何时成功或失败,所以我们需要安全地打开这个可选项。在您的错误中,您强制转发([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);