Swift Image from URL - swift

I am trying to display an image from a URL in swift using the code below but nothing appears.
let url = NSURL(string: "https://www.psychicliving.co.uk/images/Michael.jpg")
if let data = NSData(contentsOf: url as! URL) {
cell.imgCarNane.image = UIImage(data: data as Data)
}
The odd thing is that if I substitute the image for a jpeg hosted on a different site like:
https://www.thawte.com/assets/hp/images/promo_myths.jpg
it displays fine.
Is there something about the image I am trying to use that would be causing the issue?
if someone could take a look I would be very greatful.
Thanks!

I don't know why since the website you're retrieving the image from is using https (and seems secured), but you have to add the website (or allow arbitrary loads) in your plist.
Create an entry App Transport Security Settings https://developer.apple.com/library/content/documentation/General/Reference/InfoPlistKeyReference/Articles/CocoaKeys.html

add NSAppTransportSecurity in info.plist
NSAllowsArbitraryLoads= YES
let url = URL(string: "https://www.psychicliving.co.uk/images/Michael.jpg")
let data = try? Data(contentsOf: url!) //make sure your image in this url does exist, otherwise unwrap in a if let check / try-catch
imageViewTest.image = UIImage(data: data!)
}

Related

How to save multi images from URLs to local storage in swift?

I am developing Restaurant app.
There are 340 foods data.
I am getting this data from backend that developed with Laravel.
App is working well in online.
But, although network is turned off, All foods data should be displayed in app.
So, I tried to save foods data to local.
It is good to save text data to local(exactly, UserDefaults and FileSystem).
But, when I try to save images to local from urls, It occur error and don't save to local exactly.
Have you ever seen such problems?
If yes, I appreciate your help.
Thanks
I don't know exactly what error you faced, but I think the answer to the link can help you.
How do I make JSON data persistent for offline use (Swift 4)
Additionally, image data would be good to be cached.
If you communicate based on URLSession, you can process caching as below.
Saving an Image to a Cache
Cache.imageCache.setObject(image, forKey: url.absoluteString as NSString)
Bring up cached images
let cacheImage = Cache.imageCache.object(forKey: url.absoluteString as NSString)
Code
class Cache {
static let imageCache = NSCache<NSString, UIImage>()
}
extension UIImageView {
func imageDownload(url: URL, contentMode mode: UIView.ContentMode = .scaleAspectFit) {
if let cacheImage = Cache.imageCache.object(forKey: url.absoluteString as NSString) {
DispatchQueue.main.async() { [weak self] in
self?.contentMode = mode
self?.image = cacheImage
}
}
else {
var request = URLRequest(url: url)
request.httpMethod = "GET"
URLSession.shared.dataTask(with: request) { 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 {
print("Download image fail : \(url)")
return
}
DispatchQueue.main.async() { [weak self] in
print("Download image success \(url)")
Cache.imageCache.setObject(image, forKey: url.absoluteString as NSString)
self?.contentMode = mode
self?.image = image
}
}.resume()
}
}
}
To make caching more convenient, use a library called Kingfisher.
Kingfisher
You need to manage lazy loadings, you can use SDWebImages instead of manage it manually
SDWebImages will automatically manage your images caches and will also load them without internet here is a simple usage of it
add pod in podfile
pod 'SDWebImage'
usagae:
import SDWebImage
imageView.sd_setImage(with: URL(string: "http://www.example.com/path/to/image.jpg"), placeholderImage: UIImage(named: "placeholder.png"))

how to assign a URL to imageView in swift?

I have JSON response for image after a post request
"profile_picture": "uploads/profile_pictures/18/file.jpeg"
if I combine the base URL and "profile_picture" url I can have the image // browsing on the web page
http://ms.XXX.net/uploads/profile_pictures/18/file.jpeg
I want to store that image url to a UIImageView and show that image on ImageView.Please guide me how do I do that. Below is how im trying.
image = "http://ms.XXX.net/"+"\(LoginSingleton.shared.pathImage!)"
imageView.image = image as? UIImage
It would be ideal to use third party frameworks like SDWebImage, Kingfisher etc. for better user experience. But you can do it without them by getting the data from url asynchronously and then set the image.
guard let url = URL(string: "image-url") else { return }
DispatchQueue.global().async {
guard let data = try? Data(contentsOf: url) else { return }
DispatchQueue.main.async {
let image = UIImage(data: data)
// Set the image to your image view
}
}

how to get image from Json in Swift

i'm a baby of xcode developer, and i really need a help. Below is one of my json data, that i have print in output, for the text i already got display into my screen, but now i'm trying to get the image from the server, and i don't know how to do it.
JSON :
"MoviePhotoL" : "\/Data\/UploadFile\/cnymv-01_1.jpg",
"MoviePhotoP" : "\/Data\/UploadFile\/cnymv-02_1.jpg"
XCODE:
let userImage = iP["MoviePhotoP"] as? String
cell.imageView.image = userImage (??????)
i know that String cannot be converted into UIImage, and i already try to convert it to NSData and convert the NSData to UIImage(data), but still not get the picture :'(.... can somebody please help me?? i really need some help
Those paths seem relative to another source.
You need to generate or get an absolute URL that will let you access the image.
Right now you have a simple string and that's all, you can't convert this to data or image.
You need a string that you can put in a browser and load an image.
Once you're able to do that, you can load the image in your app.
Example:
func getImage(from string: String) -> UIImage? {
//2. Get valid URL
guard let url = URL(string: string)
else {
print("Unable to create URL")
return nil
}
var image: UIImage? = nil
do {
//3. Get valid data
let data = try Data(contentsOf: url, options: [])
//4. Make image
image = UIImage(data: data)
}
catch {
print(error.localizedDescription)
}
return image
}
//1. Get valid string
let string = "https://images.freeimages.com/images/large-previews/f2c/effi-1-1366221.jpg"
if let image = getImage(from: string) {
//5. Apply image
cell.imageView.image = image
}
NOTE: Data(contentsOf:options:) is synchronous and can reduce performance. The larger the image, the longer it will lock it's thread.
Generally you would do such intensive tasks in a background thread and update UI on the main thread, but... to keep this answer simple, I chose not to show that.

Display base64 encoded image in imageview: SWIFT 3

I have base64 image string which is downloaded from a webpage using POST request and I am trying to decode and display inside imageview but it's not working. I have tried couple of sources but no luck :(
let base64String = "data:image/jpg;base64,/9j/4aaQSkZJRg0BMADAE15a5df.....H/12Q=="
Currently, trying this method:
if let decodedData = Data(base64Encoded: base64String, options: .ignoreUnknownCharacter) {
let image = UIImage(data: decodedData)
ImageView.image = image
} else {
print("error in decoding")
}
Tried NSData method also:
let dataDecode:NSData = NSData(base64Encoded: base64String!, options:.ignoreUnknownCharacters)!
let image= UIImage(data: dataDecode as Data)!
yourImageView.image = image
The else part always executes. I have tried this in xCode playground by putting encoded string in static variable and noticed nil in front of if condition line.
Not sure, what I am doing wrong?
Your base64String is actually a URL with a data scheme. There is built in support for these types of URLs.
You can do something like:
let dataString = "data:image/jpg;base64,/9j/4aaQSkZJRg0BMADAE15a5df.....H/12Q=="
let dataURL = URL(string: dataString)
let data = Data(contentsOf: dataURL)
let image = UIImage(data: data)
I leave it as an exercise to properly handle optional values and error handling.
be careful, only part of the string represents the image
let base64String = "data:image/jpg;base64,9j/4aaQSkZJRg0BMADAE15a5df.....H/12Q=="

Swift Haneke: cache doesn't resolve

I'm trying to pre-load some images with the following code:
let thumbnailUrl = NSURL(string: urlString)
let fetcher = NetworkFetcher<UIImage>(URL: thumbnailUrl)
Shared.imageCache.fetch(fetcher) {
println("Finished")
}
But afterwards when I try to set it to the imageview, it downloads it again from the network instead of reading it from the cache. This is the code:
self.imageView.hnk_setImageFromURL(
NSURL(string: urlString)
success: { thumbnail in
println("Finished setting image")
}
)
Is this a bug or maybe I missunderstood the usage of imageCache.fetch()?
PD: I put breakpoints in the whole code, and I can guarantee the key for the cache (in this case, the url) is exactly the same, so I have no clue why the cache isn't resolving when used with .hnk_setImageFromURL()
I was stuck on this for 3 days. I hope this answer might help someone else in the future.
The issue was that I didn't specify a Format Name to the fetcher, while the UIImageView.hnk_setImageFromURL() does. The way to fix it is:
let thumbnailUrl = NSURL(string: urlString)
let fetcher = NetworkFetcher<UIImage>(URL: thumbnailUrl)
let cache = Shared.imageCache
let format = self.imageView.hnk_format
cache.fetch(fetcher, formatName: format.name) {
println("Finished")
}