Tuesday, April 30, 2013

NSURL getResourceValue example ios

getResourceValue :forKey:error:

Returns the resource value for the property identified by a given key.
- (BOOL)getResourceValue:(id *)value forKey:(NSString *)key error:(NSError**)error
Parameters of [NSURL getResourceValue]
The value for the property identified by key.
The name of one of the URL’s resource properties.
The error that occurred in the case that the resource value cannot be retrieved.
Return Value
YES if value is successfully populated; otherwise, NO.
Discussion of [NSURL getResourceValue]
value is set to nil if the requested resource value is not defined for the URL. In this case, the method still returns YES.
Example of [NSURL getResourceValue] - 1
NSURL *samplePath = [[NSURL alloc initWithString:@"file://localhost/Users/Abhinav/Test/abhi.pdf"];
NSNumber *fileSizeBytes;
[samplePath getResourceValue:&fileSizeBytes forKey:NSURLFileSizeKey error:&error];
NSLog(@"Error===%@",error); NSLog(@"size of file in bytes ===%@",fileSizeBytes);
Example of [NSURL getResourceValue] - 2
if (![url getResourceValue:&name forKey:NSURLNameKey error:&error])
    NSLog(@"name: %@", [error localizedDescription]);error = nil;
Example of [NSURL getResourceValue] - 3 

NSFileManager *fileManager = [[[NSFileManager alloc] init] autorelease];
NSURL *directoryURL = … // URL pointing to the directory you want to browse
NSArray *keys = [NSArray arrayWithObject:NSURLIsDirectoryKey];

NSDirectoryEnumerator *enumerator = [fileManager
    errorHandler:^(NSURL *url, NSError *error) {
        // Handle the error.
        // Return YES if the enumeration should continue after the error.
        return YES;

for (NSURL *url in enumerator) { 
    NSError *error;
    NSNumber *isDirectory = nil;
    if (! [url getResourceValue:&isDirectory forKey:NSURLIsDirectoryKey error:&error]) {
        // handle error
    else if (! [isDirectory boolValue]) {
        // No error and it’s not a directory; do something with the file