Skip to content

Instantly share code, notes, and snippets.

@AllanChen
Created June 26, 2018 02:41
Show Gist options
  • Save AllanChen/663933dac8e37bf54b0243489074964f to your computer and use it in GitHub Desktop.
Save AllanChen/663933dac8e37bf54b0243489074964f to your computer and use it in GitHub Desktop.
write data to documents folder
+ (void)writeDataToFile:(NSString *)fileName wirteData:(NSData*)data{
NSString *filePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject] stringByAppendingPathComponent:fileName];
BOOL fileExists = [self fileExists:fileName];
if(fileExists){
NSFileHandle *fileHandle = [NSFileHandle fileHandleForWritingAtPath:filePath];
[fileHandle seekToEndOfFile];
[fileHandle writeData:data];
[fileHandle closeFile];
}
else{
NSString *filePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject] stringByAppendingPathComponent:fileName];
BOOL writeSuccess = [data writeToFile:filePath atomically:YES];
}
}
+ (BOOL)fileExists:(NSString *)fileName{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *path = [paths objectAtIndex:0];
NSString *filePath = [path stringByAppendingPathComponent:fileName];
NSFileManager *fileManager = [NSFileManager defaultManager];
BOOL result = [fileManager fileExistsAtPath:filePath];
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment