Last active
June 11, 2024 07:19
-
-
Save mackoj/2a7e62fdae87b692e81601114cc514d0 to your computer and use it in GitHub Desktop.
This simplifies the process of loading custom fonts that are resources in an iOS Apple SPM Package (Swift Package Manager).
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 typealias FontNameExt = (name: String, ext: String) | |
public func autoRegisteringFont(_ fontNames: [FontNameExt], _ spmBundleName : String) throws { | |
guard let spmBundle = Bundle(bundleName: spmBundleName) else { | |
throw("Fail to find bundle(\(spmBundleName).bundle) in your app bundle.") | |
} | |
try fontURLs(for: fontNames, in: spmBundle).forEach { try registerFont(from: $0) } | |
} | |
extension Bundle { | |
convenience init?(bundleName: String) { | |
self.init(path: "\(Bundle.main.bundlePath)/\(bundleName).bundle") | |
} | |
} | |
func fontURLs(for fontNames: [FontNameExt], in bundle: Bundle) -> [URL] { | |
return fontNames.compactMap { police in | |
bundle.url(forResource: police.name, withExtension: police.ext) | |
} | |
} | |
func registerFont(from url: URL) throws { | |
guard let fontDataProvider = CGDataProvider(url: url as CFURL) else { | |
throw("Could not get reference to font data provider.") | |
} | |
guard let font = CGFont(fontDataProvider) else { | |
throw("Could not get font from CoreGraphics.") | |
} | |
var error: Unmanaged<CFError>? | |
guard CTFontManagerRegisterGraphicsFont(font, &error) else { | |
throw("Error registering font: \(dump(error)!).") | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Yes 126 SPM modules that means 126 library targets all in the same
Package.swift