Update: This is now possible using WKURLSchemeHandler
.
@interface MySchemeHandler : NSObject <WKURLSchemeHandler>
@end
@implementation MySchemeHandler
- (void)webView:(nonnull WKWebView *)webView startURLSchemeTask:(nonnull id<WKURLSchemeTask>)urlSchemeTask
{
NSURL *url = urlSchemeTask.request.URL;
NSString *mimeType = [NSString stringWithFormat:@"text/%@", url.pathExtension]; //or whatever you need
NSURLResponse *response = [[NSURLResponse alloc] initWithURL:url MIMEType:mimeType expectedContentLength:-1 textEncodingName:nil];
[urlSchemeTask didReceiveResponse:response];
NSData *data = [self getResponseData];
[urlSchemeTask didReceiveData:data];
[urlSchemeTask didFinish];
}
@end
And when configuring your WKWebView
instance:
WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
MySchemeHandler *handler = [[MySchemeHandler alloc] init];
[config setURLSchemeHandler:handler forURLScheme:@"myScheme"];
//now pass the config to your WKWebView
------Old answer----------
My guess is that the WKWebView
can no longer access fonts specific to the application because it's now in a separate process (XPC).
I got around this by adding the font with @font-face
declarations in CSS. See here for details on MDN about how to do this.
Example:
@font-face
{
font-family: "MyFontFace";
src:url('url-to-font.ttf');
}
//And if you have a font with files with different variants, add this:
@font-face
{
font-family: "MyFontFace";
src:url('url-to-italic-variant.ttf');
font-style:italic;
}
But this is going to reference a local file, which the WKWebView
can't do (I assume you've already discovered this because you're loading an HTML string instead of the local file). As per a comment on this question, I was able to use GCDWebServer to get my local HTML file working. In your app delegate, after adding the relevant files to your project as per the GCDWebServer's wiki on GitHub:
GCDWebServer *server = [[[GCDWebServer alloc]init]autorelease];
NSString *bundlePath = [[NSBundle mainBundle] bundlePath];
[server addGETHandlerForBasePath:@"/"
directoryPath:bundlePath indexFilename:nil
cacheAge:0 allowRangeRequests:YES];
[server startWithPort:8080 bonjourName:nil];
Now you can reference an HTML file named test.html
in your bundle like this:
NSString *path = @"http://localhost:8080/test.html";
NSURL *url = [NSURL URLWithString:path];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[myWebView loadRequest:request];
Put the aforementioned @font-face
declaration in a style
element in your HTML file (or in your HTML string if you really just need to load a string) and you should be good to go.