Swift 3:显示URL中的图片 [英] Swift 3: Display Image from URL

查看:251
本文介绍了Swift 3:显示URL中的图片的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Swift 3中,我试图从互联网上捕获图像,并使用以下代码行:

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)

我在做什么错了?

推荐答案

您的代码有以下几项内容:

There's a few things with your code as it stands:

  1. 您正在使用大量的投射,不需要.
  2. 您将URL视为本地文件URL,不是这种情况.
  3. 您永远不会下载图像要使用的URL.

我们要做的第一件事是将您的变量声明为let,因为我们稍后将不对其进行修改.

The first thing we are going to do is to declare your variable as let, as we are not going to modify it later.

let catPictureURL = URL(string: "http://i.imgur.com/w5rkSIj.jpg")! // We can force unwrap because we are 100% certain the constructor will not return nil in this case.

然后,我们需要下载该URL的内容.我们可以使用URLSession对象来做到这一点.调用完成处理程序时,我们将从网络上下载UIImage.

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 a UIImage downloaded from the web.

// Creating a session object with the default configuration.
// You can read more about it here https://developer.apple.com/reference/foundation/urlsessionconfiguration
let session = URLSession(configuration: .default)

// Define a download task. The download task will download the contents of the URL as a Data object and then you can do what you wish with that data.
let downloadPicTask = session.dataTask(with: catPictureURL) { (data, response, error) in
    // The download has finished.
    if let e = error {
        print("Error downloading cat picture: \(e)")
    } else {
        // No errors found.
        // It would be weird if we didn't have a response, so check for that too.
        if let res = response as? HTTPURLResponse {
            print("Downloaded cat picture with response code \(res.statusCode)")
            if let imageData = data {
                // Finally convert that Data into an image and do what you wish with it.
                let image = UIImage(data: imageData)
                // Do something with your image.
            } else {
                print("Couldn't get image: Image is nil")
            }
        } else {
            print("Couldn't get response code for some reason")
        }
    }
}

最后,您需要在下载任务上调用resume,否则您的任务将永远无法启动:

Finally you need to call resume on the download task, otherwise your task will never start:

downloadPicTask.resume().

所有这些代码起初看起来似乎有些吓人,但是URLSession API是基于块的,因此它们可以异步工作-如果您阻塞UI线程几秒钟,则操作系统将杀死您的应用.

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:

let catPictureURL = URL(string: "http://i.imgur.com/w5rkSIj.jpg")!

// Creating a session object with the default configuration.
// You can read more about it here https://developer.apple.com/reference/foundation/urlsessionconfiguration
let session = URLSession(configuration: .default)

// Define a download task. The download task will download the contents of the URL as a Data object and then you can do what you wish with that data.
let downloadPicTask = session.dataTask(with: catPictureURL) { (data, response, error) in
    // The download has finished.
    if let e = error {
        print("Error downloading cat picture: \(e)")
    } else {
        // No errors found.
        // It would be weird if we didn't have a response, so check for that too.
        if let res = response as? HTTPURLResponse {
            print("Downloaded cat picture with response code \(res.statusCode)")
            if let imageData = data {
                // Finally convert that Data into an image and do what you wish with it.
                let image = UIImage(data: imageData)
                // Do something with your image.
            } else {
                print("Couldn't get image: Image is nil")
            }
        } else {
            print("Couldn't get response code for some reason")
        }
    }
}

downloadPicTask.resume()

这篇关于Swift 3:显示URL中的图片的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆