从Firebase快速从图像中获取下载URL

时间:2018-11-07 01:24:58

标签: swift firebase firebase-realtime-database firebase-storage

我尝试将图像上传到存储,并获取downloadURL以存储在数据库中。该函数接收一个UIImage(从相机获取)和uid。

图像的上传工作正常,但是我无法从数据库中获取URL。看起来它没有运行.putData函数中的代码。

注意:将数据存储到数据库是可行的,但不能从该函数进行。

func uploadImage(image:UIImage, userID:String){
    // Get a reference to the storage service using the default Firebase App
    let storage = Storage.storage()

    // Create a storage reference from our storage service

    let storageRef = storage.reference()

    profileImage.image = image
    //  dismissViewControllerAnimated(true, completion: nil)
    var data = Data()
    //data = UIImageJPEGRepresentation(profileImage.image!, 0.8)! as NSData
    data = profileImage.image!.jpegData(compressionQuality: 0.8)!
    // set upload path
    let filePath = "users/\(userID)/\("userPhoto")"
    let metaData = StorageMetadata()
    metaData.contentType = "image/jpg"

    let refer = storageRef.child(filePath)

    refer.putData(data, metadata: metaData, completion: { metadata, error in

        if error != nil {
            print("Error: \(error!.localizedDescription)")
            return
        }
        refer.downloadURL(completion: { (url, error) in
            if error != nil {
                print("Failed to download url:", error!)
                return
            } else {
                //Do something with url
                let URL = (url?.absoluteString)!
                print(URL)
                self.databaseRef.child("users").child(userID).updateChildValues(["userPhoto": URL])
            }

        })
    }) 
}

0 个答案:

没有答案