背景: 我們app里有一個(gè)webView編輯器。以前用的是UIWebView, 但是升級(jí)到iOS13后 UIWebView 已經(jīng)被廢棄了,而且UIWebView在iOS13的機(jī)器上很不穩(wěn)定,很多crash,so決定改為WKWebView。
這里不介紹各種怎么換WKWebView了,百度,google 一堆文章,這里寫下我遇到的一個(gè)問題。
首先我們的html是我們本地拼接起來的,加載的時(shí)候是
self.webView.loadHTMLString(htmlString, baseURL:nil)
然后調(diào)用什么的都沒問題。但是如果插入圖片,圖片不顯示。用safari聯(lián)調(diào)的時(shí)候 發(fā)現(xiàn)JS報(bào)了個(gè)"Not allowed to load local resource"。也找過寫JS的同事,也查過各種文章,都沒有結(jié)果。也想過跨域問題,但是依然沒有解決方案。?
后來偶然間發(fā)現(xiàn)了另一個(gè)加載的方法
@available(iOS 9.0, *) ? ?
open func loadFileURL(_ URL: URL, allowingReadAccessTo readAccessURL: URL) -> WKNavigation??
這個(gè)方法的注釋是這樣的(自行翻譯)
?/** @abstract Navigates to the requested file URL on the filesystem. ?? ? @param URL The file URL to which to navigate. ?? ? @param readAccessURL The URL to allow read access to. ?? ? @discussion If readAccessURL references a single file, only that file may be loaded by WebKit. ?? ? If readAccessURL references a directory, files inside that file may be loaded by WebKit. ?? ? @result A new navigation for the given file URL. ?? ? */
然后聯(lián)想到我們用到的
/** @abstract Sets the webpage contents and base URL.
?? ? @param string The string to use as the contents of the webpage.
?? ? @param baseURL A URL that is used to resolve relative URLs within the document.
?? ? @result A new navigation.
?? ? */
? ? open?func?loadHTMLString(_string:String, baseURL:URL?) ->WKNavigation?
emmmm 這個(gè)baseURL原來是有用的?。。魅肟赡芤虞d資源的路徑,比如我們的圖片是會(huì)保存到Caches目錄下,這里可以把Caches目錄的路徑傳入,這樣這個(gè)webview就可以加載這個(gè)路徑下的圖片了......?
總結(jié):怎么說呢,有時(shí)候用一個(gè)東西的時(shí)候,別找個(gè)demo或者查幾篇文章就直接用了,還是要翻一下文檔的。可能一個(gè)困擾你的bug,就在文檔中一句不顯眼的可選變量里。