Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS

How to show an image from a URL contained within an array

Hey there

I've gone through the basic Swift app course, and I've started playing around...! I've managed to get my Swift iOS app to show an image pulled in from a URL. However, I'd like to save the URL in an array, and pull it from there.

I've pulled together the following code and nothing seems to show.

I think the function is expecting an NSURL and its getting a string, so not showing? If I println, I get the string in the console.

Any ideas?

Which course goes into this sort of thing that I can do next?

Thanks!

    let loadImage = [

    NSURL(string: "https://www.petfinder.com/wp-content/uploads/2012/11/140272627-grooming-needs-senior-cat-632x475.jpg"),


    ]

    loadImage[0]


}

func loadImage(urlString:String)
{

    var imgURL: NSURL = NSURL(string: urlString)!
    let request: NSURLRequest = NSURLRequest(URL: imgURL)
    NSURLConnection.sendAsynchronousRequest(
        request, queue: NSOperationQueue.mainQueue(),
        completionHandler: {(response: NSURLResponse!,data: NSData!,error: NSError!) -> Void in
            if error == nil {
                self.image_element.image = UIImage(data: data)
            }
    })

}

1 Answer

Gabe Nadel
seal-mask
STAFF
.a{fill-rule:evenodd;}techdegree
Gabe Nadel
Treehouse Guest Teacher

Ok, so you've actually done exactly the right type of thinking here, you figured out that the data type you have isn't what you need for an input, but that you SHOULD be able to convert it to that type. When you encounter that kind of issue, which happens all the time, with all sorts of objects, the best thing to do is check the documentation for the class you are trying to convert TO - in your case, NSURL.

https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSURL_Class/

Once there, you'll see on the left a topic titled "Creating an NSURL Object." If you click that, you'll see a bunch of methods for creating NSURL's...as luck would have it, right at the top of the list is one for converting a string to an NSURL!