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

后端 未结 5 1288
长发绾君心
长发绾君心 2021-01-31 02:54

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 , an

5条回答
  •  执笔经年
    2021-01-31 03:39

    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);
    

提交回复
热议问题