Can I embed a custom font in a bundle and access it from an ios framework? Can I embed a custom font in a bundle and access it from an ios framework? ios ios

Can I embed a custom font in a bundle and access it from an ios framework?

Swift 3:

Firstly, don't access framework bundle from main with appending path components... Instantiate it from its identifier. You can get font URLs like this:

static func fontsURLs() -> [URL] {    let bundle = Bundle(identifier: "")!    let fileNames = ["Roboto-Bold", "Roboto-Italic", "Roboto-Regular"]    return{ bundle.url(forResource: $0, withExtension: "ttf")! })}

And I find it nice to have UIFont extension for registering fonts:

public extension UIFont {    public static func register(from url: URL) throws {        guard let fontDataProvider = CGDataProvider(url: url as CFURL) else {            throw SVError.internal("Could not create font data provider for \(url).")        }        let font = CGFont(fontDataProvider)        var error: Unmanaged<CFError>?        guard CTFontManagerRegisterGraphicsFont(font, &error) else {            throw error!.takeUnretainedValue()        }    }}

Now enjoy the registration:

do {    try fontsURLs().forEach({ try UIFont.register(from: $0) })} catch {    print(error)}

This is a new method that lets you load fonts dynamically without putting them in your Info.plist:

Here is way I implemented it for my fmk based on the solution provided by "David M."This solution doesn't require to add the reference to the font in the plist.

1) Class that load the font

- (void) loadMyCustomFont{    NSString *fontPath = [[NSBundle frameworkBundle] pathForResource:@"MyFontFileNameWithoutExtension" ofType:@"ttf"];    NSData *inData = [NSData dataWithContentsOfFile:fontPath];    CFErrorRef error;    CGDataProviderRef provider = CGDataProviderCreateWithCFData((__bridge CFDataRef)inData);    CGFontRef font = CGFontCreateWithDataProvider(provider);    if (! CTFontManagerRegisterGraphicsFont(font, &error)) {        CFStringRef errorDescription = CFErrorCopyDescription(error);        NSLog(@"Failed to load font: %@", errorDescription);        CFRelease(errorDescription);    }    CFRelease(font);    CFRelease(provider);}

2) Category on NSBundle to get access to my bundle

+ (NSBundle *)frameworkBundle {    static NSBundle* frameworkBundle = nil;    static dispatch_once_t predicate;    dispatch_once(&predicate, ^{        NSString* mainBundlePath = [[NSBundle mainBundle] resourcePath];        NSString* frameworkBundlePath = [mainBundlePath stringByAppendingPathComponent:@"MyBundleName.bundle"];        frameworkBundle = [NSBundle bundleWithPath:frameworkBundlePath];    });    return frameworkBundle;}

Note: require to integrate CoreText in your project