I'm using Firebase for iOS on my app the user has to associate a photo with his profile on MySQL there is BLOB type to save images inside the database but on Firebase I don't find such a thing
guard let uid = Auth.auth().currentUser?.uid else {return}
guard let imageData = UIImageJPEGRepresentation(profilePic, 0.5) else {return}
let profileImgReference = Storage.storage().reference().child("profile_image_urls").child("\(uid).png")
let uploadTask = profileImgReference.putData(imageData, metadata: nil) { (metadata, error) in
if let error = error {
print(error.localizedDescription)
} else {
let downloadURL = metadata?.downloadURL()?.absoluteString ?? ""
// Here you get the download url of the profile picture.
}
}
uploadTask.observe(.progress, handler: { (snapshot) in
print(snapshot.progress?.fractionCompleted ?? "")
// Here you can get the progress of the upload process.
})
Step 1: convert your UIImage to Jpeg Data or PNG Data by using UIImageJPEGRepresentation(UIImage, compressionQuality)
or UIImagePNGRepresentation(UIImage)
Step 2: Create a storage reference. In the above example I have used Storage.storage().reference()
to get the storage reference of the current Firebase app and then I am creating a folder by using .child("FolderName")
Step 3: Use Firebase Storage's .putData
function for upload the image data to firebase storage. You can capture the task reference (ie. uploadTask) for observing the progress of the upload.
// Note: I am using the Firebase user ID as the image name because every user id is unique for firebase Auth and there is no mismatch in profile picture replacing or getting deleted accidently.
You have to use Firebase Storage
to upload the image, and then get the URL and save the URL somewhere in your database.
Here's the documentation on how to upload files: https://firebase.google.com/docs/storage/ios/upload-files
Here's an example from one of my projects
FIRStorageReference *ref = [[[FIRStorage storage] reference] child:[NSString stringWithFormat:@"images/users/profilesPictures/pp%@.jpg", [UsersDatabase currentUserID]]];
[ref putData:imageData metadata:nil completion:^(FIRStorageMetadata * _Nullable metadata, NSError * _Nullable error) {
if (error) {
[[self viewController] hideFullscreenLoading];
[[self viewController] showError:error];
} else {
[ref downloadURLWithCompletion:^(NSURL * _Nullable URL, NSError * _Nullable error) {
if (error) {
[[self viewController] hideFullscreenLoading];
[[self viewController] showError:error];
} else {
[[self viewController] hideFullscreenLoading];
[self.profilePictureButton setImage:nil forState:UIControlStateNormal];
[[UsersDatabase sharedInstance].currentUser setProfilePictureURL:[URL absoluteString]];
[UsersDatabase saveCurrentUser]; // This also updates the user's data in the realtime database.
}
}];
}
}];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With