iOS WKWebView有时会显示

时间:2018-03-13 23:22:02

标签: ios wkwebview

我有一个不会通过iOS WKWebView显示的网页链接。如何通过WKWebView显示此类链接?

似乎只有3个版本的https://www.google.comhttp://www.apple.com会显示使用http://或https://的网页。如何通过WKWebView加载其他网页? (注意:所有网站都在不使用http://语法的情况下加载到Google Chrome和Apple Safari中。)

以下是ViewDidLoad的代码:

          @IBOutlet weak var myWebkitView: WKWebView!
          override func viewDidLoad() {
          super.viewDidLoad()


        `if let myUrl = URL(string:"https://www.ihs-us.org")`
         {

          let myURLRequest = URLRequest(url: myUrl)
          myWebkitView.load(myURLRequest)

         }

         }

      Below links works only for Apple and Google. 
     https://www.google.com will shows a Web site
     http://www.apple.com also will shows its web site
     schools.nyc.gov/SchoolPortals/08/X282 -- causes a crash
     ihs-us.org // causes a crash, and does not show a web page

2 个答案:

答案 0 :(得分:1)

所有浏览器都将http://附加到网址(如果不存在),通常如果网页支持SSL,则会重定向https://网站。我开发了一个供内部使用的浏览器,任何URL用户都输入,我将http://附加到URL。最简单的方法是

class func getValidURLFromString(_ urlString: String)->String{        
    if !urlString.hasPrefix("http://") && !urlString.hasPrefix("https://"){
        return "http://" + urlString
    }
    else {
        return urlString
    }
}

<强>编辑: ViewController代码

import UIKit
import WebKit
class ViewController: UIViewController, WKUIDelegate {

@IBOutlet weak var webView: WKWebView!
override func viewDidLoad() {
    super.viewDidLoad()
    let urlString = isValidURLFormat("schools.nyc.gov/SchoolPortals/08/X282")
    let myURL = URL(string: urlString)
    let myRequest = URLRequest(url: myURL!)
    webView.load(myRequest)
}
func isValidURLFormat(_ urlString: String) -> String {
    if !urlString.hasPrefix("https://") && !urlString.hasPrefix("http://"){
        return "http://" + urlString
    }
    return urlString }

}

Plist设置

<key>NSAppTransportSecurity</key>
    <dict>
        <key>NSAllowsArbitraryLoads</key>
        <true/>
        <key>NSAllowsArbitraryLoadsInWebContent</key>
        <true/>
    </dict>

答案 1 :(得分:0)

试试这个 -

import UIKit
import WebKit

class ViewController: UIViewController{

    @IBOutlet var webView: WKWebView!

    override func viewDidLoad() {
        super.viewDidLoad()

        let urlString = "ihs-us.org"

        if urlString.hasPrefix("https://") || urlString.hasPrefix("http://"){
            let myURL = URL(string: urlString)
            let myRequest = URLRequest(url: myURL!)
            webView.load(myRequest)
        }else {
            let correctedURL = "http://\(urlString)"
            let myURL = URL(string: correctedURL)
            let myRequest = URLRequest(url: myURL!)
            webView.load(myRequest)
        }

    }

}

schools.nyc.gov/SchoolPortals/08/X282 -

enter image description here

对于ihs-us.org -

enter image description here

您只需执行以下步骤 -

打开项目的Info.plist文件。右键单击它并添加一行。

enter image description here

然后在你的(原样)中添加这两行 -

Info.plist`