How to download and install fonts dynamically in an iOS application

The client would like to dynamically add fonts to the iOS application, loading them using an API call.

Is it possible? All the resources I extracted show how to manually drag and drop the .ttf file into Xcode and add it to plist. Can I download a font and use it on the client side on the fly, programmatically?

Thanks.

+5
source share
1 answer

Ok, this is how I did it. First, where necessary, follow these steps:

#import <CoreText/CoreText.h> 

Then make your NSURLSession call. My client downloaded the font on Amazon S3. So do this if necessary:

 // 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]; 

My data 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]; } 

Then this fontTest at the end is just to make sure that the font is actually there, and in my case it was! And also, this manifested itself when the application was launched where necessary.

 - (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); } } 
+9
source

Source: https://habr.com/ru/post/1246311/


All Articles