简体   繁体   English

如何在不同视图之间共享从Firebase存储下载的图像?

[英]How to share image downloaded from firebase storage between different views?

This is the code i use to fetch the image from the storage. 这是我用来从存储中获取图像的代码。 It works like charm but i dont want to redownload it on different views again. 它像魅力一样工作,但我不想再次在不同的视图上重新下载它。

func retreiveImagesFromFireBase(downloadUrl:String,imageHolder:UIImageView){
    if downloadUrl != "" {
        let storageRef = Storage.storage().reference(forURL: downloadUrl)
        // Download the data, assuming a max size of 1MB (you can change this as necessary)
        storageRef.getData(maxSize: 5*1024*1024) { (data, error) in
            if error == nil {
                if let pic = UIImage(data: data!) {
                    imageHolder.image = pic
                }
            } else {
                print(error)
            }
        }
    }
}

How should i handle this? 我该如何处理?

Just declare UIImage globally in your class, and inside your function, where you are setting imageHolder, assign that downloaded image to global image, and use it where ever you want. 只需在类中和函数内部全局声明UIImage,即可在其中设置imageHolder,将下载的图像分配给全局图像,然后在任何需要的地方使用它。

UIImage image;

func retreiveImagesFromFireBase(downloadUrl:String,imageHolder:UIImageView){
            if downloadUrl != ""{
                let storageRef = Storage.storage().reference(forURL: downloadUrl)
                // Download the data, assuming a max size of 1MB (you can change this as necessary)
                storageRef.getData(maxSize: 5*1024*1024) { (data, error) in
                    if error == nil{
                        if let pic = UIImage(data: data!){
                            imageHolder.image = pic
                            image = pic // use it on other views 
                        }
                    }else{
                        print(error)
                    }
                }
            }
        }

如果只有一两个图像,则只需将其存储在userdefault ,然后就可以在任何viewController中进行访问,将image作为datauserdefault只要您想使用,只需将数据转换为图像并使用它,请参见以下代码将数据转换为图片

let image = UIImage(data: imageData)

You can do 你可以做

class Service { 
   static let shared = Service()  
   var image1:UIImage?
   var image2:UIImage?
   let imageLink = "//////" // or with SDWebImage
}

if let pic = UIImage(data: data!){
    Service.shared.image = pic
}

Or use SDWebImage and share the link , you can aslo make a global var like 或者使用SDWebImage并共享链接,您还可以像这样创建全局变量

var image:UIImage? 

but it's not recommended as it has no grouping to let the developer know it's source local/instance/global so it's confusing unlike singleton 但不建议使用此方法,因为它没有分组以让开发人员知道其来源本地/实例/全局,因此与单例不同,这令人困惑

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM