在 swift 中没有 http 或 https 时崩溃 uiwebview

crash uiwebview without http or https in swift

我想在 Web 视图中显示 URL

这是我的代码

  let urlString:String = "https://www.apple.com"
        let url:URL = URL(string: urlString)!
        let urlRequest:URLRequest = URLRequest(url: url)
        webView.load(urlRequest)

        urlTextField.text = urlString

如果用户忘记写 http 或 https 应用程序崩溃了我该如何解决这个错误

只需在字符串上使用starts(with:)来检测url字符串是否以http/https开头,如果不是,请自行添加"http://"(同时使用safe if let 而不是强制展开):

var urlString: String = "www.apple.com"
if !urlString.starts(with: "http://") && !urlString.starts(with: "https://") {
      urlString = "http://\(urlString)"
}
if let url: URL = URL(string: urlString) {
    let urlRequest: URLRequest = URLRequest(url: url)
    webView.load(urlRequest)
    urlTextField.text = urlString
}