Unable to register font programmatically in Swift 3

Viewed 3900

I am trying to register font programmatically in swift 3. Here is the piece of code i am using to install fonts. The font i am trying to install is Oswald

func installFonts(_ fonts: [String]){
    for i in 0 ..< fonts.count{
        let font = fonts[i].components(separatedBy: ".")
        let fontPath = Bundle.main.url(forResource: font[0], withExtension: font[1])!
        var error: Unmanaged<CFError>?
        if let dataProvider = CGDataProvider(url: fontPath as CFURL) {
            let font = CGFont(dataProvider)
            if (!CTFontManagerRegisterGraphicsFont(font, &error)) {
                print(error.debugDescription)
            }
        }
    }
}

None of the fonts get installed and error description states:

Optional(Swift.Unmanaged<__ObjC.CFError>(_value: Error Domain=com.apple.CoreText.CTFontManagerErrorDomain Code=105 \"Could not register the CGFont \'<CGFont (0x6100000d9f30): Oswald-Bold>\'\" UserInfo={NSDescription=Could not register the CGFont \'<CGFont (0x6100000d9f30): Oswald-Bold>\', CTFailedCGFont=<CGFont (0x6100000d9f30): Oswald-Bold>}))

4 Answers

I had the same error, and couldn't work out why the font was still appearing correctly in the app despite an error being reported.

Turns out iOS already includes the font I was trying to load! I assume the error was caused because there already existed a font of the same name.

Related