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)
}
}
}
}
If you have only one or two images then simply store in userdefault and then you can access in any viewController, Store image as data in userdefault
whenever you want to use just convert data to image and use it, See the following code to convert data to image
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