gpt4 book ai didi

swift - 从 UIImagePicker 上传图片到 Firebase

转载 作者:行者123 更新时间:2023-11-28 11:32:35 25 4
gpt4 key购买 nike

当我的 UIImage 选择器被选中时,我想将个人资料图片上传到 Firebase。但我不知道该怎么做我无法理解文档,因为我是编码新手)。请帮我。我需要将图片上传到 Firebase。它将是用户图片,因此对图片的引用应保存到数据库中。

extension ProfileViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {




let image = info[UIImagePickerController.InfoKey.originalImage] as! UIImage
profileImage.image = image
picker.dismiss(animated: true, completion: nil)
}

我不知道如何上传和下载个人资料图片。

最佳答案

创建存储引用并添加文件夹名称和图像名称。

Storage.storage().reference().child("id").child("profile.png")

并使用putData:metadata:completion:方法上传图片。上传图片后,获取图片 url 并在用户详细信息中更新它。

上传个人资料图片

import FirebaseStorage
import FirebaseAuth

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
if let image = info[.originalImage] as? UIImage, let imageData = image.pngData() {
profileImage.image = image
let storageRef = Storage.storage().reference().child("id").child("profile.png")
let metaData = StorageMetadata()
metaData.contentType = "image/png"
storageRef.putData(imageData, metadata: metaData) { (metaData, error) in
if error == nil, metaData != nil {
storageRef.downloadURL { url, error in
if let url = url {
print(url)//URL of the profile image
self.saveProfileImageUrlInUserDetails(url: url)
}
}
} else {
print(error?.localizedDescription)//upload failed
}
}
}
picker.dismiss(animated: true, completion: nil)
}

在用户详细信息中保存上传的照片引用 Update the user's profile

func saveProfileImageUrlInUserDetails(url: URL) {
let changeRequest = Auth.auth().currentUser?.createProfileChangeRequest()
changeRequest?.photoURL = url
changeRequest?.commitChanges(completion: { error in
if error == nil {
//saved
} else {
print(error?.localizedDescription)//failed to udpate
}
})
}

下载个人资料图片

if let profileImgUrl = Auth.auth().currentUser?.photoURL?.absoluteString {
let ref = Storage.storage().reference(forURL: profileImgUrl)
ref.getData(maxSize: 1 * 1024 * 1024) { data, error in
if let error = error {
print(error.localizedDescription)
} else if let data = data, let image = UIImage(data: data) {
self.profileImage.image = image
}
}
}

关于swift - 从 UIImagePicker 上传图片到 Firebase,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56407641/

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