GIF images to UIImageView using AlamofireImage in Swift - ios

I am using AlamofireImage library to download/cache web images and show it in UIImageView inside tableViewCells.
imageView.af_setImage(withURL: url, placeholderImage: nil, filter: nil, imageTransition: .crossDissolve(0.3), runImageTransitionIfCached: true, completion: { (response) in
//...... other code .....
})
It works perfect for .png/.jpg or other still images but I am not able to show GIF images using this.
I tried using external library to convert imageData to gif images and it works perfect however Alamofire is not caching the gif data and next time the image loads as still image.
Check the code below:
imageView.af_setImage(withURL: url, placeholderImage: nil, filter: nil, imageTransition: .crossDissolve(0.3), runImageTransitionIfCached: true, completion: { (response) in
if imageUrl.hasSuffix("gif") {
if let data = response.data{
self.imageView.image = UIImage.gifImageWithData(data)
}
}
})
The above code shows the GIF for first time but next time only still image appears.
Any idea how the following can be achieved using AlamofireImage:
Download the GIF imageData for the first time, cache it and show GIF to imageView
Next time get the imageData from cache and show GIF again

I have not found a direct way to play GIF with AlamofireImage but we can do using SwiftyGif. I'm using AlamofireImage throughout the app but for display GIF and load from the server, I'm using SwiftyGif. Using SwiftyGif you can play, load from the server as well as locally. I think it will be reliable solution instead of use SDWebImage.
SwiftyGif
// You can also set it with an URL pointing to your gif
let url = URL(string: "...")
let loader = UIActivityIndicatorView(style: .white)
cell.gifImageView.setGifFromURL(url, customLoader: loader)

Download GIF file , next time get the file and show
Alamofire.download(gifUrl, to: destination).responseJSON(completionHandler: {
response in
if let filePath = response.destinationURL?.path{
if let gifImage = UIImage.init(contentsOfFile: filePath){
self.imageVIew.image = gifImage
}
}
})

Related

How to put animating placeholder image while downloading url image in swift 4 or Swift 5

I did try with Cocapods "Kingfisher" but cannot figure out how to set an animating placeholder image while the image is being downloaded.
here is the Below code I tried with kingfisher Pod
func configureCell(category:Category){
if let url = URL(string: category.imgUrl){
let placeholder = UIImage(named: "placeholder")
let options : KingfisherOptionsInfo = [KingfisherOptionsInfoItem.transition(.fade(0.1))]
categoryImg.kf.indicatorType = .activity
categoryImg.kf.setImage(with: url, placeholder: placeholder, options: options)
}
}
This is actually not an image but a UIView. The best option would be to use SkeletonView.
SkeletonView has been conceived to address this need, an elegant way to show users that something is happening and also prepare them to which contents he is waiting.
This animation is called Shimmer effect . You can use this link for your help
facebook/Shimmer.

SDWebImage doesn't show locally stored image on a real device but it shows up in simulator

I'm using SDWebImages library to get image for thumbnails. It is working seemlesly.
However when I navigate from video to a controller where I play video, I need to show thumbnail once again. I need an image path to pass to the player.
The problem is if I pass the same URL the player will download the image once again. In order to avoid this behaviour i'm trying to get the image from disc which is already stored there by sdwebimages library.
/// get thumbnail from cache
var thumbnail: String?
if (video?.hasThumbnail) {
let urlString = "https://test.com/image/001.png"
if let path = SDImageCache.shared.cachePath(forKey: urlString) {
thumbnail = path
} else {
thumbnail = urlString
}
}
This is working on a simulator, but NOT on the real device.
Please read more about how to use
imageView.sd_setImage(with: URL(string: "http://www.example.com/path/to/image.jpg"), placeholderImage: UIImage(named: "placeholder.png"))

Error Domain=NSCocoaErrorDomain Code=256 "The file “images” couldn’t be opened." UserInfo={NSURL=http://

func loadCell(personObj:Person){
self.lblTitle.text = personObj.title
self.lblDesc.text = personObj.desc
print("ImgUrlInCell:", personObj.imageUrl)
do {
self.imgPicture.image = try UIImage(data:NSData(contentsOf:NSURL(string: personObj.imageUrl) as! URL) as Data)
} catch {
print("Error:",error)
}
}
Firstly, I've parsed data from API and put it in object and then insert it into database. At the time of displaying data I fetched them from database and list them in Tableview.
If there is an internet connection everything is working fine
If there is no internet connection image url doesn't work, It prints error 6 times. (I have 10 images in database or API)
Also, There are 10 image url displaying in console in ImgUrlInCell:
Please someone help me with this issue. What have I wronged.
You are using TableView and in TableView as per screen size and Cell size, it will show max cell in your screens so it may be possible that in your case its loading 6 cells data and all 6 cells have load image method so its throwing error 6 times.
To load Images lazily there are many famous libraries which will manage single time download and cache that image.
SDWebImage is one of the best libraries fits for your problem.
Link : SDWebImage
And follow below code to get Image from the server.
Swift:
import SDWebImage
imageView.sd_setImage(with: URL(string: "http://www.example.com/path/to/image.jpg"), placeholderImage: UIImage(named: "placeholder.png"))
Put an above line of code in your loadCell method with your imageURL.
Please check Internet connection by using Apple Reachability classes and load your image if the Internet connection is there.
Edit:
For Locally storing image you can use below function of SDWebImage Downloader and cache your image before showing it to the user.
SDWebImageManager.shared().imageDownloader?.downloadImage(with: NSURL(string: strURL) as URL!, options: SDWebImageDownloaderOptions.continueInBackground, progress: {
(receivedSize, ExpectedSize, imageURL) in
print("receive:",receivedSize,"Expected:",ExpectedSize,"Image URL:",imageURL ?? "No URL")
}, completed: {
(image, data, error, finished) in
print("Image Data:",data ?? "No Data")
// Do your stuff to store downloaded image
})
Link : Reachability Sample
Hope this will helps.

how can I get the data of cached images SDWebImage

I'm using SDWebImage library to cache web images in my UICollectionView:
cell.packItemImage.sd_setImage(with: URL(string: smileImageUrl[indexPath.row]))
but I want to save the cached images locally in a file instead of downloading them again
FileManager.default.createFile(atPath: newPath, contents: Data(contentsOf: URL(string: snapchildvalue[Constants.smiles.smileImageUrl] as! String)!), attributes: nil)
is there a way to get the data of cached images
SDWebImage caches downloaded images automatically by default. You can use SDImageCache to retrieve images from the cache. There is a memory cache for the current app session, which will be quicker, and there is the disk cache. Example usage:
if let image = SDImageCache.shared().imageFromDiskCache(forKey: imageURL.absoluteString) {
//use image
}
if let image = SDImageCache.shared().imageFromMemoryCache(forKey: imageURL.absoluteString) {
//use image
}
Also make sure you import SDWebImage in your file. (If you're using Swift/Carthage, it will be import WebImage
SDWebimage chaches image once it is downloaded from a url. Basically it saves image against a url and next time if an image is available for a URL. It will simply get that image from cache. So the below method will be called instantly if the image is already downloaded to device.
imgView.sd_setImage(with: URL(string:url), completed: { (image, error, type, url) in
imgView.image = image
//Do any thing with image here. This will be called instantly after image is downloaded to cache. E.g. if you want to save image (Which is not required for a simple image fetch,
//you can use FileManager.default.createFile(atPath: newPath, contents: UIImagePNGRepresentation(image), attributes: nil)
})
Still if you want to save that image somewhere else or modify it or whatever, you can do it in the completion block above.
SDWebImage already have this kind of caching file locally
Create a SDImageCache with namespace of your choice
Try get the image with imageCache.queryDiskCache
If the image exist, set it to your imageview, if not, use sd_setImage to get the image then save it to the local cache with SDImageCache.shared().store
The key usually to be the image url string
Something like this, might not be correct syntax:
imageCache.queryDiskCache(forKey: urlForImageString().absoluteString, done: {(_ image: UIImage, _ cacheType: SDImageCacheType) -> Void in
if image {
self.imageView.image = image
}
else {
self.imageView.sd_setImage(withURL: urlForImageString(), placeholderImage: UIImage(named: "placeholder")!, completed: {(_ image: UIImage, _ error: Error, _ cacheType: SDImageCacheType, _ imageURL: URL) -> Void in
SDImageCache.shared().store(image, forKey: urlForImageString().absoluteString)
})
}
})

Not able to cache image using method downloadImageWithURL in SDWebImageManager

I am using the code given below to download the image using downloadImageWithURL method and to assign the image to a UIImageView and cache the same image using SDImageCache().storeImage, but i am not able to cache the image. Am i missing anything?
Here is my code:
SDWebImageManager.sharedManager().downloadImageWithURL(profileImageURL,
options: SDWebImageOptions.HighPriority,
progress: { (min:Int, max:Int) -> Void in
})
{ (image:UIImage!, error:NSError!, cacheType:SDImageCacheType, finished:Bool, url:NSURL!) -> Void in
if (image != nil)
{
self.userProfilePic.image = image
SDImageCache.sharedImageCache().storeImage(image, forKey: "userProfilePicImage", toDisk: true)
}
}
Looking at the github page, there's a category specifically for UIImageView. Look for Using UIImageView+WebCache category with UITableView on https://github.com/rs/SDWebImage as they give an example.
This both sets the image, caches it and uses a placeholder image whilst the image is fetching.
SDWebImage has a Method sd_setImageWithURL which will download the image and save it to Cache also, you don't need to manually save that image on Cache
Try below code it will solve your problem
self.userProfilePic.sd_setImageWithURL(NSURL(string: "http://www.domain.com/path/to/image.jpg")!, placeholderImage: UIImage(named: "placeholder.png")!)

Resources