好的,这就是我的做法。首先在需要的地方执行此操作:
#import <CoreText/CoreText.h>
然后进行 NSURLSession 调用。我的客户将字体上传到 Amazon S3。因此,在需要的地方执行此操作:
// 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 数据在这里:
- (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 只是为了确保字体确实存在,就我而言,它确实存在!而且,当应用程序在需要的地方运行时它就会出现。
- (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);
}
}