Open Montoya opened 9 years ago
FYI, here's my complete File.write method:
- (void) writeFile:(NSString*)filePath withData: (JSValue*) data andType: (NSString*) type
{
if([_acceptedTypes containsObject:type]){
// first we might need to create the directories
if([filePath rangeOfString:@"/"].location != NSNotFound) {
// create path
NSString* directoryPath = [filePath stringByDeletingLastPathComponent];
NSError* error;
if(![[NSFileManager defaultManager] createDirectoryAtPath:directoryPath withIntermediateDirectories:YES attributes:nil error:&error])
NSLog(@"failed to create directory at %@, error: %@", directoryPath, error);
}
if([type isEqualToString:@"string"]) {
NSString* valToWrite = [data toString];
[valToWrite writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:NULL];
} else if([type isEqualToString:@"json"]) {
NSDictionary* dictData = [data toDictionary];
NSString* valToWrite = [dictData JSONString];
[valToWrite writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:NULL];
} else {
NSString* base64Data = [data toString];
BOOL success = NO;
success = [[NSFileManager defaultManager] createFileAtPath:filePath contents:[NSData dataFromBase64String:base64Data] attributes:nil];
if (!success) {
NSLog(@"failed to create file at %@", filePath);
}
}
}
}
You'll notice I also added a check to ensure directories are created if needed.
It looks like this hasn't been implemented yet so I did the following:
NSString* base64Data = [data toString]; BOOL success = NO; success = [[NSFileManager defaultManager] createFileAtPath:filePath contents:[NSData dataFromBase64String:base64Data] attributes:nil]; if (!success) { NSLog(@"failed to create file at %@", filePath); } else { NSLog(@"file should have successfully been written at %@", filePath); }
I've tried it with GIFs, JPGs and PNGs and it works.
Also for the record, if you have a dataURI you can use substr to get everything after the ',' and that's the base64 representation of the image. You can also convert an arraybuffer to base64 with javascript's built in atob method. So base64 made sense for this in my case.