我在Swift中编写了一个简单的WebView,但每当我尝试在iOS模拟器中启动它时,我都会遇到这些错误。出了什么问题?
import UIKit
class ViewController: UIViewController {
@IBOutlet var webview: UIWebView
var urlpath = "http://www.google.de"
func loadAddressURL(){
let requesturl = NSURL(string: urlpath)
let request = NSURLRequest(URL: requesturl)
webview.loadRequest(request)
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
loadAddressURL()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
错误:
fatal error: unexpectedly found nil while unwrapping an Optional value
(lldb)
self uiwebview.ViewController 0x7987fc70 0x7987fc70
request NSURLRequest * 0x78ebfc40 0x78ebfc40
requesturl NSURL * "" 0x78ec0040
答案 0 :(得分:11)
您根本没有将UIWebView连接到webview
类属性
打开助理编辑器,在左侧显示您的xib或故事板,在右侧显示您的视图控制器源文件,单击webview
属性左侧的圆圈并拖动到UIWebView
控件。建立连接后,运行应用程序,它现在应该可以正常工作
答案 1 :(得分:0)
我猜你得到一个白页,因为你在模拟器上测试。如果您在真实设备上进行测试,那么您应该没问题。
答案 2 :(得分:0)
你需要把“!”在“UIWebView”之后并解开“requesturl”以获取您的String值,否则它是可选的并且您会收到错误。
import UIKit
class WebViewController: UIViewController {
@IBOutlet var webview: UIWebView!
var urlpath: String = "http://www.google.de"
func loadAddressURL(){
let requesturl = NSURL(string: urlpath)
let request = NSURLRequest(URL: requesturl!)
webview.loadRequest(request)
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
loadAddressURL()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}