【发布时间】:2014-08-11 22:40:02
【问题描述】:
我正在尝试用 Swift 制作一个简单的网络浏览器应用程序来学习这门语言。现在,我坚持允许用户点击他们最近添加的书签,并让 webview 加载特定的 url。
要决定选择哪个 URL,我在 BookmarkTVC(带书签的 TableViewController)中有这个
func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!) {
let vc = ViewController(nibName: "ViewController", bundle: nil)
vc.gotoWebsite(bookmarks[indexPath.row].url)
self.dismissViewControllerAnimated(true, completion: nil)
}
编辑:BookmarksTVC 截图:http://imgur.com/7rKcGBZ
我100%知道
书签[indexPath.row].url
得到了正确的字符串,因为我打印了它。
现在,这是我的vc.gotoWebsite 函数
func gotoWebsite(link: String) {
// Format Link
var formattedLink: String!
if link.hasPrefix("http://") || link.hasPrefix("https://") {
formattedLink = link
} else if link.hasPrefix("www.") {
formattedLink = "http://\(link)"
} else {
formattedLink = "http://www.\(link)"
}
// Goto formatted link
println(formattedLink)
let url = NSURL(string: formattedLink)
println(url)
let request = NSURLRequest(URL: url)
println(request)
webView.loadRequest(request)
}
在webView.loadRequest(request) 行,我得到:
fatal error: unexpectedly found nil while unwrapping an Optional value
这是断点(图片):http://imgur.com/S7dMswD&4pdL4xX
即使我已经打印了request 变量并得到了响应
<NSURLRequest: 0x7fb9c8616700> { URL: https://www.google.com/?gws_rd=ssl, headers: (null) }
请帮忙。同样,我要做的只是获取与用户单击的表格视图单元格相关联的 url。然后,我使用该字符串并从另一个类中调用一个方法,该方法会到达该 URL。
【问题讨论】:
-
好吧,如果您确定请求不是 nil,那么它可能是 webView 是 nil,因为它是该行中唯一的其他变量...
-
当我从 ViewController 类中的其他方法调用它时,此方法有效,但当我从其他类中调用它时,它不起作用...... hmmmmmmmmmm。有什么想法吗?
-
好吧,我认为 webView 大概是一个 IBOutlet 连接的变量,它会在视图加载时设置,但没有发生。请注意,从 nib doesn't necessarily load its view and instantiate things 创建视图控制器。
-
@马特吉布森,你是个天才!!那么,我将如何初始化这个 IBOutlet Webview?
-
有完全相同的问题。你解决了吗?