Search code examples
iosxcodefontsfont-facewkwebview

Use custom local stored font with WKWebView


I'm using the newest version of Xcode and Swift.

I imported a font called Blastimo.ttf to my Xcode project by drag and drop it to the files list on the left side of Xcode.

I enabled Target Membership.

I added Fonts provided by application > Item 0 : Blastimo.ttf to Info.plist.

Now I can use this font for e.g. labels. This is working.

I also want to use this font in my WKWebView like this:

let html = """
        <html>
        <body>
        <head>
        <style>
        @font-face
        {
            font-family: 'Blastimo';
            src: local('Blastimo'), url('Blastimo.ttf') format('truetype');
        }
        </style>
        </head>
        <h1 style="font-family:'Blastimo';font-size:50px;">This is my test!</h1>
        </body>
        </html>
        """
        webView.loadHTMLString(html, baseURL: nil)

But this is not working, the standard font gets loaded.

The html code itself is working with the font Blastimo.ttf. I tested it on my web server.

But it's not working in WKWebView. What am I doing wrong?


Solution

  • The solution was to replace:

    webView.loadHTMLString(html, baseURL: nil)

    by

    webView.loadHTMLString(html, baseURL: Bundle.main.resourceURL)