How can I use a bundled font in a WebView with React Native on iOS?

Viewed 99

In my React Native app I have some information I have stored in a local bundled folder and that I display in a WebView. I want this to work consistently with the rest of the app, so I need to use the same fonts as I use through the rest of the app.

I have this working correctly in Android, but in iOS I can't make it show the fonts at all.

My Webview Screen looks like this:

export class InstructionView extends React.Component<InstructionScreenRouteProp> {

render(): JSX.Element {
 
  let filePath = (Platform.OS === 'android') ? 'file:///android_asset/' : './html/';
  filePath +=  this.props.route.params.file.file + '.html';

  return (
    <WebView
        originWhitelist={['*']}
        source={{ baseUrl:'',
          uri: filePath }}
    startInLoadingState = { true }
    />
  );
}
}

My bundle is structured like this:

/html/instructions.html
/html/styles.css 
/Resources/MyFont-Regular.ttf

And then the css file font declaration looks like this:

@font-face {
  font-family: 'myFont';
  src: local('MyFont-Regular'), url('MyFont-Regular.ttf'), format('truetype');
}

h1 {
  font-family: 'myFont';
  font-size: 2em;
  background-color: #622a53;
  color: #fffcdc;
  padding: 0.5em;
}

I don't think the font would currently work on Android because I've been trying to figure out the iOS version of it, but I have had it working on Android previously by using the explicit path, much like the file path in the render function.

The html is loaded and rendered correctly, the other styles from the stylesheet are applied, it is only the font that is missing.

I have seen various suggestions around this in different places, but none of them satisfy me because they seem to rely on placing the font in the same folder as the html content or even encoding it in the stylesheet, which seems redundant when I already have it included in the app bundle elsewhere. I have tried a lot of different paths in the font-face url and none of them seemed to work, but because of the way React silently caches assets it can be hard to know if I actually saw all the things I tried.

What do I need to do to be able to use an existing font in a WebView on an iOS device?

0 Answers
Related