Alamofire: Image download request issue - ios

I'm new in the Swift, I am using Alamofire framework in my project, I am facing the following issue while giving the request for download image, I am using following code:
let imageURL = Constant.BaseAPI_URL + "/" + driver.driverProfile
Alamofire.request(.GET, imageURL).response() {
(_, _, data, _) in
let image = UIImage(data: data! as! NSData)
deiverProfileImageView.image = image
}
Issue :
Click Here For Image Description

Try this:
let imageURL = Constant.BaseAPI_URL + "/" + driver.driverProfile
Alamofire.download(imageURL).responseData { response in
if let data = response.result.value {
let image = UIImage(data: data)
deiverProfileImageView.image = image
}
}

Try below code
let imageURL = Constant.BaseAPI_URL + "/" + driver.driverProfile
Alamofire.request(imageURL).responseData(completionHandler: { response in
if let imageData = response.data
{
deiverProfileImageView.image = imageData
}
})

Try this:
let imageUrl = "www.your_url.com"
Alamofire.download(imageUrl).responseData {
response in
if let data = response.result.value {
let image = UIImage(data: data)
ProfileImage.image = image
}
}
or
The easiest way according to me will be using SDWebImage
Add this to your pod file
pod 'SDWebImage', '~> 4.0'
Run pod install
Now import SDWebImage
import SDWebImage
Now for setting image from url
imageView.sd_setImage(with: URL(string: "http://www.domain/path/to/image.jpg"), placeholderImage: UIImage(named: "placeholder.png"))
It will show placeholder image but when image is downloaded it will show the image from url .Your app will never crash
This are the main feature of SDWebImage
Categories for UIImageView, UIButton, MKAnnotationView adding web image and cache management
An asynchronous image downloader
An asynchronous memory + disk image caching with automatic cache expiration handling
A background image decompression
A guarantee that the same URL won't be downloaded several times
A guarantee that bogus URLs won't be retried again and again
A guarantee that main thread will never be blocked
Performances!
Use GCD and ARC
To know more https://github.com/rs/SDWebImage

Related

Image View Does not display image after setting image to it downloaded from url

here it is what i am doing.
extension UIImageView {
func downloadedFrom(url: URL, contentMode mode: UIViewContentMode = .scaleAspectFit) {
contentMode = mode
URLSession.shared.dataTask(with: url) { data, response, error in
guard
let httpURLResponse = response as? HTTPURLResponse, httpURLResponse.statusCode == 200,
let mimeType = response?.mimeType, mimeType.hasPrefix("image"),
let data = data, error == nil,
let image = UIImage(data: data)
else { return }
DispatchQueue.main.async() {
self.image = image
}
}.resume()
}
func downloadedFrom(link: String, contentMode mode: UIViewContentMode = .scaleAspectFit) {
guard let url = URL(string: link) else { return }
downloadedFrom(url: url, contentMode: mode)
}
i checked it in image its show image in preview in debug state. but after self.image = image
nothing change on image view image is not displaying. anyone know where the problem is ? thanks
Most efficient way for downloading image: SDWebImage
You can use a Cocoa Pod file for SDWebImage Library.
init the pod file.
pod 'SDWebImage'
install Pod file.
Swift snippet:
import SDWebImage
imageView.sd_setImage(with: URL(string: #"user-url"), placeholderImage: UIImage(named: "placeholder"))
Objective-C Snippet:
#import <SDWebImage/UIImageView+WebCache.h>
...
[imageView sd_setImageWithURL:[NSURL URLWithString:#"user-url"]
placeholderImage:[UIImage imageNamed:#"placeholder"]];
Hope this will help to do efficient way to downloading images basically, whenever you are using UICollectionView or UITableView.
You can do it easier with Kingfisher library like below.
let url = URL(string: "url_of_your_image")
imageView.kf.setImage(with: url)
Try this below code
if data != nil { // check nil here
let image = UIImage(data: data)
DispatchQueue.main.async {
self.image = image
}
}
}.resume()
no need to check the image mime type, just a check of data and image is sufficient, since data will be nil for error and vice versa.
change as
URLSession.shared.dataTask(with: url) { data, response, error in
guard let data = data, let image = UIImage(data: data) else { return }
DispatchQueue.main.async {
self.image = image
}
}.resume()
And cross check with image with debugger.

Error always thrown loading UIImage from URL [duplicate]

This question already has answers here:
Transport security has blocked a cleartext HTTP
(29 answers)
Closed 6 years ago.
When I try to load an image from a URL I always get an error despite the fact that I know that there is a URL that contains a valid .jpg image.
mainImageView.image = try UIImage(data: Data(contentsOf: URL(fileURLWithPath: artworkURL)))
I also tried these solution but the line where I initialise the UIImage still throws an error.
Example of data in artworkURL:
http://is1.mzstatic.com/image/thumb/Music/v4/ef/97/95/ef979538-8321-151a-dceb-9b0a7f7c7641/source/100x100bb.jpg
Current solutions do not solve my problem. I also tried:
try UIImage(data: Data(contentsOf: URL(string: artworkURL)!))
and
try UIImage(data: Data(contentsOf: (URL : artworkURL)))
and (fuller code) now using a static url to debug
let artworkString = "http://is1.mzstatic.com/image/thumb/Music/v4/ef/97/95/ef979538-8321-151a-dceb-9b0a7f7c7641/source/100x100bb.jpg" // album.artworkURL[index.row]
let url = URL(string: artworkString)
do {
mainImageView.image = try UIImage(data: Data(contentsOf: url!))
} catch _ {
print("No album artwork!")
}
This last one outputs "No album artwork!"!
You can user this library:
https://github.com/onevcat/Kingfisher
Kingfisher is a lightweight, pure-Swift library for downloading and caching images from the web. This project is heavily inspired by the popular SDWebImage. It provides you a chance to use a pure-Swift alternative in your next app.
let imagePath = URL(string: "url_of_your_image")
imageView.kf_setImageWithURL(NSURL(string: imagePath)!, placeholderImage: UIImage(named: "placeholder"))
you can also add placeholder image.

Firebase - downloading few files

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

UIImage Bad instruction

Looking through the forums I have found that this issue is one that shows its head every now and then. And apparently doing so in a wide scope of different cases. None that I have managed to find seem to be similar to mine though.
I'm halfway through my program (lesson) in creating a usable twitter application. Testing it currently runs the program as it should, without any errors. But when I select an account the program crashes and an error message shows up at the image method which is supposed to load the avatar of the selected user. I assume that it is not able to retrieve a valid image or fetch data at all (because of the line ImageData = (NSDATA?) nil in the debug area), but I am by no means sure of anything, let alone how to or where to find a solution. If I am searching with the wrong keywords then please let me know. (I am searching for exc_bad_instruction and uiimage error) Thanks in advance.
I'll post the snippet of code where the issue presents itself below and what is shown in the debug area below that.
if let cachedImage = image {
cell.tweetUserAvatar.image = cachedImage
}
else {
cell.tweetUserAvatar.image = UIImage(named: "camera.png")
queue?.addOperationWithBlock() {
let imageURL = NSURL(string: imageURLString) as NSURL!
let imageData = NSData(contentsOfURL: imageURL) as NSData?
let image = UIImage(data: imageData!) as UIImage? // EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subode=0x0)
if let downloadedImage = image {
NSOperationQueue.mainQueue().addOperationWithBlock(){
let cell = tableView.cellForRowAtIndexPath(indexPath) as! TweetCell
cell.tweetUserAvatar.image = downloadedImage
}
self.imageCache?.setObject(downloadedImage, forKey: imageURLString)
}
}
}
Debug area:
imageURLString String
"http://pbs.twimg.com/profile_images/465756113825067008/8jH2nZO0_normal.png"
tableView UITableView 0x00007fc52481b400
indexPath NSIndexPath * 0xc000000000000016
self Chapter7_8___Social_App.FeedViewController 0x00007fc5235f5ef0
imageURL NSURL! "http://pbs.twimg.com/profile_images/465756113825067008/8jH2nZO0_normal.png"
imageData NSData? nil None
image UIImage? 0x000000010ee778dd
downloadedImage UIImage
I had this issue as well and found that my image was being initialized with bad data. This is to say that the image I requested from the server did not exist and the server sent back a response which could not be converted into an UIImage.
To mitigate this you can do the following:
if let cachedImage = image {
cell.tweetUserAvatar.image = cachedImage
}
else {
cell.tweetUserAvatar.image = UIImage(named: "camera.png")
queue?.addOperationWithBlock() {
let imageURL = NSURL(string: imageURLString) as NSURL!
let imageData = NSData(contentsOfURL: imageURL) as NSData?
if let image = UIImage(data: imageData!) {
let downloadedImage = image
NSOperationQueue.mainQueue().addOperationWithBlock(){
let cell = tableView.cellForRowAtIndexPath(indexPath) as! TweetCell
cell.tweetUserAvatar.image = downloadedImage
}
self.imageCache?.setObject(downloadedImage, forKey: imageURLString)
}
}
}
What I have done above is changed
let image = UIImage(data: imageData!) as UIImage?
if let downloadedImage = image {
...
...
}
To:
if let image = UIImage(data: imageData!) {
let downloadedImage = image
...
...
}
In this way I have checked that the image was able to be created successfully. If the image is not able to be created then the code will not execute and you will not receive an error.
If you expect an image to be at the url you specified in 'imageURLString' then I would suggest that you check the url you are using.
I also noticed that you did not get any data back which is why you could not create the UIIMage. You can test to see if this is the case with the following:
let imageData = NSData(contentsOfURL: imageURL) as NSData?
if imageData != nil {
Do More Stuff
...
{
I hope my answer was helpful. If you have any questions feel free to leave a comment and I'll do my best to answer them.
More Info Here:
This question & answer also provides methods on how to handle the case when the UIImage cannot be created from the data provide.

Grab image from server in ios

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

Resources