Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use Custom Local Font in WKWebView

I am attempting to use a local font (one installed with the application) in the CSS of some dynamic HTML presented within a WKWebView. I have read numerous Stack Overflow posts and this webpage. To review what I have done:

The font (in this case ImpactLTStd.otf) is part of the iOS application.

It is entered as part of the application plist in the Fonts provided by application section.

Per the referenced webpage, I can confirm that the ImpactLTStd.otf is listed in the Copy Bundle Resources section of Build Phases and leads me to believe that the ImpactLTStd.otf is being bundled with the application correctly.

The font is listed in the CSS as:

<style> @font-face {font-family: 'Impact LT Std'; src: local('Impact LT Std'), local('ImpactLTStd'), url('ImpactLTStd.otf'); format('opentype'); } </style>

I reference the font two different ways in this fashion (one by font family and one by font name in order see which one worked and neither did):

<style>  .box_root {    overflow: auto;    background-color: #000000;    padding-top: 1.5em;    padding-bottom: 1.5em;    padding-left: 1.5em;    max-width: 1440px;    max-height: 640px;    display: table;  }  .box_title {    color: #ffd300;    line-height: 1em;    font-size: 85pt;    font-size: 6vw;    font-family: 'Impact LT Std';    text-transform: uppercase;  }  .box_description {    padding-top: .5em;    line-height: 1em;    color: #ffffff;    font-size: 65pt;    font-size: 4vw;    font-weight: bold;    font-family: 'ImpactLTStd';  } 

I load the HTML into the WKWebView using loadHTMLString:

webView.loadHTMLString(getHtml(), baseURL: nil)

However, the HTML text that is displayed in the WKWebView using the CSS tags does not use the Impact font but instead some default font that looks like Times New Roman.

Anyone have an idea what step I did incorrectly?

like image 684
Perry Hoekstra Avatar asked Nov 07 '17 20:11

Perry Hoekstra


1 Answers

You did not provide a base URL when loading the HTML string, this will cause the font failing to load. Try accessing your bundle's main resource path, like this:

if let resourcePath = Bundle.main.resourcePath {
    let url = URL.init(fileURLWithPath: resourcePath)
    webView.loadHTMLString(getHtml(), baseURL: url)
}
like image 128
Tamás Sengel Avatar answered Nov 14 '22 21:11

Tamás Sengel