2016-12-07 27 views
0

我試圖表明圖像的圖像,但出現以下錯誤:斯威夫特3頁:如何顯示使用URL與API

error : fatal error: unexpectedly found nil while unwrapping an Optional value

var imageURL:UIImageView! 
override func viewDidLoad() { 
    super.viewDidLoad() 
    let url = NSURL(string:"http://cdn.businessoffashion.com/site/uploads/2014/09/Karl-Lagerfeld-Self-Portrait-Courtesy.jpg") 
    let data = NSData(contentsOfURL:url!) 
    if data!= nil { 
     imageURL.image = UIImage(data:data!) 
    } 
} 
+0

我想說這不是重複。 NSURL不是不能強制解包的。它錯誤地使用了'NSData(contentsOfURL:url!)',這是不直觀的,因爲它在文檔中不明顯,這個方法實際上做了什麼。 –

回答

0

從蘋果文檔:

Important

Do not use this synchronous method to request network-based URLs. For network-based URLs, this method can block the current thread for tens of seconds on a slow network, resulting in a poor user experience, and in iOS, may cause your app to be terminated.

Instead, for non-file URLs, consider using the dataTaskWithURL:completionHandler: method of the NSURLSession class. See URL Session Programming Guide for details.

也許考慮使用Alamofire完成這項任務?

Alamofire.request(.GET, "http://cdn.businessoffashion.com/site/uploads/2014/09/Karl-Lagerfeld-Self-Portrait-Courtesy.jpg").response { (request, response, data, error) in 
    self.imageURL.image = UIImage(data: data, scale:1) 
}