UIImagepicker is uploading to the wrong Firebase storage - ios

I have two image views that I'm are used to have the user upload their photos on. When I go to upload the main profile picture everything runs fine and the image gets stored in the appropriate Firebase storage child, but when I press the next image view to upload my next photo, it gets stored in the wrong Firebase Storage.
I tried fixing this problem by having two separate uiimagepickers, but that didn't seem to solve the issue. So my question is, why is it when I press SecondPhoto, it uploads to Profile_Images and not Second_Images which is what I want?
import UIKit
import Firebase
import FBSDKLoginKit
class ProfileViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
#IBOutlet weak var imageView: UIImageView!
#IBOutlet weak var secondPhoto: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
self.imageView.frame.size.width / 2;
self.imageView.layer.cornerRadius = 24
self.imageView.clipsToBounds = true;
self.secondPhoto.layer.cornerRadius = self.secondPhoto.frame.size.height / 2;
secondPhoto.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(handleSecondProfileImageView)))
profilePicture.addGestureRecognizer(UITapGestureRecognizer(target:self, action: #selector(handleSelectProfileImageView)))
let uid = FIRAuth.auth()?.currentUser?.uid
FIRDatabase.database().reference().child("Users").child(uid!).observeSingleEvent(of: .value, with: {(snapshot) in if let dictionary = snapshot.value as? [String: AnyObject]
{
self.imageView.loadImageUsingCachWithUrlString(urlString:dictionary["profileImageUrl"] as! String)
self.secondPhoto.loadImageUsingCachWithUrlString(urlString:dictionary["secondImageUrl"] as! String)
}
}, withCancel: nil)
}
func handleSelectProfileImageView() {
let picker = UIImagePickerController()
picker.delegate = self
picker.allowsEditing = true
present(picker, animated: true, completion:nil)
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
var selectedImageFromPicker:UIImage?
if let editedImage = info["UIImagePickerControllerEditedImage"] as? UIImage{
selectedImageFromPicker = editedImage
}else if let originalImage = info["UIIMagePickerControllerOriginalImage"] as? UIImage{
selectedImageFromPicker = originalImage
}
if let selectedImage = selectedImageFromPicker{
updateProfileImageInFirebase(image: selectedImage)
}
dismiss(animated: true, completion: nil)
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
print("canceled picker")
dismiss(animated: true, completion: nil)
}
func updateProfileImageInFirebase(image: UIImage){
let user = FIRAuth.auth()?.currentUser
guard let uid = user?.uid else {
return
}
if user != nil {
let imageName = NSUUID().uuidString
let storageRef = FIRStorage.storage().reference().child("Profile_Images").child("\(imageName).jpg")
if let uploadData = UIImageJPEGRepresentation(image, 0.1) {
storageRef.put(uploadData, metadata: nil, completion: { (metadata, error) in
if error != nil {
print(error!)
return
}
if let profileImageUrl = metadata?.downloadURL()?.absoluteString {
FIRDatabase.database().reference().child("Users").child(uid).updateChildValues(["profileImageUrl": profileImageUrl])
}
})
}
}
}
func handleSecondProfileImageView() {
let picker = UIImagePickerController()
picker.delegate = self
picker.allowsEditing = true
present(picker, animated: true, completion:nil)
}
func secondimagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
var selectedImageFromPicker:UIImage?
if let editedImage = info["UIImagePickerControllerEditedImage"] as? UIImage{
selectedImageFromPicker = editedImage
}else if let originalImage = info["UIIMagePickerControllerOriginalImage"] as? UIImage{
selectedImageFromPicker = originalImage
}
if let selectedImage = selectedImageFromPicker{
updatesecondAvatarImageInFirebase(image: selectedImage)
}
dismiss(animated: true, completion: nil)
}
func secondimagePickerControllerDidCancel(_ picker: UIImagePickerController) {
print("canceled picker")
dismiss(animated: true, completion: nil)
}
func updatesecondAvatarImageInFirebase(image: UIImage){
let user = FIRAuth.auth()?.currentUser
guard let uid = user?.uid else {
return
}
if user != nil {
let imageName = NSUUID().uuidString
let storageRef = FIRStorage.storage().reference().child("Second_Images").child("\(imageName).jpg")
if let uploadData = UIImageJPEGRepresentation(image, 0.1) {
storageRef.put(uploadData, metadata: nil, completion: { (metadata, error) in
if error != nil {
print(error!)
return
}
if let secondImageUrl = metadata?.downloadURL()?.absoluteString {
FIRDatabase.database().reference().child("Users").child(uid).updateChildValues(["secondImageUrl": secondImageUrl])
}
})
}
}
}
}

I was able to solve it by adding adding tags to the buttons and using a switch control

Related

Image Picker does not crop the image for me correctly (swift) (firebase)

I have an image picker and after the image got picked, it should get uploaded into my Firebase Storage.
Now I have one problem: Somehow all the images dont get cropped correctly.
Did I misplace some Code, because that's the only thing I could think of, since I already got
picker.allowsEditing = true
The picture gets uploaded correctly, but not how I intended to crop it. The "cropper-window" shows up, but it doesnt get saved as intended.
Here is my code:
import UIKit
import Firebase
class editViewController: UIViewController {
#IBOutlet var pfp: UIImageView!
var fireImage: UIImage? = nil
override func viewDidLoad() {
super.viewDidLoad()
setupPfp()
}
func setupPfp(){
pfp.layer.cornerRadius = pfp.frame.height/2
pfp.clipsToBounds = true
pfp.isUserInteractionEnabled = true
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(presentPicker))
pfp.addGestureRecognizer(tapGesture)
}
#objc func presentPicker(){
let picker = UIImagePickerController()
picker.sourceType = .photoLibrary
picker.allowsEditing = true
picker.delegate = self
self.present(picker, animated: true, completion: nil)
}
func uploadToFirebase(){
guard let imageSelected = self.fireImage else {
print("Image is nil")
return
}
guard let imageData = imageSelected.jpegData(compressionQuality: 0.5) else {
return
}
let storageRef = Storage.storage().reference(forURL: "gs://lidjd-9dad5.appspot.com")
let storageProfileRef = storageRef.child("profileImages").child(Auth.auth().currentUser!.uid)
let metadata = StorageMetadata()
let db = Firestore.firestore()
let userID = Auth.auth().currentUser!.uid
let docRef = db.collection("users").document(userID)
metadata.contentType = "image/jpeg"
storageProfileRef.putData(imageData, metadata: metadata) { (storageMetaData, error) in
if error != nil{
print(error!.localizedDescription)
return
}
storageProfileRef.downloadURL { (url, error) in
if let metaImageUrl = url?.absoluteString{
print(metaImageUrl)
docRef.updateData([
"profileimage": metaImageUrl
]){ err in
if let err = err {
print("Error updating document: \(err)")
} else {
print("Profile Image successfully updated")
}}
}
}
}
}
}
extension editViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate{
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
if let imageSelected = info[UIImagePickerController.InfoKey.editedImage] as? UIImage {
fireImage = imageSelected
pfp.image = imageSelected
}
if let imageOriginal = info[UIImagePickerController.InfoKey.originalImage] as? UIImage {
fireImage = imageOriginal
pfp.image = imageOriginal
}
picker.dismiss(animated: true, completion: nil)
uploadToFirebase()
}
}
Choose one of them .. in your current code you are always using orignal image
extension editViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate{
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
if let imageSelected = info[UIImagePickerController.InfoKey.editedImage] as? UIImage {
fireImage = imageSelected
pfp.image = imageSelected
}
else if let imageOriginal = info[UIImagePickerController.InfoKey.originalImage] as? UIImage {
fireImage = imageOriginal
pfp.image = imageOriginal
}
picker.dismiss(animated: true, completion: nil)
uploadToFirebase()
}
}

Photo Uploads to Firebase Database and Storage but doesn't save photo in application

So I have an edit profile page where the user can change their profile picture and cover photo. I have it to where once the users selects their image, they click the saveButton and the photo is uploaded to Firebase Database and Firebase Storage and then the edit profile viewcontroller is dismissed and returns to profile view. Only problem I am having is that although the photo uploads to firebase, it doesn't save the image on the app if I close out and reopen it. I'm not sure what I am missing to make that happen. Here is the code below:
import UIKit
import Foundation
import Firebase
import FirebaseDatabase
class NewEditProfileViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
#IBOutlet weak var imageView1: UIImageView!
#IBOutlet weak var imageView2: UIImageView!
var ref = DatabaseReference.init()
var imagePicker = UIImagePickerController()
var imagePicked = 0
var selectedImage1: UIImage?
override func viewDidLoad() {
super.viewDidLoad()
self.ref = Database.database().reference()
self.saveFIRData()
imagePicker.delegate = self
imagePicker.sourceType = .photoLibrary
imagePicker.allowsEditing = true
}
#IBAction func chooseImage1(_ sender: Any) {
if UIImagePickerController.isSourceTypeAvailable(UIImagePickerController.SourceType.photoLibrary){
imagePicked = (sender as AnyObject).tag
present(imagePicker, animated: true)
}
}
#IBAction func chooseImage2(_ sender: Any) {
if UIImagePickerController.isSourceTypeAvailable(UIImagePickerController.SourceType.photoLibrary){
imagePicked = (sender as AnyObject).tag
present(imagePicker, animated: true)
}
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
let pickedImage = info[UIImagePickerController.InfoKey.editedImage] as? UIImage
let pickedImage2 = info[UIImagePickerController.InfoKey.editedImage] as? UIImage
if imagePicked == 1 {
self.imageView1.image = pickedImage
} else if imagePicked == 2 {
self.imageView2.image = pickedImage2
}
dismiss(animated: true)
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
dismiss(animated: true)
}
#IBAction func saveButton(_ sender: Any) {
self.saveFIRData()
self.dismiss(animated: true, completion: nil)
}
#IBAction func backButton(_ sender: Any) {
self.dismiss(animated: true, completion: nil)
}
#objc func saveFIRData() {
guard let image = imageView1.image else { return }
self.uploadProfileImage(image){ url in
self.saveProfileImage(profileURL: url!){ success in
if success != nil{
print("yes")
}
}
}
}
}
extension NewEditProfileViewController {
func uploadProfileImage(_ image:UIImage, completion: #escaping (_ url: URL?)->()) {
guard let uid = Auth.auth().currentUser?.uid else { return }
let storageRef = Storage.storage().reference().child("users/\(uid)")
let imageData = imageView1.image?.jpegData(compressionQuality: 0.8)
let metaData = StorageMetadata()
metaData.contentType = "image/jpeg"
storageRef.putData(imageData!, metadata: metaData) { (metaData, error) in
if error == nil{
print("success")
storageRef.downloadURL(completion: { (url, error) in
completion(url)
})
}else{
print("error in save image")
completion(nil)
}
}
}
func saveProfileImage(profileURL:URL, completion: #escaping ((_ url: URL?) -> ())){
guard let uid = Auth.auth().currentUser?.uid else { return }
let databaseRef = Database.database().reference().child("users/profilePhotoURL/\(uid)")
let userObject = [
"photoURL": profileURL.absoluteString
] as [String:Any]
self.ref.child("users").child(uid).setValue(userObject)
}
}
As I can see in your code in function
func saveProfileImage(profileURL:URL, completion: #escaping ((_ url: URL?) -> ()))
code to download image is missing you have to update your saveProfileImageto support download & then save to local app directory.
func saveProfileImage(profileURL:URL, completion: #escaping ((_ url: URL?) -> ())){
guard let uid = Auth.auth().currentUser?.uid else { return }
let databaseRef = Storage.storage().reference().child("users/profilePhotoURL/\(uid)")
// Download in memory with a maximum allowed size of 1MB (1 * 1024 * 1024 bytes), Change it according to your need
storageRef.getData(maxSize: 1 * 1024 * 1024) { data, error in
if let error = error {
// Uh-oh, an error occurred!
} else {
// Save `data` to your local directory here
let imageFilename = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] + "/" + "\(uid).jpg"
data.write(toFile: imageFilename, atomically: true)
}
}
let userObject = [
"photoURL": profileURL.absoluteString
] as [String:Any]
self.ref.child("users").child(uid).setValue(userObject)
}
}
Refer following sample code taken from Firebase guide Download to local section on file "Download File on iOS" page.
// Create a reference to the file you want to download
let islandRef = storageRef.child("images/island.jpg")
// Create local filesystem URL
let localURL = URL(string: "path/to/image")!
// Download to the local filesystem
let downloadTask = islandRef.write(toFile: localURL) { url, error in
if let error = error {
// Uh-oh, an error occurred!
} else {
// Local file URL for "images/island.jpg" is returned
}
}

Issue uploading an image to firebase storage

I am trying to write a function that will allow a user to set a new profile image, new image will be uploaded and the old image will be removed from firebase storage.
I have two functions that will do this and they work individually, however if I run the upload after the delete function the new image will not upload, even though I get a success message in the console nothing appears in the storage. Ideally I would like to remove first and the set the new image, and I have tried doing this multiple ways; completion handlers, adding delays but nothing has worked. I now even have two buttons one controlling each function to test this but this is still not working. What am I missing?? Any help would be great as ive spent hours racking my brains with this!
Here is my complete code for the VC:
//
// LandingVC.swift
// Login
//
// Created by George Woolley on 07/11/2017.
// Copyright © 2017 George Woolley. All rights reserved.
//
import UIKit
import FBSDKLoginKit
import SwiftKeychainWrapper
import Firebase
class MyAccountVC: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
#IBOutlet weak var profilePictureImg: UIImageView!
#IBOutlet weak var usernameField: UILabel!
#IBOutlet weak var saveButton: UIButton!
#IBOutlet weak var changeProfilePicButton: UIButton!
let picker = UIImagePickerController()
let myUID = KeychainWrapper.standard.string(forKey: "uid")
override func viewDidLoad() {
super.viewDidLoad()
picker.delegate = self
if myUID == nil {
print("You are not logged in")
} else {
let ref = DataService.ds.DBCurrentUser
ref.child("MyDetails").observe(.value, with: { (snapshot) in
if let snapshots = snapshot.children.allObjects as? [DataSnapshot] {
for snap in snapshots {
if snap.key == "username" {
self.usernameField.text = snap.value as? String
}
if snap.key == "profileImageURL" {
if let url = snap.value as? String {
let ref = Storage.storage().reference(forURL: url)
ref.getData(maxSize: 2 * 1024 * 1024, completion: { (data, error) in
if error != nil {
print("An error has occured downloading image")
} else {
print("Image downloaded")
if let imageData = data {
if let img = UIImage(data: imageData) {
self.profilePictureImg.image = img
}
}
}
})
}
}
}
}
})
}
}
func removeImgFromFirebaseStorage() {
let ref = DataService.ds.DBCurrentUser.child("MyDetails")
ref.observe(.value) { (snapshot) in
if let snapshots = snapshot.children.allObjects as? [DataSnapshot] {
for snap in snapshots {
if snap.key == "profileImageURL" {
if let url = snap.value as? String {
let img = Storage.storage().reference(forURL: url)
img.delete(completion: { (error) in
if error != nil {
print("Error is \(String(describing: error))")
} else {
print("Success")
}
})
}
}
}
}
}
saveButton.isHidden = false
changeProfilePicButton.isHidden = true
}
func uploadImageToFirebase() {
if let imageToUpload = profilePictureImg.image {
if let imageData = UIImageJPEGRepresentation(imageToUpload, 0.2) {
let metaData = StorageMetadata()
metaData.contentType = "image/jpeg"
let imageUID = UUID().uuidString
DataService.ds.StorageProfile.child(imageUID).putData(imageData, metadata: metaData, completion: { (metadata, error) in
if error != nil {
print("Error occured uploading profile image")
} else {
print("Sucess")
if let downloadURL = metadata?.downloadURL()?.absoluteString {
DataService.ds.DBCurrentUser.child("MyDetails").child("profileImageURL").setValue(downloadURL)
}
}
})
}
}
saveButton.isHidden = true
changeProfilePicButton.isHidden = false
}
#IBAction func saveButonPressed(_ sender: Any) {
uploadImageToFirebase()
}
#IBAction func changeProfilePicturePressed(_ sender: Any) {
picker.allowsEditing = true
picker.sourceType = .photoLibrary
picker.mediaTypes = UIImagePickerController.availableMediaTypes(for: .photoLibrary)!
present(picker, animated: true, completion: nil)
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
let chosenImage = info[UIImagePickerControllerOriginalImage] as! UIImage
profilePictureImg.contentMode = .scaleAspectFill
profilePictureImg.image = chosenImage
dismiss(animated: true, completion: removeImgFromFirebaseStorage)
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
dismiss(animated: true, completion: nil)
}
#IBAction func logOffPressed(_ sender: Any) {
KeychainWrapper.standard.removeObject(forKey: "uid")
performSegue(withIdentifier: "loginVC", sender: nil)
let fbLogin = FBSDKLoginManager()
fbLogin.logOut()
try! Auth.auth().signOut()
}
}

Creating an image format with an unknown type is an error did not upload image. Swift

Im trying to have users upload an Image and create an account. After the image is selected however, the user is then supposed to select, 'create account'. But the program is halted and does nothing after that. Then this message shows up in the compiler, 'Creating an image format with an unknown type is an error did not upload image.'
Here is the code.
import UIKit
import Firebase
import FirebaseDatabase
import FirebaseStorage
import SwiftKeychainWrapper
class SignUpVC: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
#IBOutlet weak var userImagePicker: UIImageView!
#IBOutlet weak var usernameField: UITextField!
#IBOutlet weak var signUpBtn: UIButton!
var userUid: String!
var emailField: String!
var passwordField: String!
var imagePicker: UIImagePickerController!
var imageSelected = false
var username: String!
override func viewDidLoad() {
super.viewDidLoad()
imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.allowsEditing = true
}
override func viewDidDisappear(_ animated: Bool) {
if let _ = KeychainWrapper.standard.string(forKey: "uid") {
performSegue(withIdentifier: "toMessage", sender: nil)
}
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
if let image = info[UIImagePickerControllerEditedImage] as? UIImage {
userImagePicker.image = image
imageSelected = true
} else {
print("image wasnt selected")
}
imagePicker.dismiss(animated: true, completion: nil)
}
func setUser(img: String) {
let userData = [
"username": username!,
"userImg": img
]
KeychainWrapper.standard.set(userUid, forKey: "uid")
let location = Database.database().reference().child("users").child(userUid)
location.setValue(userData)
dismiss(animated: true, completion: nil)
}
func uploadImg() {
if usernameField.text == nil {
signUpBtn.isEnabled = false
} else {
username = usernameField.text
signUpBtn.isEnabled = true
}
guard let img = userImagePicker.image, imageSelected == true else {
print("image needs to be selected")
return
}
if let imgData = UIImageJPEGRepresentation(img, 0.2) {
let imgUid = NSUUID().uuidString
let metadata = StorageMetadata()
metadata.contentType = "image/jpeg"
Storage.storage().reference().child(imgUid).putData(imgData, metadata: metadata) { (metadata, error) in
if error != nil {
print ("did not upload image")
} else {
print("uploaded")
let downloadURL = metadata?.downloadURL()?.absoluteString
if let url = downloadURL {
self.setUser(img: url)
}
}
}
}
}
#IBAction func createAccount (_ sender: AnyObject) {
Auth.auth().createUser(withEmail: emailField, password: passwordField, completion: {(user, error) in
if error != nil {
print("Cant create user")
} else {
if let user = user {
self.userUid = user.uid
}
}
self.uploadImg()
})
}
#IBAction func selectedImgPicker (_ sender: AnyObject) {
present(imagePicker, animated: true, completion: nil)
}
#IBAction func cancel (_ sender: AnyObject) {
dismiss(animated: true, completion: nil)
}
}
Sorry if this is too much, but I'm not exactly sure where to pin point this error since Xcode isn't showing it as an error. It seems as if the solution could be somewhere here but I am having trouble finding it. Thanks in advance.
You can use availableMediaTypes to make sure it only shows the valid image types.
let type = kUTTypeImage as String
let imagePicker = UIImagePickerController()
if UIImagePickerController.isSourceTypeAvailable(.camera) {
if let availableTypes = UIImagePickerController.availableMediaTypes(for: .camera) {
if availableTypes.contains(type) {
imagePicker.mediaTypes = [type]
imagePicker.sourceType = UIImagePickerControllerSourceType.camera
}
}
} else {
return
}
imagePicker.allowsEditing = true
imagePicker.showsCameraControls = true
imagePicker.delegate = self
Then you might also check UIImagePickerControllerOriginalImage
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
if let image = info[UIImagePickerControllerOriginalImage] as? UIImage ?? info[UIImagePickerControllerEditedImage] as? UIImage {
userImagePicker.image = image
imageSelected = true
} else {
print("image wasnt selected")
}
imagePicker.dismiss(animated: true, completion: nil)
}

Uploading Images from UIImage Picker onto new Firebase (Swift)

I have a UIImagePicker set up within my app that works fine. I would like to upload a profile picture to Firebase when my UIImage picker has been chosen. Here is my function for when a picture has been selected.
//image picker did finish code
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
let chosenImage = info[UIImagePickerControllerOriginalImage] as! UIImage
profilePic.contentMode = .ScaleAspectFill
profilePic.image = chosenImage
profilePic.hidden = false
buttonStack.hidden = true
changeButtonView.hidden = false
self.statusLabel.text = "Here is Your Profile Picture"
dismissViewControllerAnimated(true, completion: nil)
}
The new documentation states that we need to declare a NSURl in order to upload a file. Here is my attempt to find the NSURL of the given file, but it doesn't work. Here is the documentation and a link to it:https://firebase.google.com/docs/storage/ios/upload-files#upload_from_data_in_memory
// File located on disk
let localFile: NSURL = ...
// Create a reference to the file you want to upload
let riversRef = storageRef.child("images/rivers.jpg")
// Upload the file to the path "images/rivers.jpg"
let uploadTask = riversRef.putFile(localFile, metadata: nil) { metadata, error in
if (error != nil) {
// Uh-oh, an error occurred!
} else {
// Metadata contains file metadata such as size, content-type, and download URL.
let downloadURL = metadata!.downloadURL
}
}
Here is my attempt for retrieving the NSURL of the UIImagePicker:
//image picker did finish code
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
let chosenImage = info[UIImagePickerControllerOriginalImage] as! UIImage
//getting the object's url
let imageUrl = info[UIImagePickerControllerReferenceURL] as! NSURL
let imageName = imageUrl.lastPathComponent
let documentDir = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).first! as String;
let photoUrl = NSURL(fileURLWithPath: documentDir)
let localPath = photoUrl.URLByAppendingPathComponent(imageName!)
self.localFile = localPath
profilePic.contentMode = .ScaleAspectFill
profilePic.image = chosenImage
profilePic.hidden = false
buttonStack.hidden = true
changeButtonView.hidden = false
self.statusLabel.text = "Here is Your Profile Picture"
dismissViewControllerAnimated(true, completion: nil)
}
I believe that I am also running into difficulties if the image was taken from the camera instead of the gallery since it is not saved on the device yet. How do I find this image/snapshots's NSURL?
Here is my method to upload and download the user profile photo from firebase storage:
func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
userPhoto.image = image
dismissViewControllerAnimated(true, completion: nil)
var data = NSData()
data = UIImageJPEGRepresentation(userPhoto.image!, 0.8)!
// set upload path
let filePath = "\(FIRAuth.auth()!.currentUser!.uid)/\("userPhoto")"
let metaData = FIRStorageMetadata()
metaData.contentType = "image/jpg"
self.storageRef.child(filePath).putData(data, metadata: metaData){(metaData,error) in
if let error = error {
print(error.localizedDescription)
return
}else{
//store downloadURL
let downloadURL = metaData!.downloadURL()!.absoluteString
//store downloadURL at database
self.databaseRef.child("users").child(FIRAuth.auth()!.currentUser!.uid).updateChildValues(["userPhoto": downloadURL])
}
}
}
I also store the Image URL into firebase database and check if the user has a profile photo or you might get a crash:
//get photo back
databaseRef.child("users").child(userID!).observeSingleEventOfType(.Value, withBlock: { (snapshot) in
// check if user has photo
if snapshot.hasChild("userPhoto"){
// set image locatin
let filePath = "\(userID!)/\("userPhoto")"
// Assuming a < 10MB file, though you can change that
self.storageRef.child(filePath).dataWithMaxSize(10*1024*1024, completion: { (data, error) in
let userPhoto = UIImage(data: data!)
self.userPhoto.image = userPhoto
})
}
})
Simple 2020 example
Don't forget to add pod 'Firebase/Storage' to your podfile, and pod install
Add two delegates to your class
class YourScreen: UIViewController,
UIImagePickerControllerDelegate, UINavigationControllerDelegate {
Storyboard, button, link to ...
#IBAction func tapCameraButton() {
let picker = UIImagePickerController()
picker.allowsEditing = true
picker.delegate = self
present(picker, animated: true)
}
and then
func imagePickerController(_ picker: UIImagePickerController,
didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
guard let im: UIImage = info[.editedImage] as? UIImage else { return }
guard let d: Data = im.jpegData(compressionQuality: 0.5) else { return }
let md = StorageMetadata()
md.contentType = "image/png"
let ref = Storage.storage().reference().child("someFolder/12345678.jpg")
ref.putData(d, metadata: md) { (metadata, error) in
if error == nil {
ref.downloadURL(completion: { (url, error) in
print("Done, url is \(String(describing: url))")
})
}else{
print("error \(String(describing: error))")
}
}
dismiss(animated: true)
}
But where do you put the image?
At the code,
... .child("someFolder/12345678.jpg")
Almost inevitably,
• as the folder name use the user's id, the chat id, the feed id or a similar concept
• for the name, the only possibility is a uuid
Hence almost always
let f = chatId + "/" + UUID().uuidString + ".jpg"
let ref = Storage.storage().reference().child(f)
Working in Swift 4.2
Here i am doing click on image i have added tapGesture then it open gallery then selected image that upload in Firebase and also i add textField Value Too i hope it helps you Thank You
import UIKit
import Firebase
class ViewController: UIViewController {
#IBOutlet var myImageView: UIImageView!
#IBOutlet var txtText: UITextField!
var ref = DatabaseReference.init()
var imagePicker = UIImagePickerController()
override func viewDidLoad() {
super.viewDidLoad()
self.ref = Database.database().reference()
let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(ViewController.openGalleryClick(tapGesture:)))
myImageView.isUserInteractionEnabled = true
myImageView.addGestureRecognizer(tapGestureRecognizer)
myImageView.backgroundColor = UIColor.red
}
#objc func openGalleryClick(tapGesture: UITapGestureRecognizer){
self.setupImagePicker()
}
#IBAction func btnSaveClick(_ sender: UIButton) {
self.saveFIRData()
}
func saveFIRData(){
self.uploadMedia(image: myImageView.image!){ url in
self.saveImage(userName: self.txtText.text!, profileImageURL: url!){ success in
if (success != nil){
self.dismiss(animated: true, completion: nil)
}
}
}
}
func uploadMedia(image :UIImage, completion: #escaping ((_ url: URL?) -> ())) {
let storageRef = Storage.storage().reference().child("myimage.png")
let imgData = self.myImageView.image?.pngData()
let metaData = StorageMetadata()
metaData.contentType = "image/png"
storageRef.putData(imgData!, metadata: metaData) { (metadata, error) in
if error == nil{
storageRef.downloadURL(completion: { (url, error) in
completion(url)
})
}else{
print("error in save image")
completion(nil)
}
}
}
func saveImage(userName:String, profileImageURL: URL , completion: #escaping ((_ url: URL?) -> ())){
let dict = ["name": "Yogesh", "text": txtText.text!, "profileImageURL": profileImageURL.absoluteString] as [String : Any]
self.ref.child("chat").childByAutoId().setValue(dict)
}
}
extension ViewController: UINavigationControllerDelegate, UIImagePickerControllerDelegate{
func setupImagePicker(){
if UIImagePickerController.isSourceTypeAvailable(.savedPhotosAlbum){
imagePicker.sourceType = .savedPhotosAlbum
imagePicker.delegate = self
imagePicker.allowsEditing = true
self.present(imagePicker, animated: true, completion: nil)
}
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
let image = info[UIImagePickerController.InfoKey.originalImage] as! UIImage
myImageView.image = image
picker.dismiss(animated: true, completion: nil)
}
}

Resources