Search code examples
iosswiftuiimagensdatansurl

Calling a URL within a variable to receive image


I'm trying to grab an image from an URL. Now I know you can do this by using let url = NSURL(string: "http://"). But what if you have a variable that has a url in it.

Example: self.testAd.getImgPath() has http://www.Woods.com/images/imgs/MAU_SouthTrees_mobi.jpg /as/img.cfm?gphc=14490.

How do we call testAd.getImgPath() to recognize the url and grab the image? I'm using this code below to grab the content and insert it into an image.

let url = NSURL(string:)    
var err: NSError?
var imageData :NSData = NSData(contentsOfURL: url!,options: NSDataReadingOptions.DataReadingMappedIfSafe, error: &err)!
var bgImage = UIImage(data:imageData)
imageView.image = bgImage
imageView.contentMode = .ScaleAspectFit

Solution

  • NSURL's initializer, NSURL(string:) takes a string parameter, and it doesn't have to be a literal string. We can pass a string variable in here.

    if let url = NSURL(string:testAd.getImgPath()) {
        var err: NSError?
        if let imageData = NSData(contentsOfURL:url, options:.DataReadingMappedIfSafe, error:&err) {
            let bgImage = UIImage(data:imageData)
            imageView.image = bgImage
            imageView.contentMode = .ScaleAspectFit
        }
    }