我想从firebase存储ios swift获取图像的下载URL

时间:2017-09-11 09:28:31

标签: ios swift image firebase firebase-storage

我正在使用firebase上传一些图片,其工作正常,但问题我无法获取图片的下载网址

这里是我的代码

@IBAction func btnUploadImgsAction(_ sender: UIButton) {


    let url1 = uploading(img: Img1)
    print("///////////img 1   //////// \(url1)   ////////")
    let url2 = uploading(img: Img2)
    print("///////////img 2   //////// \(url2)   ////////")
    let url3 = uploading(img: Img3)
    print("///////////img 3   //////// \(url3)   ////////")
    let url4 = uploading(img: Img4)
    print("///////////img 4   //////// \(url4)   ////////")


}


func uploading( img : UIImageView)-> String{
    var strURL = ""
    let imageName = NSUUID().uuidString
    let storeImage = self.storageRef.child("profile_Images").child(imageName)

    if let uploadImageData = UIImagePNGRepresentation((img.image)!){
        storeImage.putData(uploadImageData, metadata: nil, completion: { (metaData, error) in
            storeImage.downloadURL(completion: { (url, error) in
                if let urlText = url?.absoluteString {

                     strURL = urlText
                    print("///////////tttttttt//////// \(strURL)   ////////")


                }
            })
        })


    }

    return strURL
}

当我在上传方法中打印strURL时,url会出现但是当我在btnUploadImgsAction中打印时它不会出现,什么是错误的? 请提前帮助谢谢

1 个答案:

答案 0 :(得分:4)

您应该创建一个闭包方法,而不是直接返回字符串的方法,因为此方法是异步方法

您的方法声明应如下所示

func uploading( img : UIImageView, success: (url: String) -> Void) {
 // return with clouser
 success(url: strurl)
}

更新了您的方法

func uploading( img : UIImageView, completion: @escaping ((String) -> Void)) {
    var strURL = ""
    let imageName = NSUUID().uuidString
    let storeImage = self.storageRef.child("profile_Images").child(imageName)

    if let uploadImageData = UIImagePNGRepresentation((img.image)!){
        storeImage.putData(uploadImageData, metadata: nil, completion: { (metaData, error) in
            storeImage.downloadURL(completion: { (url, error) in
                if let urlText = url?.absoluteString {

                    strURL = urlText
                    print("///////////tttttttt//////// \(strURL)   ////////")

                    completion(strURL)
                }
            })
        })
    }
}

函数调用将是

let str = uploading(img: imageObject) { (url) in
     print(url)
 }