gpt4 book ai didi

ios - Swift 认为 Structure 中的变量是可选的

转载 作者:行者123 更新时间:2023-11-30 13:00:00 28 4
gpt4 key购买 nike

我基于 Firebase 制作了简单的后期制作项目。我将帖子保存到 Firebase 中,如下所示:

let data = UIImageJPEGRepresentation(newPostImageView.image!, 0.5)//Take photo from imageview
let metadata = FIRStorageMetadata()
metadata.contentType = "image/jpeg"//Define post image path

let postId = "\(currentUser.generalDetails.uid)\(NSUUID().uuidString)"//Generate postId
let imagePath = "postImages\(postId)/postPic.jpg"

storageRef.child(imagePath).put(data!, metadata: metadata) { (metadata, error) in
if error == nil {

let postRef = self.databaseRef.child("posts").childByAutoId()


let post = Post(postImageUrl: String(describing: metadata?.downloadURL()), profileImageUrl: self.currentUser.generalDetails.profileImageURL, postId: postId, content: self.newPostTextView.text, username: self.currentUser.generalDetails.userName)
postRef.setValue(post.toAnyObject())

}else {
print(error!.localizedDescription)
}
}
dismiss(animated: true, completion: nil)

currentUser.generalDetails。 ... 是我的单例。

  1. 但是,它会像
  2. 一样将 "postImageUrl" 设置到 Firebase 中

"Optional(https://firebasestorage.googleapis.com/v0/b/"

我不明白为什么,因为我没有选择。 imagePicker 中的图像是可选的吗?

最佳答案

我认为 swift 在使用 if let 解开并测试 block 所需的所有先决条件时效果最好。

在此示例中,您需要一个未包装的图像 URL 作为不为空的字符串。

可以设置所有这些。

if let downloadUrl = metadata?.downloadURL() { // Unwrap the URL.
if let imageUrl = downloadUrl.absoluteString { // URL as a string.
if !imageUrl.isEmpty { // URL must not be empty.
}
}
}

幸运的是,这一切都可以在一行内完成。

if let imageUrl = metadata?.downloadURL()?.absoluteString, !imageUrl.isEmpty {
}

放在上下文中,给出以下内容。

storageRef.child(imagePath).put(data!, metadata: metadata) { (metadata, error) in
if let imageUrl = metadata?.downloadURL()?.absoluteString, !imageUrl.isEmpty {
let postRef = self.databaseRef.child("posts").childByAutoId()

let post = Post(postImageUrl: imageUrl,
profileImageUrl: self.currentUser.generalDetails.profileImageURL,
postId: postId,
content: self.newPostTextView.text,
username: self.currentUser.generalDetails.userName)

postRef.setValue(post.toAnyObject())
} else if error != nil {
print(error!.localizedDescription)
} else {
print("Unknown error")
}
}

最后,我们可以使用guard语句提前退出。这减少了主代码行中的缩进级别。

storageRef.child(imagePath).put(data!, metadata: metadata) { (metadata, error) in
guard let imageUrl = metadata?.downloadURL()?.absoluteString, !imageUrl.isEmpty else {
print(error?.localizedDescription ?? "Unknown error")
return
}

let postRef = self.databaseRef.child("posts").childByAutoId()

let post = Post(postImageUrl: imageUrl,
profileImageUrl: self.currentUser.generalDetails.profileImageURL,
postId: postId,
content: self.newPostTextView.text,
username: self.currentUser.generalDetails.userName)

postRef.setValue(post.toAnyObject())
}

关于ios - Swift 认为 Structure 中的变量是可选的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39957659/

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