0

Why ever function return nil?! I try add DispathQue but I don't understand how it should be right! Pls Help

func storagePutData(uid: String, image: UIImage, compretition: @escaping (Error?) -> Void) -> String {
            var downloadURL: String!
            let imageName = NSUUID().uuidString
            let uploadDara = UIImageJPEGRepresentation(image, 0.1)!
            let ref = self.refStorage.child("usersProfileImage/\(uid)/\(imageName).png")

            ref.putData(uploadDara, metadata: nil) { (metaDara, error) in
                if let err = error {
                    compretition(err)
                }
                ref.downloadURL(completion: { (url, error) in
                    if let err = error {
                        compretition(err)
                    } else {
                        downloadURL = url?.absoluteString
                    }
                })
            }
            return downloadURL
        }

1 Answers1

0

You're returning downloadURL before the asynchronous function within your callee function has finished execution.
At this point, it will have nil value, which is correct.
You'll want to use a completion handler to return downloadURL when its ready, like -

func storagePutData(uid: String, image: UIImage, success:@escaping (String?)->(), error: @escaping (Error?) -> Void) {
        var downloadURL: String!
        let imageName = NSUUID().uuidString
        let uploadDara = UIImageJPEGRepresentation(image, 0.1)!
        let ref = self.refStorage.child("usersProfileImage/\(uid)/\(imageName).png")

        ref.putData(uploadDara, metadata: nil) { (metaDara, error) in
            if let err = error {
                error(err)
            }
            ref.downloadURL(completion: { (url, error) in
                if let err = error {
                    error(err)
                } else {
                    downloadURL = url?.absoluteString
                    success(downloadURL)
                }
            })
        }
    }
Code.Decode
  • 3,736
  • 4
  • 25
  • 32
  • Tnx It work!! But can you help again?! I try create a singleton class for Firebase and it work! FirebaseAPI.shared.signUP(name: name, email: email, password: password, image: self.profileImageView.image!) { (error) in if let err = error { print("error") self.showAlert(message: err.localizedDescription) } else { print("hello") self.dismiss(animated: true, completion: nil) } } When error == nil I have alert, but when error != nil I haven't nothing –  Sep 24 '18 at 18:01
  • I'm sure if your snippet had typo in it, but can you try with this? - `FirebaseAPI.shared.signUP(name: name, email: email, password: password, image: self.profileImageView.image!) { let err = error; if (error) { print("error"); self.showAlert(message: err.localizedDescription); } else { print("hello"); self.dismiss(animated: true, completion: nil); } }` – Code.Decode Sep 26 '18 at 21:36
  • Ohhh, tnx) I did it)) –  Sep 28 '18 at 09:19