尝试获取存储参考的下载URL来填充标签

时间:2019-05-20 09:15:00

标签: swift firebase firebase-storage

我正在使用Xcode 10和此方法将在应用程序中选择的照片上传到Firebase Storage。它已成功上传了照片,但是,我试图获取下载URL并将其填充到同一屏幕上的标签中。

我已经尝试过metadata.downloadURL,但是这引发了错误的元数据,不再能够识别Xcode 10中的downloadURL。

这是我的功能...

   func uploadPhoto(completion: @escaping (_ url: String?) -> Void) {

    let photoName = NSUUID().uuidString
    let storageRef = Storage.storage().reference().child("photoURL").child("\(photoName).jpg")

    let photo = self.photoImageView.image!

    if let uploadData = photo.jpegData(compressionQuality: 0.75) {
        storageRef.putData(uploadData, metadata: nil) { (metadata, error) in

            guard metadata != nil else {
                // Uh-oh, an error occurred!
                return
            }
            // Metadata contains file metadata such as size, content-type.
            //let size = metadata?.size

            // You can also access to download URL after upload.
            storageRef.downloadURL { (url, error) in
                guard url != nil else {
                    // Uh-oh, an error occurred!
                    return
                }

                // Metadata contains file metadata such as size, content-type, and download URL.

                // THROWS ERROR
                // let downloadURL = metadata.downloadURL

                // MY ATTEMPT
                var downloadURL = StorageReference.downloadURL(self.refStorage)
               completion(downloadURL = self.urlLabel.text) 
            }
        }
    }
}

1 个答案:

答案 0 :(得分:0)

您需要

storageRef.put(uploadData, metadata: nil, completion: { (metadata, error) in
    if(error != nil){
        print(error)
        return
    }

    storageRef.downloadURL { url, error in
        if let error = error {
            // Handle any errors
            if(error != nil){
                print(error) 
            }
        } else {
            // Get the download URL for 'images/stars.jpg'

            let urlStr:String = (url?.absoluteString) ?? ""
            print(urlStr)
        }
    }
})