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

问题描述

在 Swift 3 中,我尝试从 Internet 捕获图像,并使用以下代码行:

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 的图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 01:27