1

When using an image picker to grab the image selected and place in firebase storage I want to be able to download the URL and take place of the profile image inside the app. Unfortunately, when the process reaches the URLSession in the script nothing happens. There is not an error display nor does it dispatchQueue. The app will not crash but just skip over everything. Any ideas or suggestions to a code fix?

  if let profileImageUploadedData = self.profileImage.image, let uploadData = profileImage.image?.jpegData(compressionQuality: 0.1)
            {

                storageRef.putData(uploadData, metadata: nil, completion: { (metadata, error) in
                    if error != nil
                    {
                        print("Downdloading putData Error: \(error!.localizedDescription)")
                        return
                    }
                    storageRef.downloadURL(completion: { (url, error) in
                        if error != nil
                        {
                            print("DownloadURL ERROR \(error!.localizedDescription)")
                            return
                        }

                        if let profileImageUrl = url?.absoluteString
                        {
                            print("Profile image uploading...")
                            let values = ["profileImageUrl": profileImageUrl]

                            let url = URL(fileURLWithPath: profileImageUrl)
                            URLSession.shared.dataTask(with: url) { (data, response, error) in // ERROR OCCURING NEED TO FIX
                                if error != nil
                                {
                                    print("* URL SESSIONS ERROR: \(error!)")
                                    return
                                }
                                DispatchQueue.main.async
                                {
                                    print("Trying to register profile")
                                    self.registerUserIntoDatabaseWithUID(uid: uid, values: values as [String : AnyObject])
                                    self.profileImage.image = UIImage(data: data!)
                                    print("Dispatch: \(data!)")
                                }

                                print("Profile image successfull uploaded to storage")
                            }
                        }
                    })

                }).resume()
                print("** Profile Image Data Uploaded:\(profileImageUploadedData)")
            }
}

func registerUserIntoDatabaseWithUID(uid: String, values: [String: AnyObject])
{
    print("Registering to database")
    let dataReference = Database.database().reference(fromURL: "URL String")
    let usersReference = dataReference.child("users").child(uid)
    usersReference.updateChildValues(values, withCompletionBlock: { (err, reference) in
        if err != nil
        {
            print(err!)
            return

        }
//            self.profileImage.image = values["profileImageUrl"] as? UIImage
//            self.fetchProfileImage()
        self.dismiss(animated: true, completion: nil)
            print("Saved user sussccessfully in database")

        })

    }
}
Cal
  • 422
  • 6
  • 20
  • It's a bit unclear what you're trying to do here. If you want to download an image from Storage based on a URL, that's not really how to do it. You would typically craft a ref based on the url and then use .getData to download the actual file. Or are you trying to upload a selected image, and then get the URL for where it's stored and keep that in your app? Or... something else? – Jay Dec 26 '18 at 19:13
  • Hello Jay, I am trying to upload a selected image and then get the url from where its stored and display that image every time the user logouts and logs back into the app @Jay – Michael Edlin Dec 26 '18 at 19:30
  • @Jay I also, added another piece to the scripting I currently have to get a better understanding. Much appreciated for your time! – Michael Edlin Dec 26 '18 at 19:41
  • Unfortunately, none of the code in the question really does that - also noting that you've got 3 different questions rolled into one. !) How to upload an image to storage and store it's url in Firebase Database 2) How to download an image from storage 3) How to get the url from Firebase database upon login to perform the download in #2. At a high level the process is: Authenticate User->Get UID->Get download URL from Firebase Database->Download image. Can you narrow the question a bit and we'll take a look! – Jay Dec 26 '18 at 20:32
  • 1
    @Jay I completely understand. So in the script it does complete the task of uploading the image to storage in firebase. The main question would be how to get the downloadURL and download the image to the profileImage. – Michael Edlin Dec 26 '18 at 20:57

1 Answers1

1

This is a big question that is actually asking for a number of different answers so let's just focus on one;

How to authenticate a user, get a url stored in Firebase Database that references an image stored in Firebase Storage, then download that image.

Here we go

First - authenticate a user

Auth.auth().signIn(withEmail: user, password: pw, completion: { (auth, error) in
    if let x = error {
       //handle an auth error
    } else {
        if let user = auth?.user {
            let uid = user.uid
            self.loadUrlFromFirebaseDatabase(withUid: uid)
        }
    }
})

now the user is authenticated, get the image location url from Firebase Database

func loadUrlFromFirebaseDatabase(withUid: String) {
    let thisUserRef = self.ref.child("users").child(withUid)
    let urlRef = thisUserRef.child("url")
    urlRef.observeSingleEvent(of: .value, with: { snapshot in
        if let url = snapshot.value as? String {
            self.loadImageUsingUrl(url: url)
        } else {
            print("no image for user")
        }
    })
}

Now that we have the location of the image in Firebase Storage, get it

func loadImageUsingUrl(url: String) {
    let storage = Storage.storage()
    let imageRef = storage.reference(forURL: url)
    imageRef.getData(maxSize: 1 * 1024 * 1024) { data, error in
        if let error = error {
            print("error downloading \(error)")
        } else {
            if let image = UIImage(data: data!) {
                //do something with the image
            } else {
                print("no image")
            }
        }
    }
}
Jay
  • 34,438
  • 18
  • 52
  • 81