搜索png文件iOS

时间:2013-11-25 10:09:12

标签: ios objective-c

我正在寻找我的应用文档夹的文件夹中的png文件,并将它们的标题添加到数组中。调用函数数组后仍为空。你能帮助我吗?我是Obj-C的初学者。谢谢。

我的功能:

-(void)getphotolist{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
                                                   NSUserDomainMask, YES);

    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSBundle *myBundle = [NSBundle bundleWithPath:documentsDirectory];

    NSArray *mypngs = [myBundle pathsForResourcesOfType:@".png"
                                               inDirectory:documentsDirectory];

    NSMutableArray *photo_array = [[NSMutableArray alloc] init];

    NSLog(documentsDirectory);

    for (NSString *tString in mypngs) {
        [photo_array addObject:tString];

        for (id obj in photo_array)
        {
            NSLog(@"obj: %@", obj);
        }
    }   
}

3 个答案:

答案 0 :(得分:1)

试试这个,

NSString * myBundle = [[NSBundle mainBundle] bundlePath];
NSFileManager *manager = [NSFileManager defaultManager];
NSDirectoryEnumerator *dir = [manager enumeratorAtPath: myBundle];

NSString *filename;
NSMutableArray *photo_array = [[NSMutableArray alloc] init];
while ((filename = [dir nextObject] )) {


    if ([filename hasSuffix:@".png"]) {   


        [photo_array addObject:[filename stringByDeletingPathExtension]];


    }

}

答案 1 :(得分:0)

问题出在这里:

NSArray *mypngs = [myBundle pathsForResourcesOfType:@".png"
                                        inDirectory:nil];

这里你应该有“无”。如果您有任何自定义目录,它表示bundle目录下的目录。

答案 2 :(得分:-1)

参考此代码。

NSString *extension = @"JPEG";
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

NSString *documentsDirectory = [paths objectAtIndex:0];

NSArray *contents = [fileManager contentsOfDirectoryAtPath:documentsDirectory error:nil];

NSMutableArray *jpegFiles = [NSMutableArray alloc]init];
NSMutableArray *jpegFilesPath=[NSMutableArray alloc]init];
NSString *filename;
for (filename in contents)
{
    if ([[filename pathExtension] isEqualToString:extension])
    {
        [jpegFilesPath addObject:[NSString stringWithFormat:@"%@",[documentsDirectory stringByAppendingPathComponent:filename]]];
        NSLog(@"%@",jpegFilesPath);
        [jpegFiles addObject:[UIImage imageWithContentsOfFile:[documentsDirectory stringByAppendingPathComponent:filename]]];

    }
}

希望这可以帮助你...... !!