0

** Update** My point is im trying to match my profilePicLink with image I upload from my library. Also selectedUsers is Users Type as following

var username : String = ""
var email : String = ""
var uid : String = ""
var profilePicLink : String  = ""

init(username : String, email: String, uid : String, profilePicLink: String ) {
    self.username = username
    self.email = email
    self.uid = uid
    self.profilePicLink = profilePicLink
}

I am having problem when I am trying to upload photo. The action are I pick the photo from my library

 @IBAction func getPhotoButton(_ sender: Any) {
        let image = UIImagePickerController()
        image.delegate = self
        image.sourceType = UIImagePickerController.SourceType.photoLibrary
        self.present(image, animated: true, completion: nil)
    }

It leads me to my photo library. After I pick my photo. I click on button "Update" with the action as following code

 @IBAction func updatePhoto(_ sender: Any) {
        uploadPhoto()
    }
    func uploadPhoto(){
        selectedUser?.uploadProfileImage(imageView.image!){
            url in print (URL.self)
        }

    }

I got the error as ** Fatal error: Unexpectedly found nil while unwrapping an Optional value: ** in the func uploadPhoto as the picture Fatal Error

And here is the code of func in my other class (Users) for upload and get Profile Image

func getProfileImage() -> UIImage {
    if let url = NSURL(string: profilePicLink){
        if let data = NSData(contentsOf: url as URL) {
            return UIImage(data: data as Data)!
        }
    }
    return UIImage()
}

func uploadProfileImage(_ image:UIImage, completion: @escaping ((_ url:URL?)->())) {
    guard let uid = Auth.auth().currentUser?.uid else { return }
    let storageRef = Storage.storage().reference().child("user/\(uid)")

    guard let imageData = image.jpegData(compressionQuality: 0.75) else { return }

    let metaData = StorageMetadata()
    metaData.contentType = "image/jpg"

    storageRef.putData(imageData, metadata: metaData) { metaData, error in
        if error == nil, metaData != nil {

            storageRef.downloadURL { url, error in
                completion(url)
                // success!
            }
        } else {
                // failed
            completion(nil)

        }
    }
}

Updated : I modifed my function uploadProfileImage as following. My point is I wanna assign profilePicLink variables to the downloadurl. And then I update value of profilePicLink

 func uploadProfileImage(_ image:UIImage, completion: @escaping ((_ url:URL?)->())) {

        let storageRef = Storage.storage().reference().child("profileImages").child("\(NSUUID().uuidString).jpg")


       guard let imageData = image.jpegData(compressionQuality: 0.75) else { return }

        let metaData = StorageMetadata()
        metaData.contentType = "image/jpg"

    storageRef.putData(imageData, metadata:metaData) { (metaData, error) in
        if error != nil, metaData != nil {
            storageRef.downloadURL (completion: {(url, error) in
                if error != nil {
                if let downloadurl = url?.absoluteString {
                if (self.profilePicLink == "") {
                self.profilePicLink = downloadurl
                   Database.database().reference().child("users").child(self.uid).updateChildValues(["profilePicLink":downloadurl])
                }
            }

        }   else {
            completion(nil)
            }
        }
            )
    }

        }

  }

Please be advised on this.

Jay
  • 34,438
  • 18
  • 52
  • 81
  • It appears this is `selectedUser` is causing the error but since we don't know what that is, it's just a guess. It seems to be nil and it's an optional `?`. Can you clarify what your asking and include more complete code regarding that var? Or it could be this `imageView.image!` as force-unwapping an optional is dangerous. You should handle that in case it's nil. – Jay Apr 14 '20 at 19:02
  • Not related, but why not `print (url)` instead of `print (URL.self)`? – Larme Apr 14 '20 at 19:12
  • Please don't post code in comments, it's very hard to read. Update your question with code. – Jay Apr 14 '20 at 19:35
  • For those voting to close this question as a duplicate, the OP is not asking what the error means, they are asking *why* they are getting the error. – Jay Apr 14 '20 at 19:37
  • 1
    Check `imageView.image`. Is it nil? If so, why is it nil? Where is it set? When? – Larme Apr 14 '20 at 19:41
  • @Larme I upaded my question. I am trying to get the pic I upload from my photolibrary as url and match it up with my profilePicLink. However, it gave me current error – Lan Nguyen Apr 14 '20 at 20:43
  • There is no indication where you did `imageView.image`. Or is `imageView` `nil` ? – Larme Apr 15 '20 at 10:22
  • Please do some troubleshooting so we can help you. Right before this line `selectedUser?.uploadProfileImage(imageView.image!){` add two print statements `print(selectedUser)` and then `print(imageView.image)` and see if either prints nil. – Jay Apr 15 '20 at 16:47
  • @jay this is what I get ```ObjectiveC.NSObject NSObject username String "Robin" email String "largo2904@gmail.com" uid String "4Ih3BjKemcMQlaBh2hNtTAtMDEo2" profilePicLink String "" image UIImage? nil none ``` – Lan Nguyen May 05 '20 at 05:36
  • So now we know two things.1) selectedUser is populated corrected and is not nil. 2) *imageView.image* is NIL and it's crashing because it's be force unwrapped with the !. Please be kind to your code and users and don't force unwrap optionals. Anything that's optional should be treated as if it could be nil - provide a default value if it is, or handle the nil situation so the app doesn't crash. You need to troubleshoot more to determine why that's nil. – Jay May 05 '20 at 13:12

0 Answers0