尝试使用NSURL下面的类时出错,下面的代码实际上是试图将我从Facebook拉入的图像存储到imageView.错误如下:
value of optional type 'NSURL?' not unwrapped, did you mean to use '!' or '?'
Run Code Online (Sandbox Code Playgroud)
不知道为什么会这样,帮忙!
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.
}
}
Run Code Online (Sandbox Code Playgroud)
你正在调用的NSURL构造函数有这个签名:
convenience init?(string URLString: String)
Run Code Online (Sandbox Code Playgroud)
?表示构造函数可能不返回值,因此它被视为可选.
这同样适用于NSData的构造函数:
init?(contentsOfURL url: NSURL)
Run Code Online (Sandbox Code Playgroud)
快速解决方法是:
let myProfilePictureURL = NSURL(string: "http://graph.facebook.com/bobdylan/picture")
let imageData = NSData(contentsOfURL: myProfilePictureURL!)
self.myImage.image = UIImage(data: imageData!)
Run Code Online (Sandbox Code Playgroud)
最好的解决方案是检查(解包)这些选项,即使您确定它们包含值!
您可以在此处找到更多关于选项的信息:链接到官方Apple文档.
| 归档时间: |
|
| 查看次数: |
10388 次 |
| 最近记录: |