Skip to content

Instantly share code, notes, and snippets.

@muizidn
Last active December 21, 2023 09:59
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save muizidn/5c314f96b9f536308eb20b79894b220c to your computer and use it in GitHub Desktop.
Save muizidn/5c314f96b9f536308eb20b79894b220c to your computer and use it in GitHub Desktop.
Using custom font in iOS without register to Info.plist
public class FontLoader {
private enum Error: Swift.Error {
case error(String)
}
/// Register fonts
///
/// - Parameter fonts: Font names
static func registerFonts(fonts: [String]) throws {
let bundle = Bundle(for: FontLoader.self)
let urls = fonts.compactMap({ bundle.url(forResource: $0, withExtension: "ttf") })
try urls.forEach { (url) in
let data = try Data.init(contentsOf: url)
guard let provider = CGDataProvider.init(data: data as CFData) else { throw Error.error("CGDataProvider nil") }
guard let font = CGFont.init(provider) else { throw Error.error("CGFont nil") }
var error: Unmanaged<CFError>?
guard CTFontManagerRegisterGraphicsFont(font, &error) else {
throw error!.takeUnretainedValue()
}
}
}
}
@ZUCheema
Copy link

ZUCheema commented Jun 2, 2023

Getting actual error. duplicateName or alreadyRegistered error is common. direct casting from cfError to NSError doesn't work, we first need to cast to Error.
let cfError = error?.takeRetainedValue() if let err = (cfError as? Error) as? NSError { if err.code == CTFontManagerError.alreadyRegistered.rawValue || err.code == CTFontManagerError.duplicatedName.rawValue { } }

@muizidn
Copy link
Author

muizidn commented Jun 2, 2023

Thanks. Why does that error happen? Do you install different font using similar name as system provided one?

@ZUCheema
Copy link

ZUCheema commented Jun 2, 2023 via email

@muizidn
Copy link
Author

muizidn commented Jun 2, 2023

I would suggest to filter those fonts before register them. Or you can handle that for your specific use case.

@ZUCheema
Copy link

ZUCheema commented Jun 2, 2023 via email

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment