Why function return nil FireBase Swift [duplicate]

谁说胖子不能爱 提交于 2021-02-05 09:28:24

问题


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:


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


来源:https://stackoverflow.com/questions/52483163/why-function-return-nil-firebase-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!