Skip to content

Instantly share code, notes, and snippets.

@DreamingInBinary
Last active February 22, 2018 18:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DreamingInBinary/042f8690c6c757230d07e9bbead000a5 to your computer and use it in GitHub Desktop.
Save DreamingInBinary/042f8690c6c757230d07e9bbead000a5 to your computer and use it in GitHub Desktop.
Machine Learning Blog Post: Snip 1
// Once you get the NSData from the download task from where you hosted the file...
#pragma mark - Local Storage
// A 4 Step Process
// 1) Save off the NSData of the Core ML model to a temporary spot
// 2) Compile the model from that URL, whic gives us another temporary URL of where it's compiled at
// 3) Create a permanent URL by appending the temporary URL that was generated. This is what initlizes stuff
// 4) Save the permanent URL for later use
- (void)saveModelData:(NSData *)data {
// First, save the raw NSData since MLModel uses a URL for compilation.
NSURL *modelDataURL = [NSURL URLWithString:[NSString stringWithFormat:@"%@modelData.tmp", NSTemporaryDirectory()]];
NSError *writeError;
[data writeToFile:modelDataURL.path options:NSDataWritingAtomic error:&writeError];
if (writeError != nil) {
NSLog(@"Couldn't save data. Error: %@", writeError.localizedDescription);
return;
}
// Now compile the model itself, which results in a temporary URL where the model is at
NSError *compilationOrSaveError;
NSURL *compiledModelURL = [MLModel compileModelAtURL:modelDataURL error:&compilationOrSaveError];
if (compilationOrSaveError != nil) {
NSLog(@"Couldn't compile model data. Error: %@", compilationOrSaveError.localizedDescription);
return;
}
// Now save off the permanent URL so we can later access it in the app support directory
NSFileManager *fileManager = [NSFileManager defaultManager];
NSURL *appSupportDirectory = [fileManager URLForDirectory:NSApplicationSupportDirectory inDomain:NSUserDomainMask appropriateForURL:compiledModelURL create:YES error:&compilationOrSaveError];
if (compilationOrSaveError != nil) {
NSLog(@"Couldn't save compile model data permanent URL. Error: %@", compilationOrSaveError.localizedDescription);
return;
}
NSURL *permanentURL = [appSupportDirectory URLByAppendingPathComponent:compiledModelURL.lastPathComponent];
[self savePermanentFileURL:permanentURL];
// Replace it or save it
if ([fileManager fileExistsAtPath:permanentURL.absoluteString]) {
[fileManager replaceItemAtURL:permanentURL withItemAtURL:compiledModelURL backupItemName:nil options:NSFileManagerItemReplacementWithoutDeletingBackupItem resultingItemURL:nil error:nil];
} else {
[fileManager copyItemAtURL:compiledModelURL toURL:permanentURL error:nil];
}
NSLog(@"Compilation successful and the URL was saved.");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment