Last active
September 21, 2024 03:34
-
-
Save muizidn/5c314f96b9f536308eb20b79894b220c to your computer and use it in GitHub Desktop.
Using custom font in iOS without register to Info.plist
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() | |
} | |
} | |
} | |
} |
Thanks. Why does that error happen? Do you install different font using similar name as system provided one?
Yes. I'm loading a many fonts from server, synching them locally and
loading in table view cell from file url. Table cell registers font which
caused the issue.
I would suggest to filter those fonts before register them. Or you can handle that for your specific use case.
The error is alreadyRegistered, not duplicate.
As table view reloads cells, it reloads font from url and registers it to
output ui font. Is there an other way to check already registered font?
Thanks.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Getting actual error. duplicateName or alreadyRegistered error is common. direct casting from
cfError
toNSError
doesn't work, we first need to cast toError
.let cfError = error?.takeRetainedValue() if let err = (cfError as? Error) as? NSError { if err.code == CTFontManagerError.alreadyRegistered.rawValue || err.code == CTFontManagerError.duplicatedName.rawValue { } }