为WKWebkitView运行localhost

时间:2017-09-25 14:24:47

标签: ios swift xcode uiwebview wkwebview

以前,当将本地html内容加载到UIWebView时,它会在后台自动运行localhost / server。例如,这种服务器仿真使我能够通过json加载动态内容。以下示例代码;

@IBOutlet weak var webView: UIWebView!

    override func viewDidLoad() {
        super.viewDidLoad()

        webView.loadRequest(URLRequest(url: URL(fileURLWithPath: Bundle.main.path(forResource: "www/index", ofType: "html")!)))
}

我现在正在尝试将其实现为WKWebView。我可以加载本地html内容,但与UIWebView不同,WKWebView不会模拟localhost / server,所以我不能像以前那样做,比如用json等动态加载内容。我如何通过localhost运行本地html内容?如果UIWebView自动拥有该功能,那么WKWebView肯定应该拥有它吗?代码如下。

@IBOutlet weak var webView: WKWebView!

override func viewDidLoad() {
    super.viewDidLoad()

    webView.load(URLRequest(url: URL(fileURLWithPath: Bundle.main.path(forResource: "www/index", ofType: "html")!)))
}

注意:我正在使用Xcode 9,因此WKWebview将通过Storyboard添加,并作为插座引用。

非常感谢任何可以帮助我的人。

1 个答案:

答案 0 :(得分:5)

启动localhost服务器并将其添加到info.plist

<key>NSAppTransportSecurity</key>  
<dict>  
    <key>NSExceptionDomains</key>  
    <dict>  
        <key>127.0.0.1</key>  
        <dict>  
            <key>NSExceptionAllowsInsecureHTTPLoads</key>  
            <true/>  
        </dict>  
        <key>localhost</key>  
        <dict>  
            <key>NSExceptionAllowsInsecureHTTPLoads</key>  
            <true/>  
        </dict>  
    </dict>  
</dict>