我得到零错误。但我不明白为什么会这样。我可以通过打印获得选定的照片名称。但我不能在 NSUrl 中使用。你能帮我吗?
我的代码:
print(selectedPhoto)
if selectedPhoto != nil
{
let photoUrl = NSURL(string: "http://www.kerimcaglar.com/uploads/yemek-resimler/\(selectedPhoto)")
print("photo url: \(photoUrl)")
dataPhoto = NSData(contentsOfURL:photoUrl!)
yemekResim.image = UIImage(data: dataPhoto!)
}
else
{
print("Error")
}
最佳答案
来自苹果关于 NSData(contentsOfURL) 的文档
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.
如果您的应用因此而崩溃,它将被商店拒绝。
相反,你应该使用 NSURLSession。在我的示例中使用 Async 回调 block 。
此外,强制解包选项 !
也不是一个好主意,因为你会得到运行时错误,而不是使用 if let
语法
请参阅下面的示例。
if let photo = selectedPhoto{
let photoUrl = NSURL(string: "http://www.kerimcaglar.com/uploads/yemek-resimler/\(photo)")
if let url = photoUrl{
NSURLSession.sharedSession().dataTaskWithURL(url, completionHandler: {(data, response, error) in
if let d = data{
dispatch_async(dispatch_get_main_queue(), {
if let image = UIImage(data: d) {
self.yemekResim.image = image
}
})
}
}).resume()
}
}
}
关于ios - fatal error : Unexpectedly found nil while unwrapping an Optional value NSURL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37269618/