Is there a way to download couple of files (images) using Firebase Storage SDK and live cache those files, so after an image is downloaded the cache is updated?
Can I also observe in another view controller for this cache being updated?
I don't need a whole answer, just maybe a hint where to learn it. I've search through firebase documentation, found some info but I have absolutely no idea how to use it.
Take a look at NSURLCache. Basically what you'll do is, every time you upload a file to Firebase Storage, you can get a download URL and download it, then storeCachedResponse:forRequest: in the URL cache. Since this cache is shared, you can even grab it across activities.
Similarly, on download, you'll want to check for the cached request via cachedResponseForRequest: and if it doesn't exist, perform the download (at which point you cache the request for later).
Long term, we're hoping to enable this behavior for you out of the box, but for now, you can use NSURLCache to make it happen :)
I still haven't found a way to do this from within the Firebase Storage SDK. Here is some code I got off bhlvoong tutorials to cache images using NSCache.
import UIKit
let imageCache = NSCache<AnyObject, AnyObject>()
extension UIImageView {
func loadImageUsingCacheWithUrlString(urlString: String) {
self.image = nil
//check cache for image first
if let cachedImage = imageCache.object(forKey: urlString as NSString) as? UIImage {
self.image = cachedImage
return
}
//otherwise fire off a new download
let url = NSURL(string: urlString)
URLSession.shared.dataTask(with: url as! URL, completionHandler: { (data, response, error) in
//download hit an error so lets return out
if error != nil {
print(error)
return
}
DispatchQueue.main.async {
if let downloadedImage = UIImage(data: data!) {
imageCache.setObject(downloadedImage, forKey: urlString as NSString)
self.image = downloadedImage
}
}
}).resume()
}
}
Related
I'm currently developing an iOS application where I've a lot of images. I use NSCache() for storing the images.
So, every time I load the application the images is being downloaded, saved in cache and stays in the cache all the way till I terminate the application.
I'm looking for a solution where the images will be saved even if you terminate the application, just download if the image does NOT exists in the current NSCache().
This one is used in the beginning of the extension:
let imageCache = NSCache<AnyObject, AnyObject>()
And then I've an extension with a function like this:
extension UIImageView {
func downloadImages(from urlString: NSString){
//Check for cached images and return out if found
if let cachedImage = imageCache.object(forKey: urlString) as? UIImage{
print("cache?", imageCache)
self.image = cachedImage
return
}
//Retrieve the images from Firebase Storage
let url = URL(string: urlString as String)
//Create an URL session
URLSession.shared.dataTask(with: url!) { (data, response, err) in
if let err = err{
print(err.localizedDescription)
}
//Continue on background thread
DispatchQueue.main.async {
//Check if image exists
if let downloadedImage = UIImage(data: data!){
//Add image to cache
imageCache.setObject(downloadedImage, forKey: urlString)
//Set the image to downloaded image.
self.image = downloadedImage
}
}
}.resume()
}
}
The image cache works until I terminate the application. Is there any way I can save the NSCache() even if I terminate the app?
This question already has answers here:
Loading/Downloading image from URL on Swift
(39 answers)
Closed 5 years ago.
EDIT 3: Please also read my comment in the "answered" tagged answer. I think I won't use my synchronous method but change to the suggested asynchronous methods that were also given!
Ok I am struggling with some basic concepts of showing images from an URL from the internet on my app.
I use this code to show my image on an UIIamgeView in my ViewController:
func showImage() {
let myUrlImage = URL(string: linkToTheImage)
let image = try? Data(contentsOf: myUrlImage!)
imageView1.image = UIImage(data: image!)
}
Now basically I have the following question:
Is the whole image downloaded in this process?
Or works the UIImageView like a "browser" in this case and doesn't download the whole picture but only "positions" the image from the URL into my UIImageView?
EDIT:
The reason I asked is, I am basically doing a quiz app and all I need in the view is an image from a URL for each question - so it's no difference if I do it asynchronous or synchronous because the user has to wait for the image anyways. I am more interested in how do I get the fastest result:
So I wanted to know if my code really downloads the picture as a whole from the URL or just "Positions" it into the UIImageView?
If in my code the picture is downloaded in its full resolution anyways, then you are right, I could download 10 pictures asynchronously when the player starts the quiz, so he hopefully doesn't have to wait after each answer as long as he would wait when I start downloading synchronously after each answer.
Edit 2:
Because my Question was tagged as similar to another some more explanation:
I already read about synchronous and asynchronous downloads, and I am aware of the downsides of synchronous loading.
I am more interested in a really basic question, and I get the feeling I had one basic thing really wrong:
My initial thought was that if I open a link in my browser, for example this one,
https://cloud.netlifyusercontent.com/assets/344dbf88-fdf9-42bb-adb4-46f01eedd629/68dd54ca-60cf-4ef7-898b-26d7cbe48ec7/10-dithering-opt.jpg
the browser doesn't download the whole picture. But I guess this isn't the case? The whole picture is downloaded?
Never use Data(contentsOf:) to display data from a remote URL. That initializer of Data is synchronous and is only meant to load local URLs into your app, not remote ones. Use URLSession.dataTask to download image data, just as you would with any other network request.
You can use below code to download an image from a remote URL asynchronously.
extension UIImage {
static func downloadFromRemoteURL(_ url: URL, completion: #escaping (UIImage?,Error?)->()) {
URLSession.shared.dataTask(with: url) { data, response, error in
guard let data = data, error == nil, let image = UIImage(data: data) else {
DispatchQueue.main.async{
completion(nil,error)
}
return
}
DispatchQueue.main.async() {
completion(image,nil)
}
}.resume()
}
}
Display the image in a UIImageView:
UIImage.downloadFromRemoteURL(yourURL, completion: { image, error in
guard let image = image, error == nil else { print(error);return }
imageView1.image = image
})
You can do it this way. But in most cases it is better to download the image first by yourself and handle the displaying then (this is more or less what the OS is doing in the background). Also this method is more fail proof and allows you to respond to errors.
extension FileManager {
open func secureCopyItem(at srcURL: URL, to dstURL: URL) -> Bool {
do {
if FileManager.default.fileExists(atPath: dstURL.path) {
try FileManager.default.removeItem(at: dstURL)
}
try FileManager.default.copyItem(at: srcURL, to: dstURL)
} catch (let error) {
print("Cannot copy item at \(srcURL) to \(dstURL): \(error)")
return false
}
return true
}
}
func download() {
let storagePathUrl = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as NSString).appendingPathComponent("image.jpg")
let imageUrl = "https://www.server.com/image.jpg"
let urlRequest = URLRequest(url: URL(string: imageUrl)!)
let task = URLSession.shared.downloadTask(with: urlRequest) { tempLocalUrl, response, error in
guard error == nil, let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode == 200 else {
print("error")
return
}
guard FileManager.default.secureCopyItem(at: tempLocalUrl!, to: storagePathUrl) else {
print("error")
return
}
}
task.resume()
}
I want to show profile image in my tableview beside the name of the user.
I have uploaded my image to Firebase storage and stored the images URL in Firebase database. Everything works perfectly.
Profile image uploads in firebase Storage and the URL saves in a database but there is something wrong with downloading code because profile image does not appear when I run my app. I don't get any error from Xcode.
if let profileImageUrl = user.profileImageUrl{
let url = URL(string: profileImageUrl)
URLSession.shared.dataTask(with: url!,
completionHandler:
{(data, response, error) in
//download hit error
if error != nil {
print(error)
return
}
DispatchQueue.main.async() {
cell?.imageView?.image = UIImage(data: data!)
}
}).resume()
}
return cell!
}
You can do this by using SDWebImageView
import SDWebImage
cell?.imageView?.sd_setImage(with: URL(string: user.profileImageUrl), placeholderImage: UIImage(named: "placeholder.png"))
A piece of advice. Use Glide for downloading the pictures. It is as easy as :
Glide.with(ExampleActivity).load(url).into(imageView);
I'm using UIImageView.image in order to change the visible image on my screen.
iv.image = images[index]
The array 'images' is currently filled with local image files. However, I wish to download images from my server and then append them to the array.
private var images = [img1, img2, img3]
I have been recommended using SDWebImage (particularly SDWebImageManager or SDWebImageDownloader) to do this, however, when exploring the download and caching tutorials, all of them downloaded to a UIImageView. I cannot pass in a UIImageView into the .image extension. I couldn't find any tutorials or examples to help me achieve this. I am fairly new to swift so I do not have a vast amount of experience or understanding.
You can donwload image Async without any library as well.
Following will create a extension for imageView and it will async down image from the server just pass the respective url as parameter it will return an image.
extension UIImageView {
public func imageFromServerURL(urlString: String) {
URLSession.shared.dataTask(with: NSURL(string: urlString)! as URL, completionHandler: { (data, response, error) -> Void in
if error != nil {
print(error!)
return
}
DispatchQueue.main.async(execute: { () -> Void in
if let imageData = data {
let image = UIImage(data: imageData)
self.image = image
}
})
}).resume()
}
}
// And you can call like this where ever required
cell.cellImageView.imageFromServerURL(urlString: banner.imageURL)
I've seen that you can download an image in IOS through a URL. However, this requires that the URL be public. I'd much rather do it in such a way where my application makes a request to the server and if the necessary requirements are met, the server responds with an image. I do not want my images to be visible from the web.
The easiest option is to put the password in the URL:
let url = NSURL(string: "http://exapmle.com/2XwLZAgAO2VP9JqXg1s73zmB/foo.png")
let dataOptional: NSData? = NSData(contentsOfURL: url)
if let data = dataOptional {
let image = UIImage(data: data)
} else {
println("Error loading \(url)")
}