iOS - 下载动态字体

时间:2014-12-06 06:38:57

标签: ios swift fonts nsdata writetofile

我正在尝试动态下载我的应用的字体,因为我经常想要动态添加新的字体,并且不想每次都重新提交我的应用。

我已经按照其他一些指南尝试从URL下载字体文件,将其保存到应用程序的文档目录,然后使用 CGFontCreateWithDataProvider& CTFontManagerRegisterGraphicsFont

然而,该应用程序仍然使'writeToFile'函数失败并吐出这一行:

println("Failed to save font: \(fontFile)")

我已经确认'fontUrl'有效(从调试器复制并粘贴到我的桌面浏览器中)。

此外,'fontPath'的值最终出现在调试器中,它看起来对我来说是正确的:

fontPath = "/Users/James/Library/Developer/CoreSimulator/Devices/E153E1F4-E3FD-4BCE-A40F-433EADF14591/data/Containers/Data/Application/969A248C-A7B3-4768-86E4-68A6C4E20ECF/Documents/Fonts/american_typewriter_medium_bt.ttf"

代码:

// Download and save font file
        let nsDocumentDirectory = NSSearchPathDirectory.DocumentDirectory
        let nsUserDomainMask = NSSearchPathDomainMask.UserDomainMask
        if let paths = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true) {
            if paths.count > 0 {
                if let documentsDirectory = paths[0] as? String {
                    let fontPath = documentsDirectory.stringByAppendingPathComponent("Fonts/"+fontFile) as String
                    let fontUrl = NSURL(string: ApiUrlString + "fonts/" + fontFile)
                    if let fontData = NSData(contentsOfURL: fontUrl!)
                    {
                        if(!fontData.writeToFile(fontPath, atomically: true))
                        {
                            println("Failed to save font: \(fontFile)")
                            return
                        }
                    }
                    else
                    {
                        println("Failed to download font from URL: \(fontUrl)")
                        return
                    }

                    // Load Font
                    let data: NSData? = NSFileManager.defaultManager().contentsAtPath(fontPath)
                    if (data == nil)
                    {
                        println("Failed to load saved font: \(fontFile)")
                        return
                    }

                    var error: Unmanaged<CFError>?
                    let provider: CGDataProviderRef = CGDataProviderCreateWithCFData(data)
                    let font: CGFontRef = CGFontCreateWithDataProvider(provider)
                    if (!CTFontManagerRegisterGraphicsFont(font, &error))
                    {
                        println("Failed to register font, error: \(error)")
                        return
                    }

                    println("Successfully saved and registered font: \(fontFile)")
                }
            }
        }
        else
        {
            println("Failed to load documents directory: \(fontFile)")
        }

1 个答案:

答案 0 :(得分:0)

我不确定这是否会对你有所帮助,但可能会有所帮助。网站iOS Font List提到使用可下载字体。也许示例代码可以引导您朝着正确的方向发展。

- (void)asynchronouslySetFontName:(NSString *)fontName toTextView:(UITextView *)textView {
    CGFloat size = 24.0f;
    UIFont *font = [UIFont fontWithName:fontName size:size];

    if (font && ([font.fontName compare:fontName] == NSOrderedSame || [font.familyName compare:fontName] == NSOrderedSame)) {
        textView.font = font;
        return;
    }

    NSMutableDictionary *attrs = [NSMutableDictionary dictionaryWithObject:fontName forKey:kCTFontNameAttribute];
    CTFontDescriptorRef desc = CTFontDescriptorCreateWithAttributes((__bridge CFDictionaryRef)attrs);

    NSMutableArray *descs = [NSMutableArray array];
    [descs addObject:(__bridge id)desc];
    CFRelease(desc);

    __weak UITextView *weakTextView = textView;

    CTFontDescriptorMatchFontDescriptorsWithProgressHandler((__bridge CFArrayRef)descs, NULL,  ^(CTFontDescriptorMatchingState state, CFDictionaryRef progressParameter) {
        if (state == kCTFontDescriptorMatchingDidFinish) {
            dispatch_async(dispatch_get_main_queue(), ^{
                weakTextView.font = [UIFont fontWithName:fontName size:size];
            });
        }

        return YES;
    });
}