为什么函数返回nil FireBase Swift

时间:2018-09-24 15:59:10

标签: swift firebase swift3

为什么函数都返回nil ?! 我尝试添加DispathQue,但我不知道它应该是正确的! 请帮助

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 个答案:

答案 0 :(得分:0)

您将在被调用者函数中的异步函数完成执行之前返回downloadURL
此时,它将具有nil值,这是正确的。
您将希望使用完成处理程序在downloadURL就绪后返回它,例如-

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