I'm using this code in CellForRowAt for showing image. Scrolling is smoothly but network debug says me that it still download image every time that i scroll the table.
How can I work for download all the images once?
if let url = URL( string: rest1.image) {
DispatchQueue.global().async {
if let data = try? Data(contentsOf: url) {
DispatchQueue.main.async {
cell.RestaurantImage.image = UIImage(data: data)
}
}
}
}
You need to use NSCache for saving and retrieving images. Once the images are fetched from network store it inside the Cache and from the next time load the images from the Cache. Create an instance of NSCache with keys NSString and value NSData because NSCache only allows class types. Here's an example:
Create an image cache outside the cellForItem method, or you can create it as Global, like this:
let imageCache = NSCache<NSString, NSData>()
And then in cellForItem method:
if let url = URL(string: rest1.image) {
if let data = imageCache.object(forKey: rest1.image as NSString) {
cell.RestaurantImage.image = UIImage(data: data as Data)
} else {
DispatchQueue.global().async {
if let data = try? Data(contentsOf: url) {
imageCache.setObject(data as NSData, forKey: rest1.image as NSString)
DispatchQueue.main.async {
cell.RestaurantImage.image = UIImage(data: data)
}
}
}
}
}
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?
I am needing to load images from a URL and store them locally so they dont have to be reloaded over and over. I have this extension I am working on:
extension UIImage {
func load(image imageName: String) -> UIImage {
// declare image location
let imagePath: String = "\(NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0])/\(imageName).png"
let imageUrl: URL = URL(fileURLWithPath: imagePath)
// check if the image is stored already
if FileManager.default.fileExists(atPath: imagePath),
let imageData: Data = try? Data(contentsOf: imageUrl),
let image: UIImage = UIImage(data: imageData, scale: UIScreen.main.scale) {
return image
}
// image has not been created yet: create it, store it, return it
do {
let url = URL(string: eventInfo!.bannerImage)!
let data = try Data(contentsOf: url)
let loadedImage: UIImage = UIImage(data: data)!
}
catch{
print(error)
}
let newImage: UIImage =
try? UIImagePNGRepresentation(loadedImage)?.write(to: imageUrl)
return newImage
}
}
I am running into a problem where the "loadedImage" in the UIImagePNGRepresentation comes back with an error "Use of unresolved identifier loadedImage". My goal is to store a PNG representation of the image locally. Any suggestions on this error would be appreciated.
It's a simple matter of variable scope. You declare loadedImage inside the do block but then you attempt to use outside (after) that block.
Move the use of loadedImage to be inside the do block.
You also need better error handling and better handling of optional results. And your load method should probably return an optional image incase all attempts to get the image fail. Or return some default image.
Here's your method rewritten using better APIs and better handling of optionals and errors.
extension UIImage {
func load(image imageName: String) -> UIImage? {
// declare image location
guard let imageUrl = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first?.appendingPathComponent(imageName).appendingPathExtension("png") else {
return nil // or create and return some default image
}
// check if the image is stored already
if FileManager.default.fileExists(atPath: imageUrl.path) {
if let imageData = try? Data(contentsOf: imageUrl), let image = UIImage(data: imageData) {
return image
}
}
// image has not been created yet: create it, store it, return it
do {
let url = URL(string: eventInfo!.bannerImage)! // two force-unwraps - consider better handling of this
if let data = try Data(contentsOf: url), let loadedImage = UIImage(data: data) {
try data.write(to: imageUrl)
return loadedImage
}
}
catch{
print(error)
}
return nil // or create and return some default image
}
}
If eventInfo!.bannerImage is a remote URL, then you must never run this code on the main queue.
I have an image in tableview that is downloaded from a Json, everything works perfect but when scrolling before seeing the corresponding image it loads another for a few seconds (these images are those that are already visible in the table).
The structure of my data is:
struct Data: Decodable {
let name: String
let img: String
let phone: String
let linktaller: String
let web: String
}
The code of my cell where the image is loaded is:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as? AseguradorasTableViewCell else { return UITableViewCell() }
cell.titleLbl.text = company[indexPath.row].name
.
.
.
// load image
if let imageURL = URL(string: company[indexPath.row].img) {
DispatchQueue.global().async {
let data = try? Data(contentsOf: imageURL)
if let data = data {
let image = UIImage(data: data)
DispatchQueue.main.async {
cell.myImage.image = image
}
}
}
}
return cell
}
The function to load the data is:
func downloadJSON() {
let url = URL(string: "http://myserver.com/data.json")
URLSession.shared.dataTask(with: url!) { (data, response, error) in
if error == nil {
do {
self.company = try JSONDecoder().decode([Data].self, from: data!)
print(self.company)
DispatchQueue.main.async {
self.tableView.reloadData()
self.refreshControl.endRefreshing()
}
} catch let jsonError{
print("error + \(jsonError)")
}
}
}.resume()
}
See image for more detail:
Any suggestions are welcome to fix this problem.
In UITableView dequeueReusableCell- Each UITableViewCell will be reused several times with different data(image).
In your case, every cellForRowAt is called, the image will be load from server so it will have delay.
Solution: You must to cache image with url in local app when the image load finish.
(1)- Use SDWebImage - with cache support
(2)- You can save image in a array -> in cellForRowAt load from this array if existed and load from server if does not exist
(image from internet)
Add the following class for cache image support:
class ImageLoader {
var cache = NSCache<AnyObject, AnyObject>()
class var sharedInstance : ImageLoader {
struct Static {
static let instance : ImageLoader = ImageLoader()
}
return Static.instance
}
func imageForUrl(urlString: String, completionHandler:#escaping (_ image: UIImage?, _ url: String) -> ()) {
let data: NSData? = self.cache.object(forKey: urlString as AnyObject) as? NSData
if let imageData = data {
let image = UIImage(data: imageData as Data)
DispatchQueue.main.async {
completionHandler(image, urlString)
}
return
}
let downloadTask: URLSessionDataTask = URLSession.shared.dataTask(with: URL.init(string: urlString)!) { (data, response, error) in
if error == nil {
if data != nil {
let image = UIImage.init(data: data!)
self.cache.setObject(data! as AnyObject, forKey: urlString as AnyObject)
DispatchQueue.main.async {
completionHandler(image, urlString)
}
}
} else {
completionHandler(nil, urlString)
}
}
downloadTask.resume()
}
}
In the cell, load the image as follows:
// Load image
let fimage = company[indexPath.row].img
ImageLoader.sharedInstance.imageForUrl(urlString: fimage, completionHandler: { (image, url) in
if image != nil {
cell.myImage.image = image
}
})
With that, the download of the images should work correctly
Because of when ever the cell is showing, you download the image from internet by
let data = try? Data(contentsOf: imageURL)
You should
Check if image in imageURL has cached or not
If cached, load image from local
If not cache, download it from internet, then cache it.
Or just simple using SDWebImage or anything else, it will auto check the step 1 to 3 for you :D
For example by using SDWebImage
import SDWebImage
imageView.sd_setImage(with: URL(string: "your_image_url"))
This is a classic cell reuse problem. You should install a placeholder image, or nil, into the image view of each cell in your tableView(cellForRowAt:) method before you begin the download. That will clear out the previous image that was installed into the cell, and then the async download can run in the background and install the image once it's done loading.
To resolve similar issues, I changed my code to coordinate the downloading of images with the creation of tableView cells, storing the images in a local array.
I create a dictionary array to hold the downloaded images, using the url string as the key:
imagesArray = [String:UIImage]()
Then, at the point in the code where each image completes downloading, I add the image to the array and insert one new row into the tableView:
imagesArray.updateValue(UIImage(data: data!)!, forKey: imageURL as! String)
tableView.beginUpdates()
tableView.insertRows(at:[IndexPath(row: imagesArray.count-1, section: 0)], with: .automatic)
tableView.endUpdates()
tableView.reloadData()
I also maintain a separate array of information elements for each image, including the image url string as one element. This allows me to present the correct items in the tableView cell:
cell.itemNameLabel.text = itemRecords[indexPath.row].itemName
cell.itemImage.image = imagesArray[itemRecords[indexPath.row].imageURL]
While the images are downloading, I present a progress indicator spinner.
Once the images are all downloaded and are loaded into the imagesArray, there is NO delay in presenting as the user scrolls up and down to view the listed cells, and reused cells are loaded with the correct images.
I have an array filled with parsed json data including image url's. But when i try to see that images inside uiimageview, it doesn't the show. What should i do
I printed the url. This is my url inside array.
This is my array
var feedResult = [Result]()
It shows the name inside collectionview but i couldn't see the images. I used named like everybody does. But what is missing?
let info = feedResult[indexPath.row]
cell.appLabel.text = info.artistName
cell.customCollectionImage.image = UIImage(named: info.artWorkUrl)
You have to download the image Data using the url you got, only then you will use the downloaded data, like so:
imageView.image = UIImage(data: downloadedData)
Here is a quick subclass of UIImageView that does the downloading:
class URLImageView: UIImageView {
func download(url urlString: String) {
guard let url = URL(string: urlString) else { return }
let task = URLSession.shared.dataTask(with: url) { (downloadedData, _, error) in
guard error == nil && downloadedData != nil else { return }
DispatchQueue.main.async{
self.image = UIImage(data: downloadedData!)
}
}
task.resume()
}
}
Update-1 Use the download function using UIImageView extension, without subclassing, like so:
extension UIImageView {
func download(url urlString: String) {
guard let url = URL(string: urlString) else { return }
let task = URLSession.shared.dataTask(with: url) { (downloadedData, _, error) in
guard error == nil && downloadedData != nil else { return }
DispatchQueue.main.async{
self.image = UIImage(data: downloadedData!)
}
}
task.resume()
}
}
Usage:
cell.customCollectionImage.download(url: info.artWorkUrl)
By using UIImage(named: info.artWorkUrl) you are not accessing the image in your array but the images in your Assets.xcassets (assets that you add manually in your project).
You need to download the image from the artWorkUrl and then directly use the downloaded image like this:
cell.customCollectionImage.image = UIImage(data: yourImageData)
Where yourImageData is what you have downloaded from the server with the artWorkUrl.
I'm having problems cacheing for images from JSON correctly with this UIImageView extension. The images load correctly when I first open the app and scroll down the page. However when I scroll back up, they don't reload and are completely gone. Can anyone see anything wrong with the code?
let imageCache = NSCache<AnyObject, AnyObject>()
extension UIImageView {
func loadImageUsingUrlString(urlString: String) {
let url = NSURL(string: urlString)
if let imageFromCache = imageCache.object(forKey: urlString as AnyObject) as? UIImage {
self.image = imageFromCache
return
}
URLSession.shared.dataTask(with: url! as URL) { (data, response, error) in
if error != nil {
print(error ?? "URLSession error")
return
}
DispatchQueue.main.async {
let imageToCache = UIImage(data: data!)
imageCache.setObject(imageToCache!, forKey: urlString as AnyObject)
self.image = imageToCache
}
}.resume()
}
}
Here is the snippet from the cell.swift file
let imageCache = NSCache<AnyObject, AnyObject>()
func setupThumbnailImage() {
if let thumbnailImageUrl = television?.poster_url {
let urlPrefix = "https://www.what-song.com"
let urlSuffix = thumbnailImageUrl
let urlCombined = urlPrefix + urlSuffix
thumbnailImageView.loadImageUsingUrlString(urlString: urlCombined)
}
}
I suggest using kingFisher, it is very easy to use and it manages all starting from cache threads etc.
let imageResource = ImageResource(downloadURL:URL(string: imagePath )!,cacheKey: imagePath )
viewImage.kf.indicatorType = .activity
viewImage.kf.setImage(with: resource)
where imagePath is the url of your image and viewImage is your imageView
Most probably you would be calling it in wrong way.
Remember that in tableView you reuse the cells.
By the time response comes back for the URLSessionTask you would have already scrolled up/down. In that case self.image would be assigned to the currently visible cell.
Please add your cellForRow code in question.