我尝试将图像上传到存储,并获取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])
}
})
})
}