我正在尝试在我的应用程序中显示Webview。 Webview的URL为对象格式,因为我是从json获得的。因此,在我的代码中,我将对象转换为NSString并尝试加载视图,但是我的应用程序崩溃了,它是这样的:致命错误:在解开Optional值时意外发现nil。有没有更好的方法将对象转换为字符串?如何获取Web视图以显示URL内容?
制作明细项目的位置:
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "showDetail" {
if let indexPath = self.tableView.indexPathForSelectedRow() {
let object: AnyObject = objectsPath[indexPath.row]
(segue.destinationViewController as DetailViewController).detailItem = object
}
}
}
这是我的代码:
var detailItem: AnyObject? {
didSet {
// Update the view.
self.configureView()
}
}
func configureView() -> NSURLRequest {
// Update the user interface for the detail item.
let detail: AnyObject = self.detailItem!
let stringURL: String = String(detail as NSString)
let url = NSURL(string: stringURL)
let request = NSURLRequest(URL: url!) <---ERROR occurs here
return request
// let string:St= detailItem!
// previewWebView.
// println(string)
//let url = NSURL(string: string)
//let request = NSURLRequest(URL: url!)
//self.previewWebView.loadRequest(request)
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.previewWebView.loadRequest(configureView())
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
最佳答案
您正在调用configureView()
中的viewDidLoad()
而不考虑self. detailItem
的值。在viewDidLoad()
中调用此函数之前,应先检查一个值,或者应修改configureView()
以不声明肯定存在self.detailItem
值。