Skip to content

Instantly share code, notes, and snippets.

@mattadatta
Created September 29, 2020 01:15
Show Gist options
  • Save mattadatta/fe5d39ccceb0c5f35a6f2261c08b533b to your computer and use it in GitHub Desktop.
Save mattadatta/fe5d39ccceb0c5f35a6f2261c08b533b to your computer and use it in GitHub Desktop.
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