我在注册后尝试创建用户个人资料
如何正确地将用户信息从Firebase数据库上传到个人资料屏幕
DatabaseRef = Database.database().reference()
let userID = Auth.auth().currentUser?.uid
DatabaseRef.child("users").child(userID!).observeSingleEvent(of: .value, with: { (snapshot) in
// Get user value
let value = snapshot.value as? NSDictionary
let username = value?["username"] as? String ?? "username"
let dict: Dictionary<AnyHashable, Any>? = ["photo": "url of photo"]
if let profileImageUrl = dict?["photo"] as? String, let url = URL(string: profileImageUrl) {
URLSession.shared.dataTask(with: url) { (data, response, error) in
DispatchQueue.main.async {
if let imageData = data{
self.ProfileImage.image = UIImage(data: imageData)
}else{
}
}
self.UsernameText.text = username
self.DisplayText.text = username
print(error?.localizedDescription as Any)
return
答案 0 :(得分:0)
您应始终避免强行打开包装。相反,您可以检查url
是否不为零,并且仅在url具有某些值时才发送请求。
if let profileImageUrl = dict?["photo"] as? String, let url = URL(string: profileImageUrl) {
URLSession.shared.dataTask(with: notNillUrl) { (data, response, error) in
我可以看到您的url
是由profileImageUrl
创建的,URL格式可能不正确(如不带“ http” /“ https”),因此有必要检查URL创建的表单字符串是否为不零。我将保留以前的答案,因为这可能对其他人有帮助。
检查此URL为何为零将是很好的。也许您正在尝试创建这样的无效URL:
let url = URL(string: "https://this is not woking.com") //or
let url = URL(string: "https://test.com/?a=this won't work")
在这种情况下,最好使用URLComponents
:
var components = URLComponents()
components.scheme = "https"
components.host = "api.github.com"
components.path = "/search / repositories"
components.queryItems = [
URLQueryItem(name: "q", value: "CodableSaveLoad"),
URLQueryItem(name: "other", value: "text with space")
]
print(components.url)
答案 1 :(得分:0)
当您使用(!)强行解开可选值时,程序崩溃,您将收到该错误。取而代之的是,用防护罩安全地打开可选包装。
guard let profileImageUrl = dict?["photo"] as? String else {
print("something wrong, dict["photo"] cannot be cast to String")
return
}
let url = URL(string: profileImageUrl)
URLSession.shared.dataTask(with: url!) { (data, response, error) in
if error != nil {
print(error!)
return
}
}