1

I have the following code in my ViewController.swift class:

import UIKit

class ViewController: UIViewController {
    @IBOutlet weak var imageView: UIImageView!

    var newImage : UIImage?

    let imgURL = NSURL(string : DemoURLs.photoURL)

    func fetchImage(){
        if let url = imgURL{
           let imageData = NSData(contentsOfURL: url)

              if imageData != nil{
                 newImage  = UIImage( data: imageData! )
              } else {
                newImage = nil
            }
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        imageView.image = newImage
    }
}

The demoURLs.swift file has a simple struct like this:

import Foundation

struct DemoURLs{
    static var photoURL = " http://science-all.com/images/wallpapers/image/image-6.jpg "
}

When I run this in the simulator I get a plain white screen.

Eric Aya
  • 69,473
  • 35
  • 181
  • 253
209135
  • 517
  • 5
  • 15

1 Answers1

1

There are three problems:

  1. You url contain whitespace at the beginning and end of the string (so it starts as <Space>http://s..., but should be http://s...)

  2. If you developing for iOS 9, it block http request for security reason. You could disable it by going Info.plist file, adding App Transport Security Settings key and adding another key inside it - Allow Arbitrary Loads with YES value. Should look something like this:

enter image description here

  1. You should call fetchImage() in viewDidLoad(), just before you set image imageView.image = newImage
Alexander Zimin
  • 1,700
  • 1
  • 15
  • 19