3

I'm new to swift and not sure why an image is loading from the url. The code:

        let url = NSURL(string: imageURL)
    let task = NSURLSession.sharedSession().dataTaskWithURL(url!, completionHandler: { (data, response, error) -> Void in
        println("Should load the pic!")
        var profilePic = UIImage(data: data)
        self.profileImage.setImage(profilePic)
    })

In my interface controller I have an image called "profileImage" that is linked with an IBOutlet. One thing I noticed is that "Should load the pic!" does not appear in the console so it is not getting to the setImage code..

2 Answers 2

4

when you downloading image from URL. I suggest you to do this in background. here is the example code for you:

import UIKit

class ViewController: UIViewController {

@IBOutlet weak var profileImage: UIImageView!
override func viewDidLoad() {
    super.viewDidLoad()

    profileImage.contentMode = UIViewContentMode.ScaleAspectFit
    if let checkedUrl = NSURL(string: "http://www.apple.com/euro/ios/ios8/a/generic/images/og.png") {
        downloadImage(checkedUrl)
    }
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}


func getDataFromUrl(urL:NSURL, completion: ((data: NSData?) -> Void)) {
    NSURLSession.sharedSession().dataTaskWithURL(urL) { (data, response, error) in
        completion(data: NSData(data: data))
        }.resume()
}

func downloadImage(url:NSURL){
    println("Started downloading \"\(url.lastPathComponent!.stringByDeletingPathExtension)\".")
    getDataFromUrl(url) { data in
        dispatch_async(dispatch_get_main_queue()) {
            println("Finished downloading \"\(url.lastPathComponent!.stringByDeletingPathExtension)\".")
            self.profileImage.image = UIImage(data: data!)
        }
    }
}
}
Sign up to request clarification or add additional context in comments.

2 Comments

This is for Watchkit. Im getting error on self.profileImage.image = UIImage(data: data!). That says "WKInterfaceImage" does not have a member named 'image'
I just gave you an example..make changes in code as per your need..:)
0

Try this, as it may help you:

dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), {
    var profilePic =  UIImage(data: NSData(contentsOfURL: NSURL(string:"http://devhumor.com/wp-content/uploads/2012/04/devhumor.com_pointers.png")));

    self.profileImage.setImage(profilePic);
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.