如何将字体动态下载并安装到iOS应用 [英] How can I download and install fonts dynamically to iOS app

查看:349
本文介绍了如何将字体动态下载并安装到iOS应用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

客户端希望通过使用API​​调用下载字体来将字体动态添加到iOS应用.

A client would like to dynamically add fonts to an iOS app by downloading them with an API call.

这可能吗?我挖掘的所有资源都显示了如何将.ttf文件手动拖动到Xcode并将其添加到plist中.可以下载字体并在客户端上以编程方式使用它吗?

Is this possible? All the resources I've dredged up show how to manually drag the .ttf file to Xcode and add it to the plist. Is it possible to download a font and use it on the fly client side, programmatically?

谢谢.

推荐答案

好的,这就是我的操作方法.首先,在需要的地方执行此操作:

Okay, so here is how I did it. First where needed do this:

#import <CoreText/CoreText.h>

然后进行您的NSURLSession调用.我的客户将字体上传到了亚马逊的S3.因此,在需要的地方这样做:

Then make your NSURLSession call. My client uploaded a font to Amazon's S3. So do this where needed:

// 1
NSString *dataUrl = @"http://client.com.s3.amazonaws.com/font/your_font_name.ttf";
NSURL *url = [NSURL URLWithString:dataUrl];

// 2
NSURLSessionDataTask *downloadTask = [[NSURLSession sharedSession] dataTaskWithURL:url completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
    // 4: Handle response here
    if (error == nil) {
        NSLog(@"no error!");
        if (data != nil) {
            NSLog(@"There is data!");
            [self loadFont:data];
        }
    } else {
        NSLog(@"%@", error.localizedDescription);
    }
}];

// 3
[downloadTask resume];

我的loadFont数据在这里:

My loadFont data is here:

- (void)loadFont:(NSData *)data
{
    NSData *inData = data;
    CFErrorRef error;
    CGDataProviderRef provider = CGDataProviderCreateWithCFData((CFDataRef)data);
    CGFontRef font = CGFontCreateWithDataProvider(provider);
    if(!CTFontManagerRegisterGraphicsFont(font, &error)){
        CFStringRef errorDescription = CFErrorCopyDescription(error);
        NSLog(@"Failed to load font: %@", errorDescription);
        CFRelease(errorDescription);
    }
    CFRelease(font);
    CFRelease(provider);

    [self fontTest];
}

然后,最后的fontTest只是要确保字体确实存在,就我而言,就是这样!而且,它会在应用程序在需要的地方运行时显示.

Then that fontTest at the end is just to make sure the font is actually there, and in my case, it was! And also, it showed up when the app ran where needed.

- (void)fontTest
{
    NSArray *fontFamilies = [UIFont familyNames];
    for (int i = 0; i < [fontFamilies count]; i++) {
        NSString *fontFamily = [fontFamilies objectAtIndex:i];
        NSArray *fontNames = [UIFont fontNamesForFamilyName:[fontFamilies objectAtIndex:i]];
        NSLog (@"%@: %@", fontFamily, fontNames);
    }
}

这篇关于如何将字体动态下载并安装到iOS应用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆