在应用启动时获取捆绑文件引用/路径 [英] Getting bundle file references / paths at app launch
问题描述
假设主应用程序包中包含任意一组文件。我想获取启动时的文件URL并将它们存储在某处。这是否可以使用 NSFileManager
?在这方面文档不清楚。
注意:我只需要文件URL,我不需要访问实际文件。
使用
NSString * path = [[NSBundle mainBundle] pathForResource:@SomeFileofType:@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){
NSString * path = [[NSBundle mainBundle] pathForResource:fileName ofType:nil];
NSURL * url = [NSURL fileURLWithPath:path];
//用'url`做一些事情
}
Suppose I have an arbitrary set of files included in the Main App Bundle. I would like to fetch the file URLs for those at launch and store them somewhere. Is this possible using NSFileManager
? The documentation is unclear in that regard.
Note: I only need the file URLs, I do not need to access the actual files.
You can get the URL of a file in the main bundle using
NSString *path = [[NSBundle mainBundle] pathForResource:@"SomeFile" ofType:@"jpeg"];
NSURL *url = [NSURL fileURLWithPath:path];
You can write this URL to, for example, a property list file in the Documents directory:
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];
If you don't know the names of the files and you just want to list all the files in the bundle, use
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`
}
这篇关于在应用启动时获取捆绑文件引用/路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!