首页 > 解决方案 > FirebaseStorage 无法为元数据创建 downloadURL

问题描述

我正在尝试使用 Firebase 云存储和实时数据库。在第一个中,我正在上传图像,然后尝试将 downloadUrl 保存在后者中。在将 Firebase pod 更新到 5.0.0 以使用 MLKit 之前,一切正常。在 StorageService 中,我正在上传图像(有效,我可以在 firebase 控制台上看到它),然后在 PostService 中创建一个满足我所有需求的字典

struct StorageService {
    static func uploadImage(_ image: UIImage, at reference: StorageReference, completion: @escaping (URL?) -> Void) {
        guard let imageData = UIImageJPEGRepresentation(image, 0.5) else {
            return completion(nil)
        }
        reference.putData(imageData, metadata: nil, completion: { (metadata, error) in
            if let error = error {
                assertionFailure(error.localizedDescription)
                return completion(nil)
            }
            completion(metadata?.downloadURL())
        })
    }
}

struct PostService {
    static func create(for image: UIImage) {
        let imageRef = StorageReference.newPostImageReference()
        StorageService.uploadImage(image, at: imageRef) { (downloadURL) in
            guard let downloadURL = downloadURL else {
                return
            }
            print("bum")
            let urlString = downloadURL.absoluteString
            let aspectHeight = image.aspectHeight
            create(forURLString: urlString, aspectHeight: aspectHeight)
        }
    }
    
    private static func create(forURLString urlString: String, aspectHeight: CGFloat) {
        //save the text
        let currentUser = User.current
        let post = Post(imageURL: urlString, imageHeight: aspectHeight)
        let dict = post.dictValue
        let postRef = Database.database().reference().child("posts").child(currentUser.uid).childByAutoId()
        postRef.updateChildValues(dict)
    }
}

标签: iosswiftfirebasefirebase-storage

解决方案


Firebase iOS SDK 5.0 中的一项重大更改删除了downloadURLStorageMetadata 上的属性。用于StorageReference.downloadURL(completion:)获取当前下载 URL。

reference.downloadURL { url, error in
  if let error = error {
    // Handle any errors
  } else {
    // Get the download URL
  }
}

推荐阅读