Created
December 2, 2016 20:36
-
-
Save leogdion/01f37fc9a4ef1e5c4b91ccf9c819db88 to your computer and use it in GitHub Desktop.
How to register fonts in a Bundle without having to edit the plist
This file contains hidden or 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
// | |
// Bundle.swift | |
// timerany | |
// | |
// Created by Leo Dion on 12/2/16. | |
// Copyright © 2016 BrightDigit. All rights reserved. | |
// | |
import Foundation | |
import CoreGraphics | |
import UIKit | |
public struct InvalidFontResource : Error { | |
public let bundle : Bundle | |
public let url : URL | |
} | |
public struct ErrorCollection : Error { | |
public let errors: [Error] | |
} | |
public extension Bundle { | |
public func registerFontResources(withExtensions extensions: [String]? = nil, inSubdirectory subdirectory: String? = nil) throws { | |
let extensions = extensions ?? ["ttf", "otf"] | |
let urls = extensions.flatMap({self.urls(forResourcesWithExtension: $0, subdirectory: subdirectory)}).flatMap({$0}) | |
let errors = urls.flatMap{ | |
(url) -> Error? in | |
let data: Data | |
let error: UnsafeMutablePointer<Unmanaged<CFError>?>? = nil | |
do { | |
data = try Data(contentsOf: url) | |
} catch let error { | |
return error | |
} | |
guard let provider = CGDataProvider(data: data as CFData) else { | |
return InvalidFontResource(bundle: self, url : url) | |
} | |
let fontRef = CGFont(provider) | |
if (!CTFontManagerRegisterGraphicsFont(fontRef, error)) { | |
if let unmanagedError = error?.pointee { | |
return unmanagedError.takeRetainedValue() | |
} else { | |
return NSError() | |
} | |
} else { | |
return nil | |
} | |
} | |
if errors.count > 0 { | |
throw ErrorCollection(errors: errors) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment