AlamofireImage: Can't get image in completion block from af_setImageWithURL - ios

all
I am learning Swift and I am trying to set an image on a UIImageView using AlamofireImage. I am using the following code:
self.listImageView.af_setImageWithURL(
NSURL(string: list!.image!)!,
placeholderImage: nil,
filter: nil,
imageTransition: .CrossDissolve(0.5),
completion:{ image in
print(image)
}
)
and the result in the console is the following:
SUCCESS: <UIImage: 0x7fb0c3ec3d30>, {512, 286}
My objective is to do something with the image once is downloaded, but the problem is that I don't understand the signature for the completion callback and I don't know how to access to the image in the completion block. According to the documentation, is Result<UIImage, NSError>.
I guess is something really simple, but I am not realizing it.
Thanks

The image variable passed into the completion block is actually Alamofire.Response type, not the underlying UIImage instance itself that was fetched.
You need to update your completion block like below in order to get the actual image from the response:
self.listImageView.af_setImage(
withURL: URL(string: list!.image!)!,
placeholderImage: nil,
filter: nil,
imageTransition: .crossDissolve(0.5),
completion: { response in
print(response.value) # UIImage
print(response.error) # NSError
}
)
You might first want to check response.result.isSuccess (or his brother response.result.isFailure) to make sure whether the image has been successfully retrieved or not.

Related

Post a tweet with a photo using the Swifter Framework / Library

I'm using Swifter Library to try to post a tweet with a photo but every time I try, i get an error "The operation couldn’t be completed. (SwifteriOS.SwifterError error 1.)"
My code looks like
var tweetMedia: [String: Any]?
//I then set tweetMedia to a UIImageView from the UIImagePickerControllerOriginalImage
let picForTwitterApi = tweetMedia![UIImagePickerControllerOriginalImage] as! UIImage
let image = UIImagePNGRepresentation(picForTwitterApi) as Data?
self.swifter?.postTweet(status: tweetText, media: image!, inReplyToStatusID: nil, coordinate: nil, placeID: nil, displayCoordinates: nil, trimUser: false,
tweetMode: TweetMode.default, success: { json in self.alert(title: "Tweet PHOTO sent", message: "👍🏾")
}, failure: failureHandler)
But it does not work, i even tried
self.swifter?.postMedia(image!, additionalOwners: nil, success: { json in
print(json)
instead, still no success.
When I post a regular vanilla tweet like
self.swifter?.postTweet(status: tweetText, inReplyToStatusID: nil, trimUser: false, tweetMode: TweetMode.default, success: { json in
print(json).....
Everything works perfectly fine, I only have problems when I try to post a photo. Please help. Thanks in advance
I found the solution. The picture must be small. Even smaller than 5mb the documentation suggest. I used an image that was only 100KB and it worked. If I want to post a larger image/video (even just one picture) you have to use the chunked media post ability

GIF images to UIImageView using AlamofireImage in Swift

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

SDWebImage giving nil with URL

I've a string in which I've comma separated links of images. Here is how I'm splitting it into an array: let imagesLinks = imageLins.components(separatedBy: ","). Then I've used for loop to get one link, download the image and storing it in a UIImage array in this way:
for imag in imagesLinks
{
let img = UIImageView()
print("\(baseReportImageURL)\(imag)")
img.sd_setImage(with: URL(string: "\(baseReportImageURL)\(imag)"), placeholderImage: nil)
imagesArray.append(img.image!)
}
The print statement is giving me the correct URL which when I open on browser downloads the image. The problem is on the line where I'm appending the array i.e. imagesArray.append(img.image!). I get:
fatal error: unexpectedly found nil while unwrapping an Optional value
and
fatal error: unexpectedly found nil while unwrapping an Optional value
So what would be the correct solution for this?
UPDATE
My question is different because I'm using SDWebImage and when I use completion block there is a strange behaviour of the app:
img.sd_setImage(with: imgURL, placeholderImage: nil,options: SDWebImageOptions(rawValue: 0), completed: { (image, error, cacheType, imageURL) in
activityIndicator.stopAnimating()
imagesArray.append(image!)
self.photoCollection.reloadData()
})
So it keeps on rotating the activity indicator and when I go back and push the view again it load the images instantly. So I think that the completion block is not called when the image is downloaded but why is that?
I think that is not the proper way to get downloaded images (set images to an UIImageView and then get the images from there).
You should use the image downloader, provided by SDWebImage:
SDWebImageManager.shared().imageDownloader?.downloadImage(with: <YOUR_URL>, options: [], progress: { (received, expected, nil) in
print(received,expected)
}, completed: { (image, data, error, true) in
yourArray.append(image)
})
If you have indexes, you can update the current row in the tableview every time when an image downloaded, or just reload() the whole, but I recommend the first.
It is because
imagesArray.append(img.image!)
Image take some times for downloading. When you do imagesArray.append(img.image!) at that time it is possible that your image is not set to your imageview and that means you are trying to add nil in your imageArray!
Second thing why are you storing image in an array ? You have array of urls and you are using SDWebImage then every time when you want to display image use SDWebImage. No need to store in array!
And if you want images in array anyhow than use NSUrlSession asynchronous requests with completion handlers and from completion handler add image to your array!
Append the image into the images array in the sd_setImage completion block.
The image is not yet downloaded when you are trying to add it into the array, and check if the image is not equal nil before adding it.
Use this Block For Image Download After download Perform Operation(append Image)
cell.appIcon.sd_setImage(with: url!, placeholderImage: UIImage(named: "App-Default"),options: SDWebImageOptions(rawValue: 0), completed: { (image, error, cacheType, imageURL) in
// Perform operation.
//append Image Here
})

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