Monday, April 22, 2013

NSFileManager createFileAtPath example ios


createFileAtPath :contents:attributes:

Creates a file with the specified content and attributes at the given location.
- (BOOL)createFileAtPath:(NSString *)path contents:(NSData*)contents attributes:(NSDictionary *)attributes
Parameters
path
The path for the new file.
contents
A data object containing the contents of the new file.
attributes
A dictionary containing the attributes to associate with the new file. You can use these attributes to set the owner and group numbers, file permissions, and modification date. For a list of keys, see “File Attribute Keys.” If you specify nilfor attributes, the file is created with a set of default attributes. 
Return Value
YES if the operation was successful or if the item already exists, otherwise NO.
Discussion of [NSFileManager createFileAtPath: contents: attributes:]
If you specify nil for the attributes parameter, this method uses a default set of values for the owner, group, and permissions of any newly created directories in the path. Similarly, if you omit a specific attribute, the default value is used. The default values for newly created files are as follows:
[NSFileManager createFileAtPath: contents: attributes:]

  • Permissions are set according to the umask of the current process. For more information, see umask.
  • The owner ID is set to the effective user ID of the process.
  • The group ID is set to that of the parent directory.
If a file already exists at path, this method overwrites the contents of that file if the current process has the appropriate privileges to do so.
Example of [NSFileManager createFileAtPath: contents: attributes:]

NSData* tempData = [NSData dataWithContentsOfURL:tempSoundFile]; // reads just fine

NSError* error;
NSFileManager* fileMgr = [NSFileManager defaultManager];
NSString* docDir = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
NSString* uniqueFileName = [[NSString stringWithFormat:@"%@-%@", description.text, [NSDate date]] MD5];
NSString* newAudioFile = [NSString stringWithFormat:@"%@/%@.caf", docDir, uniqueFileName];

if (LOG) { NSLog(@"Copying %@ to %@", tempSoundFile.path, newAudioFile); }

// Have tried either or both as well as moveItemAtPath with the same result
[fileMgr createFileAtPath:newAudioFile contents:tempData attributes:nil];
//[fileMgr copyItemAtPath:tempSoundFile.path toPath:newAudioFile error:&error];

NSData* audioAfter = [NSData [NSData dataWithContentsOfFile:newAudioFile];