Created
September 29, 2020 01:15
-
-
Save mattadatta/fe5d39ccceb0c5f35a6f2261c08b533b to your computer and use it in GitHub Desktop.
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 CoreText | |
struct FontUtils { | |
enum Error: Swift.Error { | |
case dataProviderConstructionFailed | |
case cgFontConstructionFailed | |
case postScriptNameUnavailable | |
} | |
static func loadFont(at url: URL) throws -> String { | |
let fontData = try Data(contentsOf: url) | |
guard let dataProvider = CGDataProvider(data: fontData as CFData) else { | |
throw Error.dataProviderConstructionFailed | |
} | |
guard let font = CGFont(dataProvider) else { | |
throw Error.cgFontConstructionFailed | |
} | |
var unmanagedError: Unmanaged<CFError>? | |
CTFontManagerRegisterGraphicsFont(font, &unmanagedError) | |
if let unmanagedError = unmanagedError { | |
throw unmanagedError.takeRetainedValue() | |
} | |
guard let fontName = font.postScriptName as String? else { | |
throw Error.postScriptNameUnavailable | |
} | |
return fontName | |
} | |
private init() { } | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment