Search code examples
htmlcssioswebviewwkwebview

Font works on Simulator but not iOS device


There a some questions already related to this issue but my case is different. In my case the font is downloaded from a zip file and saved here:

let path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first

Here's the HTML string:

    <html>
        <head>
        <style type=text/css>
            @font-face { font-family: 'Rubik-Regular'; src: url('Rubik-Regular.ttf'); }
            @font-face { font-family: 'Rubik-Semibold'; src: url('Rubik-Medium.ttf'); }
            b { font-size:20px; color:#373534; letter-spacing: 1.27px; line-height: 30px; font-family: 'Rubik-Semibold'; background:transparent;)
            }
            p { text-align:left; font-size:20px; color:#373534; letter-spacing: 1.27px; line-height: 30px; font-family: 'Rubik-Regular'; background:transparent;  }
         </style>
        </head>
        <body>
            <header>
                <meta name='viewport' content='width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0'>
                <p>This is the text for the HTML and we <b>BOLD</b> this part</p>
            </header>
        </body>
    </html>

Then I call loadHTMLString on my webView:

let url = URL(fileURLWithPath: path!)
wkWebView.loadHTMLString(htmlString, baseURL: url)

Not sure why it loads perfectly on the Simulator and on Android devices but the HTML string becomes problematic on real devices. Why can't the real device load the font from local storage?


Solution

  • What I missed in my origin implementation was the loadFileURL(_ URL, _ URL) method. This method should precede the calling of loadHTMLString, what worked for the for me was calling loadFileURL() in the awakedFromNib method in my custom view class.