问题
Hey I am new to Xcode and need of assistance in uploading my profile image from firebase database to my user profile. I have receive no errors so far but the image is not appearing when my user logs in, the image is already stored in firebase but when I attach the UIImageView to the user profile the image shows up blank do anyone have a solution to fix this code to make my image appear on the user profile once they log in it should be automatic?
typealias blockCompletedWith = (Bool, String) -> Void
//path: folder name if any followed by name of image
func uploadImageToFirebaseStorage(data: Data, path: String, blockCompletedWith: @escaping blockCompletedWith) {
let metadata = StorageMetadata()
metadata.contentType = "profileImage.jpg"
let store = Storage.storage()
let storeRef = store.reference().child(path)
let _ = storeRef.putData(data, metadata: metadata) { (metadata, error) in
guard let _ = metadata else {
print("error occured: \(error.debugDescription)")
blockCompletedWith(false, "")
return
}
storeRef.downloadURL(completion: { (url, error) in
if let urlText = url?.absoluteString {
blockCompletedWith(true, urlText)
}
else {
blockCompletedWith(false, "")
}
})
}
}
if let profileImageUrl = dictionary?["gs://tunnel-vision-d6825.appspot.com"] as? String {
let url = URL(string: profileImageUrl)
URLSession.shared.dataTask(with: url!) { (data, response, error) in
if let error = error{
print("Error : \(error)")
return
}
DispatchQueue.main.async {
self.ProfileImage.image = UIImage(data: data!)
}
}.resume()
}
回答1:
Use firebase storage to save images and put the image link into your database.
typealias blockCompletedWith = (Bool, String) -> Void
func uploadProfileImage(_ image: UIImage) {
let imageData = image.jpegData(compressionQuality: 1.0)
let path = "folderName/imagename.jpeg"
self.uploadImageToFirebaseStorage(data: imageData!, path: path, blockCompletedWith: { (isSuccess, urlStr) in
Utility.stopActivityIndicator()
DispatchQueue.main.async {
if isSuccess {
print(urlStr)
}
else {
print("Error in uploading Image")
}
}
})
}
-----------uploadImageToFirebaseStorage Method------------
//path: folder name if any followed by name of image
func uploadImageToFirebaseStorage(data: Data, path: String, blockCompletedWith: @escaping blockCompletedWith) {
let metadata = StorageMetadata()
metadata.contentType = "image/jpeg"
let store = Storage.storage()
let storeRef = store.reference().child(path)
let _ = storeRef.putData(data, metadata: metadata) { (metadata, error) in
guard let _ = metadata else {
print("error occured: \(error.debugDescription)")
blockCompletedWith(false, "")
return
}
storeRef.downloadURL(completion: { (url, error) in
if let urlText = url?.absoluteString {
blockCompletedWith(true, urlText)
}
else {
blockCompletedWith(false, "")
}
})
}
}
来源:https://stackoverflow.com/questions/59869348/how-to-set-up-profile-image-from-firebase-database