-
-
Save mrugeshtank/d0a916396549ba54a4deaad59c6a3afe to your computer and use it in GitHub Desktop.
This will allow you to load font that are resources in a SPM module
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
import Foundation | |
import UIKit | |
public struct Resource { | |
var name: String | |
var fileExtension: String | |
var url: URL? { | |
Bundle.module.url(forResource: name, withExtension: fileExtension) | |
} | |
} | |
public enum FontRegisteringError: Error { | |
case noFontFound | |
case noFontDataProvider | |
case noFontFromFontDataProvider | |
case errorInRegisteringFont(font: CGFont, error: CFError) | |
} | |
public func autoRegisteringFont(_ fonts: [Resource]) throws { | |
try fonts.forEach({ try registerFont(from: $0.url)}) | |
} | |
func registerFont(from url: URL?) throws { | |
guard let url = url else { | |
throw FontRegisteringError.noFontFound | |
} | |
guard let fontDataProvider = CGDataProvider(url: url as CFURL) else { | |
throw FontRegisteringError.noFontDataProvider | |
} | |
guard let font = CGFont(fontDataProvider) else { | |
throw FontRegisteringError.noFontFromFontDataProvider | |
} | |
var error: Unmanaged<CFError>? | |
guard CTFontManagerRegisterGraphicsFont(font, &error) else { | |
throw FontRegisteringError.errorInRegisteringFont(font: font, error: error!.takeRetainedValue()) | |
} | |
} | |
//Usage: | |
public static func registerFontsForEpisode() { | |
let fontToRegister = [ | |
Resource(name: "AbrilFatface-Regular", fileExtension: "ttf"), | |
Resource(name: "DancingScript-Regular", fileExtension: "ttf"), | |
Resource(name: "RobotoSlab-Regular", fileExtension: "ttf"), | |
] | |
do { | |
try autoRegisteringFont(fontToRegister) | |
} | |
catch FontRegisteringError.noFontFound { | |
print("No found found in Bundle") | |
} | |
catch FontRegisteringError.noFontDataProvider { | |
print("No font data provider") | |
} | |
catch FontRegisteringError.noFontFromFontDataProvider { | |
print("Could not create font from font data provider") | |
} | |
catch FontRegisteringError.errorInRegisteringFont(let font, let error) { | |
print("Got error while registering font for: \(font) -> \(error)") | |
} | |
catch { | |
dump(error) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment