Sunday, June 16, 2013

NSFileWrapper initWithURL example in Objective C (iOS).


NSFileWrapper initWithURL

Initializes a file wrapper instance whose kind is determined by the type of file-system node located by the URL.

- (id)initWithURL:(NSURL *)url options:(NSFileWrapperReadingOptions)options error:(NSError **)outError

Parameters of [NSFileWrapper initWithURL]
url
URL of the file-system node the file wrapper is to represent.
options
Option flags for reading the node located at url. See “File Wrapper Reading Options” for possible values.
outError
If an error occurs, upon return contains an NSError object that describes the problem. Pass NULL if you do not want error information.

Return Value of [NSFileWrapper initWithURL]
File wrapper for the file-system node at url. May be a directory, file, or symbolic link, depending on what is located at the URL. Returns NO (0) if reading is not successful.

Discussion of [NSFileWrapper initWithURL]
If url is a directory, this method recursively creates file wrappers for each node within that directory. Use the fileWrappers method to get the file wrappers of the nodes contained by the directory.

NSFileWrapper initWithURL example.
- (NSData *)exportToNSData {
    NSError *error;
    NSURL *url = [NSURL fileURLWithPath:_docPath];
    NSFileWrapper *dirWrapper = [[[NSFileWrapper alloc] initWithURL:url options:0 error:&error] autorelease];
    if (dirWrapper == nil) {
        NSLog(@"Error creating directory wrapper: %@", error.localizedDescription);
        return nil;
    }  

    NSData *dirData = [dirWrapper serializedRepresentation];
    NSData *gzData = [dirData gzipDeflate];   
    return gzData;
}

Example of [NSFileWrapper initWithURL].
NSError *error;
NSFileWrapper *fw = [[NSFileWrapper alloc] initWithURL:url options:0 error:&error];
// After the above method has been called, `error` is either `nil` (if all went well),
// or non-`nil` (if something went wrong).

NSFileWrapper initWithURL example.

- (BOOL)readFromURL:(NSURL *)url error:(NSError **)outError;
{
self.fileWrapper = [[NSFileWrapper alloc] initWithURL:url options:nil error:outError];
NSString *rtfFilename = [url lastPathComponent];
NSFileWrapper *rtfWrapper = [self.fileWrapper.fileWrappers objectForKey:rtfFilename];
NSString *rtfString = [[NSString alloc] initWithData:[rtfWrapper regularFileContents] encoding:NSUTF8StringEncoding];
NSAttributedString *attributedString = [OUIRTFReader parseRTFString:rtfString];

_text = [attributedString copy];

return YES;
}

End of NSFileWrapper initWithURL example article.