-1

I'm tyring to learn swift. I have a simple demo project. I have a variable, and its value is a url which points to an image. when I try to print this value (the value of the URL encoded in the variable), it works fine, but when I try to use that same variable's value at runtime, it fails. What should I do?

var picurl : String!

profilePicView.image = UIImage(named: "\(picurl)")  // image is not showing with pic url

    print("User name --- \(Username)")
    print("User picurl --- \(picurl)")// but here value is printed.

Thank you.

Max von Hippel
  • 2,856
  • 3
  • 29
  • 46
Chetan Lodhi
  • 353
  • 1
  • 3
  • 21
  • can you show the result of `picurl`, just print `print("User picurl --- \(picurl)") – Anbu.Karthik Jul 18 '16 at 06:05
  • 3
    Possible duplicate of [Loading/Downloading image from URL on Swift](http://stackoverflow.com/questions/24231680/loading-downloading-image-from-url-on-swift) – Bhavin Bhadani Jul 18 '16 at 06:07
  • 1
    User picurl --- https://lh3.googleusercontent.com/-pHEFr40oFMk/AAAAAAAAAAI/AAAAAAAAAHc/pic1.jpg – Chetan Lodhi Jul 18 '16 at 06:07
  • [Download image from url](http://stackoverflow.com/questions/29472149/swift-how-to-display-an-image-using-url) – Bhavin Bhadani Jul 18 '16 at 06:08
  • You need to download the image from the link before setting it to UIImageView. UIImageView accepts instances of UIImage. And UIImage accepts instances of images or images created with physical names inside the bundle. Your linked image is not in the bundle so it won't load – NSNoob Jul 18 '16 at 06:14
  • Thanks.. @NSNoob for your valuable reply. – Chetan Lodhi Jul 18 '16 at 06:27

1 Answers1

2

if you are fetch the image from URL use this

if let imageUrl = NSURL(string: \(picurl)) {
if let imageData = NSData(contentsOfURL: imageUrl) {
    profilePicView.image = UIImage(data: imageData)
}        
}

load from locally use this

if let img = UIImage(named: "\(picurl)") {

 profilePicView.image =  img
 }
Anbu.Karthik
  • 82,064
  • 23
  • 174
  • 143