简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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