Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iphone - how to check if the file is a directory , audio , video or image?

Following my program shows contents of Documents directory and is displayed in a tableView . But the Documents directory contains some directories , some audio , some video , and some images etc .

NSArray *dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *docsDir = [dirPaths objectAtIndex:0]; fileType = @"" ; NSString *subDirectoryPath = [docsDir stringByAppendingPathComponent:fileType]; NSLog(@"path : %@",subDirectoryPath); files  = [[NSMutableArray alloc] initWithArray:[[NSFileManager defaultManager] contentsOfDirectoryAtPath:subDirectoryPath error:nil]]; NSLog(@"files ::::: %@ ",[files description]); 

So , I want to check if file is directory then it directory image can be shown in the cell's imageView . Same for audio , video and image .

I searched in NSFileManager classReference , but dint get a solution .

How to do this ?

like image 876
Subbu Avatar asked Jun 17 '13 10:06

Subbu


2 Answers

Sample Code :

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectory = [paths objectAtIndex:0]; NSArray *directory = [[NSFileManager defaultManager] directoryContentsAtPath: documentsDirectory]; BOOL isDirectory; for (NSString *item in directory){     BOOL fileExistsAtPath = [[NSFileManager defaultManager] fileExistsAtPath:item isDirectory:&isDirectory];     if (fileExistsAtPath) {        if (isDirectory)        {            //It's a Directory.        }     }     if ([[item pathExtension] isEqualToString:@"png"]) {        //This is Image File with .png Extension     } } 

You can also use Uniform Type Identifiers as explained by Bavarious here.

Sample Code :

NSString *file = @"…"; // path to some file CFStringRef fileExtension = (CFStringRef) [file pathExtension]; CFStringRef fileUTI = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, fileExtension, NULL);  if (UTTypeConformsTo(fileUTI, kUTTypeImage)) NSLog(@"It's an image"); else if (UTTypeConformsTo(fileUTI, kUTTypeMovie)) NSLog(@"It's a movie"); else if (UTTypeConformsTo(fileUTI, kUTTypeText)) NSLog(@"It's text");  CFRelease(fileUTI); 
like image 183
Bhavin Avatar answered Sep 22 '22 19:09

Bhavin


Look at the NSURL class. You can for example see if the url is a file url by saying isFileUrl.

Additionally you can get the last component of the url (usually the file name) by doing:

NSString *filename = [[url path] lastPathComponent]; 

These can help you do what you need, but more importantly look at the NSURL documentation.

like image 29
William Falcon Avatar answered Sep 20 '22 19:09

William Falcon