[英]Upload image from device to firebase
我一直試圖將圖像上傳到Firebase,然后將其設置為用戶的個人資料圖片。 出於某種原因,圖片的url地址為null,並且我相信它與該函數中的元數據有關:
func uploadProfileImage(_ image:UIImage, completion: @escaping((_url:URL?)->()))
{
guard let uid = Auth.auth().currentUser?.uid else { return }
let storageRef = Storage.storage().reference().child("user/\(uid)")
guard let imageData = image.jpegData(compressionQuality: 0.5) else {return}
let metaData = StorageMetadata()
metaData.contentType = "image/jpg"
storageRef.putData(imageData, metadata: metaData) { metaData, error in
if error == nil, metaData != nil {
storageRef.downloadURL { url, error in
completion(url)
// success!
}
}
}
}
在complition中返回的url為nil或錯誤!= nil,metaData == nil
以下是將圖像添加到Firebase存儲和數據庫中以供以后使用Swift 4使用的工作代碼
func uploadProfileImage(){
let storedImage = storagebaseRef.child("yourLocation")
if let uploadData = UIImageJPEGRepresentation(yourImg, 1)
{
storedImage.putData(uploadData, metadata: nil, completion: { (metadata, error) in
if error != nil {
}
storedImage.downloadURL(completion: { (url, error) in
if error != nil {
}
if let urlText = url?.absoluteString {
self.databaseRef.child("yourLocation").updateChildValues(["pic" : urlText], withCompletionBlock: { (error, ref) in
if error != nil {
self.showAlert(message: "Please Try Again", title: "Error")
return
}
})
}
})
})
}
}
這是一種快速解決方案,可以上傳具有給定文件名的圖像,然后獲取URL並將其存儲在此用戶個人資料中。
目前尚不清楚問題中使用了元數據。
這是未經測試的,所以可能有錯字。
func setUsersPhotoURL(withImage: UIImage, andFileName: String) {
guard let imageData = withImage.jpegData(compressionQuality: 0.5) else { return }
let storageRef = Storage.storage().reference()
let thisUserPhotoStorageRef = storageRef.child("this users uid").child(andFileName)
let uploadTask = thisUserPhotoStorageRef.putData(imageData, metadata: nil) { (metadata, error) in
guard let metadata = metadata else {
print("error while uploading")
return
}
thisUserPhotoStorageRef.downloadURL { (url, error) in
print(metadata.size) // Metadata contains file metadata such as size, content-type.
thisUserPhotoStorageRef.downloadURL { (url, error) in
guard let downloadURL = url else {
print("an error occured after uploading and then getting the URL")
return
}
let changeRequest = Auth.auth().currentUser?.createProfileChangeRequest()
changeRequest?.photoURL = downloadURL
changeRequest?.commitChanges { (error) in
//handle error
}
}
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.