LiveUI / Awesome

FontAwesome 6 Swift & SwiftUI implementation for iOS, tvOS & macOS
MIT License
97 stars 27 forks source link

Awesome.bundle not being loaded in Mac app using cocoapods #38

Open aaronrogers opened 5 years ago

aaronrogers commented 5 years ago

In iOS everything works great with using cocoapods, but when using Awesome in a mac app I get the exception

Font FontAwesome5FreeRegular not loaded properly. Did you forget to call AwesomePro.loadFonts(from:)?

Is there a step that I'm missing?

In Fonts.swift the following code returns nil.

fontBundle.url(forResource: type.file, withExtension: "ttf", subdirectory: isCocoapods ? "Awesome.bundle" : nil)
aaronrogers commented 5 years ago

Oddly enough, it looks like with macOS there's yet another Awesome.bundle in fontBundle. Changing the load code to the following appears to work on iOS and macOS.

    static func load(type: AwesomeFont, from bundle: Bundle? = nil) {
        guard !Font.fontNames(forFamilyName: type.description).contains(type.memberName) else {
            return
        }

        let fontBundle: Bundle!
        if bundle == nil {
            fontBundle = Bundle(for: Fonts.self)
        } else {
            fontBundle = bundle
        }

        var awesomeBundle = fontBundle!
        while true {
            guard
                let url = awesomeBundle.url(forResource: "Awesome", withExtension: "bundle"),
                let subBundle = Bundle(url: url)
                else {
                    break
            }
            awesomeBundle = subBundle
        }

        let fontURL = awesomeBundle.url(forResource: type.file, withExtension: "ttf")

        guard let url = fontURL else {
            return
        }

        let data = try! Data(contentsOf: url as URL)
        let provider = CGDataProvider(data: data as CFData)
        let font = CGFont(provider!)

        var error: Unmanaged<CFError>?

        if CTFontManagerRegisterGraphicsFont(font!, &error) == false {
            let errorDescription: CFString = CFErrorCopyDescription(error!.takeUnretainedValue())
            let nsError = error!.takeUnretainedValue() as AnyObject as! NSError
            NSException(name: NSExceptionName.internalInconsistencyException, reason: errorDescription as String, userInfo: [NSUnderlyingErrorKey: nsError]).raise()
        }

    }