在应用程序启动时获取bundle文件引用/路径



假设主应用程序捆绑包中包含任意一组文件。我想在启动时获取这些文件的URL,并将它们存储在某个地方。使用NSFileManager可以做到这一点吗?这方面的文件尚不清楚。

注意:我只需要文件的URL,我不需要访问实际的文件。

您可以使用获取主捆绑包中文件的URL

NSString *path = [[NSBundle mainBundle] pathForResource:@"SomeFile" ofType:@"jpeg"];
NSURL *url = [NSURL fileURLWithPath:path];

例如,您可以将此URL写入Documents目录中的属性列表文件:

NSString *docsDir = [NSSearchForDirectoriesInDomains(NSDocumentsDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *plistPath = [docsDir stringByAppendingPathComponent:@"Files.plist"];
NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:[url absoluteString] forKey:@"SomeFile.jpeg"];
[dict writeToFile:plistPath atomically:YES];

如果你不知道文件的名称,只想列出捆绑包中的所有文件,请使用

NSArray *files = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:[[NSBundle mainBundle] bundlePath] error:NULL];
for (NSString *fileName in files) {
    NSString *path = [[NSBundle mainBundle] pathForResource:fileName ofType:nil];
    NSURL *url = [NSURL fileURLWithPath:path];
    // do something with `url`
}

或Swift 4:

        let url = Bundle.main.url(forResource: "FileName", withExtension: ".xyz")

是的,你会得到他们的路径:

NSString *path = [NSBundle mainBundle] pathForResource:@"file1" ofType:@"png"];
NSURL *fileURL = [NSURL fileURLWithPath:path]
// save it as any other object or in a dictionary:
[myMutableDictionary setObject:fileURL forKey:@"file1.png"];

编辑:要获得完整的文件列表,请使用NSFileManager,获取捆绑包本身的路径,然后遍历每个目录,获取文件,创建URL,并将其保存在某个位置。有很多关于SO如何遍历目录的代码。[你应该更新你的问题,更具体地说明你想要什么,这一点最初根本没有明确]

在10.6或iOS 4上,NSBundle(文档)上有一个API可以直接获取NSURL,而不是将路径传递到NSURL构造函数:

- (NSURL *)URLForResource:(NSString *)name withExtension:(NSString *)ext;

它也有采用subdirectorylocalizationName的变体,与-pathForResource:的等价物相同。

最新更新