Saturday, June 1, 2013

NSData writeToFile example in Objective C (iOS).

NSData writeToFile

Writes the bytes in the receiver to the file specified by a given path.

- (BOOL)writeToFile:(NSString *)path options:(NSDataWritingOptions)mask error:(NSError **)errorPtr

Parameters of [NSData writeToFile]
The location to which to write the receiver's bytes.
A mask that specifies options for writing the data. Constant components are described in “NSDataWritingOptions”.
If there is an error writing out the data, upon return contains an NSError object that describes the problem.

Return Value of [NSData writeToFile]
YES if the operation succeeds, otherwise NO.

NSData writeToFile example.
if (data) {   
     NSString *content = [[NSString alloc]  initWithBytes:[data bytes]
                                                      length:[data length] encoding: NSUTF8StringEncoding];

    NSLog(@"%@", content); // verifies data was downloaded correctly

    NSError* error;
    [data writeToFile:storePath options:NSDataWritingAtomic error:&error];

    if(error != nil)
        NSLog(@"write error %@", error);

Example of [NSData writeToFile].
NSError *error = nil;
[data writeToFile:path options:NSDataWritingAtomic error:&error];
NSLog(@"Write returned error: %@", [error localizedDescription]);

NSData writeToFile example.
-(void)banner:(NSString *)path{
   NSData * imageData = [[NSData alloc] initWithContentsOfURL: [NSURL URLWithString: path]];
   NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);         NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"banner.png"];      
   NSError *writeError = nil;
   [imageData writeToFile:filePath options:NSDataWritingAtomic error:&writeError];

   if (writeError) {
      NSLog(@"Error writing file: %@", writeError);

End of NSData writeToFile example article.