我遇到了一个奇怪的问题 - 我无法在单独的viewcontroller的后台加载UIWebView
。具体来说,我有一个UITableViewCell
,带有一个按钮,可以在后面的viewcontroller中加载UIWebView。但是,我一直收到错误"在解包一个可选值时发现了nil" ...
这是我的代码:
func loadWebView(URLString:String) {
print("the urlstring is \(URLString)")
let theRequestURL = NSURL (string: URLString)
let theRequest = NSURLRequest (URL: theRequestURL!)
fullScreenWebView.loadRequest(theRequest)
}
print语句会生成正确的URL,因此问题不在于URL字符串未被传递。
此外,如果我从定义的视图控制器中加载UIWebView
,它可以完美地工作。我猜这个问题与在调用loadWebView()
时不是正确的viewcontroller有关...我读了Unable to display URL in WebView from another view controller,这有点帮助。
我做错了什么?
答案 0 :(得分:1)
使用
致电loadRequest
时
SecondViewController().loadWebView("URL STRING HERE")
您正在创建 SecondViewController 的新实例,而不是使用已加载的实例。
您需要在已在内存中的实例上调用loadRequest
,并初始化UIWebView
。
为此,您可以获取先前视图控制器的参考并调用方法来加载您的请求
假设SecondViewController是具有UIWebView的控制器
添加此项在顶部视图控制器(带有UITableView
的控制器)
func loadWebView(URLString:String) {
print("the urlstring is \(URLString)")
let theRequestURL = NSURL (string: URLString)
if let theRequest = NSURLRequest (URL: theRequestURL!) {
//In case you push view controller on a navigation stack
let vc : SecondViewController = self.backViewController()
vc.loadWebView(theRequest)
}
}
//Get previous view controller on navigation stack
func backViewController() -> UIViewController? {
if let stack = self.navigationController?.viewControllers {
for(var i=stack.count-1;i>0;--i) {
if(stack[i] == self) {
return stack[i-1]
}
}
}
return nil
}
现在在 SecondViewController 中添加
func loadWebView(request : NSURLRequest) {
// Replace customWebView with the reference variable of your `UIWebView`
customWebView.loadRequest(request)
}
答案 1 :(得分:0)
您收到此错误的原因是因为您需要展开零值。我总是建议使用if let
语句展开可空值:
func loadWebView(URLString:String) {
print("the urlstring is \(URLString)")
if let theRequestURL = NSURL (string: URLString) {
let theRequest = NSURLRequest (URL: theRequestURL!)
fullScreenWebView.loadRequest(theRequest)
}
}
并非每个字符串都可以转换为URL,这就是NSURL(string:)
返回可选值的原因。我会检查为什么你的URLString不能被解析为URL