Swift - NSURL错误 [英] Swift - NSURL error

查看:212
本文介绍了Swift - NSURL错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试使用下面的 NSURL 类时出错,下面的代码实际上是试图将我从Facebook拉入的图像存储到 ImageView的。错误如下:

Getting an error when trying to use the NSURL class below, the code below is essentially trying to store an image I am pulling in from Facebook into an imageView. The error is as follows:

value of optional type 'NSURL?' not unwrapped, did you mean to use '!' or '?' 

不确定为什么会发生这种情况,帮助!

Not sure why this is is happening, help!

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var myImage: UIImageView!

    override func viewDidLoad() {

        super.viewDidLoad()

        let myProfilePictureURL = NSURL(string: "http://graph.facebook.com/bobdylan/picture")
        let imageData = NSData(contentsOfURL: myProfilePictureURL)
        self.myImage.image = UIImage(data: imageData)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}


推荐答案

你正在调用的 NSURL 构造函数有这个签名:

The NSURL constructor you're calling has got this signature:

convenience init?(string URLString: String)

表示构造函数可能不返回值,因此它被认为是可选

? means that the constructor may not return a value, hence it is considered as an optional.

NSData 构造函数也是如此:

init?(contentsOfURL url: NSURL)

快速解决方法是:

let myProfilePictureURL = NSURL(string: "http://graph.facebook.com/bobdylan/picture")
let imageData = NSData(contentsOfURL: myProfilePictureURL!)
self.myImage.image = UIImage(data: imageData!)

最好的解决方案是检查(解包)这些选项,即使你确定它们包含一个值!

The best solution is to check (unwrap) those optionals, even if you're sure that they contain a value!

您可以在optiona上找到更多信息在这里:链接到Apple官方文档

You can find more infos on optionals here: link to official Apple documentation.

这篇关于Swift - NSURL错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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