Issue uploading an image to firebase storage - ios

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()
}
}

Related

Image doesn't upload to firebase storage, swift

Here is the code
import UIKit
import Photos
import Firebase
import FirebaseStorage
class SignUpViewController: UIViewController {
#IBOutlet weak var userNameTextField: UITextField!
#IBOutlet weak var emailTextField: UITextField!
#IBOutlet weak var passwordTextField: UITextField!
#IBOutlet weak var errorLabel: UILabel!
#IBOutlet weak var tapToChangeButton: UIButton!
#IBOutlet weak var profileImageView: UIImageView!
var imagePickerController = UIImagePickerController()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
userNameTextField.backgroundColor = .clear
userNameTextField.layer.cornerRadius = 27
userNameTextField.layer.borderWidth = 1
userNameTextField.layer.borderColor = UIColor.systemGreen.cgColor
emailTextField.backgroundColor = .clear
emailTextField.layer.cornerRadius = 27
emailTextField.layer.borderWidth = 1
emailTextField.layer.borderColor = UIColor.systemGreen.cgColor
passwordTextField.backgroundColor = .clear
passwordTextField.layer.cornerRadius = 27
passwordTextField.layer.borderWidth = 1
passwordTextField.layer.borderColor = UIColor.systemGreen.cgColor
let imageTap = UITapGestureRecognizer(target: self, action: #selector(openImagePicker))
profileImageView.isUserInteractionEnabled = true
profileImageView.addGestureRecognizer(imageTap)
profileImageView.layer.cornerRadius = profileImageView.bounds.height / 2
profileImageView.clipsToBounds = true
tapToChangeButton.addTarget(self, action: #selector(openImagePicker), for: .touchUpInside)
imagePickerController = UIImagePickerController()
imagePickerController.allowsEditing = true
imagePickerController.sourceType = .photoLibrary
imagePickerController.delegate = self
checkPermissions()
}
#objc func openImagePicker(_ sender:Any) {
// Open Image Picker
self.present(imagePickerController, animated: true, completion: nil)
}
func checkPermissions() {
if PHPhotoLibrary.authorizationStatus() != PHAuthorizationStatus.authorized {
PHPhotoLibrary.requestAuthorization({ (status:
PHAuthorizationStatus) -> Void in
()
})
}
if PHPhotoLibrary.authorizationStatus() == PHAuthorizationStatus.authorized {
} else {
PHPhotoLibrary.requestAuthorization(requestAuthorizationHandler)
}
}
func requestAuthorizationHandler(status: PHAuthorizationStatus) {
if PHPhotoLibrary.authorizationStatus() == PHAuthorizationStatus.authorized {
print("Have authorization")
} else {
print("Authorization declined")
}
}
After pressing the signUp button the uploadToCloud function should be performed but I don't know how to fetch the url from image picker
#IBAction func signupPressed(_ sender: UIButton) {
guard let username = self.userNameTextField.text, username.count > 3 else {
self.errorLabel.text = "Please enter a valid username"
return
}
guard let password = passwordTextField.text else {
self.errorLabel.text = "Please enter a valid password"
return
}
guard let email = emailTextField.text else {
self.errorLabel.text = "Please enter a valid email"
return
}
Auth.auth().createUser(withEmail: email, password: password) { authResult, error in
if let e = error {
self.errorLabel.text = e.localizedDescription
} else {
//Navigate to the ChatViewController
let db = Firestore.firestore()
db.collection("users").addDocument(data: ["username": username, "uid": authResult!.user.uid]) { (error) in
if let e = error {
// You may not want to show this error to the user but you should still show a "sanitised" error so that it doesn't leak information.
self.errorLabel.text = e.localizedDescription
} else {
self.performSegue(withIdentifier: "goToMap", sender: self)
}
}
}
}
}
func uploadToCloud(fileURL: URL) {
guard let uid = Auth.auth().currentUser?.uid else { return }
let storage = Storage.storage()
let data = Data()
let storageRef = storage.reference()
let localFile = fileURL
let photoRef = storageRef.child("users/\(uid)")
let uploadTask = photoRef.putFile(from: localFile, metadata: nil) { (metadata, error) in
guard let metadata = metadata else {
self.errorLabel.text = error?.localizedDescription
return
}
metadata.contentType = "image/jpg"
}
}
}
extension SignUpViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
picker.dismiss(animated: true, completion: nil)
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
if let pickedImage = info[UIImagePickerController.InfoKey.editedImage] as? UIImage {
self.profileImageView.image = pickedImage
}
if let url = info[UIImagePickerController.InfoKey.imageURL] as? URL {
uploadToCloud(fileURL: url)
}
picker.dismiss(animated: true, completion: nil)
}
}
I don't understand your problem well, But I think the problem is your
uploadToCloud function.
This is another version of your function which is more easier to me
func uploadToCloud(with profileImage:UIImage){
let storage = Storage.storage().reference()
guard let uid = Auth.auth().currentUser?.uid else { return }
guard let imageData = profileImage.pngData() else{
return
}
storage.child("users/\(uid)").putData(imageData, metadata: nil) { (StorageMetadata, error) in
guard StorageMetadata != nil else{
print("oops an error occured while data uploading")
return
}
print("Image sent")
}
}

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
}
}

Initializer for conditional binding error while trying to build Login

I am trying to finish my login page for a social media app and I have one error which I can't seem to figure out.
Here is the full code:
import UIKit
import Firebase
import FirebaseAuth
import FirebaseStorage
import FirebaseDatabase
import SwiftKeychainWrapper
class UserVC: UIViewController, UIImagePickerControllerDelegate,
UINavigationControllerDelegate
{
#IBOutlet weak var userImagePicker: UIButton!
#IBOutlet weak var CompleteSignInBtn: UIButton!
#IBOutlet weak var usernameField: UITextField!
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
}
func keychain(){
KeychainWrapper.standard.set(userUid, forKey: "uid")
}
func imagePickerController(_ picker: UIImagePickerController,
didFinishPickingMediaWithInfo info: [String : Any]) {
if let image = info[UIImagePickerControllerEditedImage] as? UIImage {
userImagePicker.setImage(image,for:.normal)
imageSelected = true
} else {
print("Image was not selected")
}
imagePicker.dismiss(animated: true, completion: nil)
}
func setUpUser(img: String ){
let userData = [
"username": username!,
"userImg": img
]
keychain()
let setLocation = Database.database().reference().child(userUid)
setLocation.setValue(userData)
}
func uploadImg() {
if usernameField.text == nil {
print("Please choose a username")
CompleteSignInBtn.isEnabled = false
} else {
username = usernameField.text
CompleteSignInBtn.isEnabled = true
}
guard let img = userImagePicker.image, imageSelected == true else {
print("image must be selected")
return
}
if let imgData = UIImageJPEGRepresentation(img, 0.2){
let imgUid = NSUUID().uuidString
let metadata = StorageMetadata()
metadata.contentType = "img/jpeg"
Storage().reference().child(imgUid).put(imgData, metadata: metadata) { (metadata, error) in
if error =! nil {
print("Did not upload")
} else{
print("Uploaded")
let downloadURl = metadata?.downloadURL()?.absoluteString
if let url = downloadURl {
self.setUpUser(img: url)
}
}
}
}
}
#IBAction func completeAccount(_ sender: Any){
Auth.auth().createUser(withEmail: emailField, password: passwordField, completion: { (user, error) in
if error != nil {
print("Error\(error)")
} else {
if let user = user {
self.userUid = user.uid
}
}
self.uploadImg()
})
dismiss(animated: true, completion: nil)
}
#IBAction func seletedImagePicker(_ sender: Any){
present(imagePicker, animated: true, completion: nil)
}
#IBAction func cancel(_ sender: AnyObject){
dismiss(animated: true, completion: nil)
}
}
The code which is causing the error mentioned in the title is this:
guard let img = userImagePicker.image, imageSelected == true else {
print("image must be selected")
return
}
I have no idea what to do. I read that is has something to do with the fact that userimagePicker.image might not be optional, but in a guide I am following it works.
Thanks!
You've declared userImagePicker as UIButton and UIButton has no property called image. You should use currentImage
guard let img = userImagePicker.currentImage, imageSelected == true else {
print("image must be selected")
return
}

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)
}

UIImagepicker is uploading to the wrong Firebase storage

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

Resources