2017-05-22 91 views
0

我繼承的UIWebView但是當我試圖使它與此錯誤崩潰的請求:iOS的:子類的UIWebView的URLRequest崩潰

fatal error: unexpectedly found nil while unwrapping an Optional value 

這是我實現:

的ViewController:

var web:MyWebView! 

    override func viewDidLoad() { 
     super.viewDidLoad() 
self.webPage = MyWebView(frame: self.view.frame) 
     self.view.bringSubview(toFront: self.webPage!) 
} 

class MyWebView: UIWebView,UIWebViewDelegate { 


let urlStr = "http://apple.com" 

override init(frame: CGRect) { 
    super.init(frame: frame) 
    scalesPageToFit = true 
    scrollView.bounces = false 
    delegate = self 
    let urlRequest = URL(string: urlStr) 
    let request = URLRequest(url: urlRequest!) 
    self.loadRequest(request) 

} 

如果在控制檯中檢查urlRequest的值:

po urlRequest 
nil 

你們誰都知道我在做什麼錯,或者爲什麼這個urlRequest設置爲nil?

我真的很感謝你的幫助。

+0

你如何初始化'MyWebView'稱呼它,它只是一個IBOutlet?如果沒有粘貼代碼,你在哪裏啓動它。你的打印報告在哪裏?你如何打印零? –

+0

是否說在哪條線上發生致命錯誤? – Koen

回答

0

這工作對我罰款

import UIKit 

    class MyWebView: UIWebView,UIWebViewDelegate { 


     let urlStr = "https://www.apple.com" 

     required init?(coder aDecoder: NSCoder) { 
      super.init(coder: aDecoder) 
     } 

     override init(frame: CGRect) { 
      super.init(frame: frame) 
      scalesPageToFit = true 
      scrollView.bounces = false 
      delegate = self 
      let urlRequest = URL(string: urlStr) 
      let request = URLRequest(url: urlRequest!) 
      self.loadRequest(request) 
     } 

    } 

然後從視圖 - 控制

import UIKit 

class ViewController: UIViewController { 

    override func viewDidLoad() { 
     super.viewDidLoad() 
     // Do any additional setup after loading the view, typically from a nib. 
    } 

    override func viewDidAppear(_ animated: Bool) { 

     let webView = MyWebView.init(frame: self.view.frame) 
     self.view.addSubview(webView) 

    } 

    override func didReceiveMemoryWarning() { 
     super.didReceiveMemoryWarning() 
     // Dispose of any resources that can be recreated. 
    } 

} 

enter image description here