gpt4 book ai didi

swift - 如何使用如果让可选照片?

转载 作者:行者123 更新时间:2023-11-30 12:37:51 25 4
gpt4 key购买 nike

所以,我的应用程序崩溃了,因为它强制打开“照片”,即使它是可选的并且里面什么也没有。我如何使用 if let 语句,比如如果照片有图片,那么它会显示,如果没有,它将为零,但应用程序不会崩溃。我有这个结构 User 这是我的数据保存的地方我正在使用 firebase。

struct User {

var fullName: String!
var username: String?
var email: String!
var country: String?
var photoURL: String?
var biography: String?
var uid: String!
var ref: FIRDatabaseReference?
var key: String?

init(snapshot: FIRDataSnapshot) {

key = snapshot.key
ref = snapshot.ref

fullName = (snapshot.value! as! NSDictionary) ["fullName"] as! String
email = (snapshot.value! as! NSDictionary) ["email"] as! String
uid = (snapshot.value! as! NSDictionary) ["uid"] as! String
country = (snapshot.value! as! NSDictionary) ["country"] as! String?
biography = (snapshot.value! as! NSDictionary) ["biography"] as! String?
photoURL = (snapshot.value! as! NSDictionary) ["photoURL"] as! String?
username = (snapshot.value! as! NSDictionary) ["username"] as! String?
}

}

这就是应用程序崩溃的地方,因为“self.storageRef.reference(forURL:imageURL!)”即使里面什么也没有,它也会强制解开包装。

 func loadUserInfo() {

@IBOutlet weak var userImageView: UIImageView!
@IBOutlet weak var addButton: UIButton!
@IBOutlet weak var fullName: UILabel!
@IBOutlet weak var username: UILabel!
@IBOutlet weak var country: UILabel!
@IBOutlet weak var biography: UILabel!

let userRef = dataBaseRef.child("users/\(FIRAuth.auth()!.currentUser!.uid)")
userRef.observe(.value, with: { (snapshot) in

let user = User(snapshot: snapshot)
self.username.text = user.username
self.country.text = user.country
self.biography.text = user.biography
self.fullName.text = user.fullName
var imageURL = user.photoURL

self.storageRef.reference(forURL:imageURL!).data(withMaxSize: 1 * 1024 * 1024, completion: { (imgData, error) in

if error == nil {
DispatchQueue.main.async {
if let data = imgData {
self.userImageView?.image = UIImage(data: data)
}
}
} else {
print(error!.localizedDescription)
}
})
})
{ (error) in
print(error.localizedDescription)
}
}

最佳答案

首先我认为你应该更改用户的init,你应该这样做:

let data = snapshot.value as! NSDictionary;
fullName = data["fullName"] as! String;

如果您不确定国家是否存在,您可以这样做:

country = data["country"] as? String;

那么当你使用use.photoURL时,你可以使用let来保存,就像:

if let photoURL = user.photoURL {
//...retrive photo of the url from somewhere
}

最后,我想说,你可能对 ?! 理解错误,或者对它们感到困惑。

? 是当你认为这个变量/函数可能为nil/无法调用时,或者当你进行类型转换,但你不确定一定会成功时。

! 表示您确定它存在或者您将立即创建它。您也可以将其理解为解开可选值,只是因为您使其绝对存在。

当我们像您的User一样创建我们自己的模型时,您可以使列不可能为零,您可以这样做:

var fullName: String?       = nil;
fullName = SomeJsonTypeData["fullName"] ?? "default value";

那么当你使用它时,你就不用担心它会nil

关于swift - 如何使用如果让可选照片?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42633092/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com