In Swift 3, I am trying to capture an image from the internet, and have these lines of code:
var catPictureURL = NSURL(fileURLWithPath: "http://i.imgur.com/w5rkSIj.jpg")
var catPictureData = NSData(contentsOf: catPictureURL as URL) // nil
var catPicture = UIImage(data: catPictureData as! Data)
What am I doing wrong here?
You could also use Alamofire\AlmofireImage for that task: https://github.com/Alamofire/AlamofireImage
The code should look something like that (Based on the first example on link above):
While it is neat yet safe, you should consider if that worth the Pod overhead. If you are going to use more images and would like to add also filter and transiations I would consider using AlamofireImage
There's a few things with your code as it stands:
The first thing we are going to do is to declare your variable as
let
, as we are not going to modify it later.Then we need to download the contents of that URL. We can do this with the
URLSession
object. When the completion handler is called, we will have aUIImage
downloaded from the web.Finally you need to call
resume
on the download task, otherwise your task will never start:downloadPicTask.resume()
.All this code may look a bit intimidating at first, but the
URLSession
APIs are block based so they can work asynchronously - If you block your UI thread for a few seconds, the OS will kill your app.Your full code should look like this:
Using Alamofire worked out for me on Swift 3:
Step 1:
Integrate using pods.
pod 'Alamofire', '~> 4.4'
pod 'AlamofireImage', '~> 3.3'
Step 2:
import AlamofireImage
import Alamofire
Step 3:
The easiest way according to me will be using SDWebImage
Add this to your pod file
Run pod install
Now import SDWebImage
Now for setting image from url
It will show placeholder image but when image is downloaded it will show the image from url .Your app will never crash
This are the main feature of SDWebImage
Categories for UIImageView, UIButton, MKAnnotationView adding web image and cache management
An asynchronous image downloader
An asynchronous memory + disk image caching with automatic cache expiration handling
A background image decompression
A guarantee that the same URL won't be downloaded several times
A guarantee that bogus URLs won't be retried again and again
A guarantee that main thread will never be blocked Performances!
Use GCD and ARC
To know more https://github.com/rs/SDWebImage
Swift
Good solution to extend native functionality by extensions
Usage
Convenience initializer is failable and accepts optional
URL
– approach is safe.