Akshansh Thakur Akshansh Thakur - 2 years ago 198
Swift Question

How to download image from URL Swift

So I am trying to download images from url link and then trying to add them to an array of downloaded images but running into trouble.

I have searched stackoverflow and related sites, but could not find similar issue.

There are two kinds of images that I am downloading.

Example of 1st type is : http://img.youtube.com/vi/7lC3UZtLa6Y/0.jpg

Example of 2nd type is : http://master.dextra.xyz/_uploads/photos/image_111.webp

Please click on both to see the difference

I have no trouble downloading the first type, simply by using the following code. But as you can see the second url link would download itself on clicking and hence I get nil when extracting it

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {

// Downloading image 1
let data = NSData(contentsOfURL: NSURL(string: "http://img.youtube.com/vi/7lC3UZtLa6Y/0.jpg")!)
self.downloadedImages.append(UIImage(data: data!)!)
// No problem downloading above image, also shows up in my app

// Downloading image 2
let data = NSData(contentsOfURL: NSURL(string: "http://master.dextra.xyz/_uploads/photos/image_111.webp")!)
self.downloadedImages.append(UIImage(data: data!)!)
// getting nil in UIImage(data: data!), although it says that data is around 300000 bytes.

dispatch_async(dispatch_get_main_queue(), {
// Updating UI

So, how can I download images of second type? It downloads it successfully. But cannot access it because it stores in computer somewhere, I am not sure about it though

Any help would be appreciated. Thanks

Answer Source

I have tried your code. The image is successfully downloaded in the second case. The reason why you are getting nil instead of valid UIImage is unsupported image format. Here is the list of supported formats:

Tagged Image File Format (TIFF)

Joint Photographic Experts Group (JPEG)

Graphic Interchange Format (GIF)

Portable Network Graphic (PNG)

Windows Bitmap Format (DIB)

Windows Icon Format (.ico)

Windows Cursor (.cur)

XWindow bitmap (.xbm)


Hope it helps.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download