MattBlack
MattBlack

Reputation: 3828

Swift Image from URL

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!

Upvotes: 0

Views: 931

Answers (2)

Abhishek
Abhishek

Reputation: 90

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

Upvotes: 0

Damien
Damien

Reputation: 3362

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

Upvotes: 1

Related Questions