Friday, May 31, 2013

NSArray pathsMatchingExtensions example in Objective C (iOS).


NSArray pathsMatchingExtensions

Returns an array containing all the pathname elements in the receiving array that have filename extensions from a given array.

- (NSArray *)pathsMatchingExtensions:(NSArray *)filterTypes

Parameters
filterTypes
An array of NSString objects containing filename extensions. The extensions should not include the dot (“.”) character.

Return Value of [NSArray pathsMatchingExtensions]
An array containing all the pathname elements in the receiving array that have filename extensions from the filterTypes array.

NSArray pathsMatchingExtensions example.
- (ViewController *) init {
    if (self = [super init]) self.title = @"Text Files";

    // get the list of .txt files
    directoryList = [[[[NSFileManager defaultManager] directoryContentsAtPath:DOCUMENTS_FOLDER]
                      pathsMatchingExtensions:[NSArray arrayWithObjects:@".txt", nil]] retain];
    NSLog(@"%@", directoryList);

    return self;
}

Example of [NSArray pathsMatchingExtensions].
Yes we have direct method for NSArray below helps you

 NSMutableArray *arrayFiles = [[NSMutableArray alloc] initWithObjects:@"a.png", @"a.jpg",  @"a.pdf", @"h.png", @"f.png", nil];
    NSLog(@"pathsMatchingExtensions----%@",[arrayFiles pathsMatchingExtensions:[NSArray arrayWithObjects:@"png", nil]]);

//my output is
"a.png",
"h.png",
"f.png"

NSArray pathsMatchingExtensions example.
-(NSMutableArray*)searchfiles:(NSString*)basePath ofTypes:(NSArray*)fileTypes{
    NSMutableArray *files = [[[NSMutableArray alloc]init] autorelease];
    NSFileManager *defFM = [NSFileManager defaultManager];
    NSError *error = nil;
    NSArray *dirPath = [defFM contentsOfDirectoryAtPath:basePath error:&error];
    for(NSString *path in dirPath){
       BOOL isDir;
       path = [basePath stringByAppendingPathComponent:path];
       if([defFM fileExistsAtPath:path isDirectory:&isDir] && isDir){
          [files addObjectsFromArray:[self searchfiles:path ofType:fileTypes]];
       }
    }

   NSArray *mediaFiles = [dirPath pathsMatchingExtensions:fileTypes];
   for(NSString *fileName in mediaFiles){
      fileName = [basePath stringByAppendingPathComponent:fileName];
      [files addObject:fileName];
   }

   return files;
}

End of NSArray pathsMatchingExtensions example article.