对不起,今天的愚蠢问题 2。是否可以确定文件是否包含在 App Bundle 中?我可以访问文件没问题,即
NSString *pathAndFileName = [[NSBundle mainBundle] pathForResource:fileName ofType:@"plist"];
但无法弄清楚如何首先检查文件是否存在。
问候
戴夫
[[NSFileManager defaultManager] fileExistsAtPath:pathAndFileName];
这段代码对我有用......
NSString *pathAndFileName = [[NSBundle mainBundle] pathForResource:fileName ofType:nil];
if ([[NSFileManager defaultManager] fileExistsAtPath:pathAndFileName])
{
NSLog(@"File exists in BUNDLE");
}
else
{
NSLog(@"File not found");
}
希望它会帮助某人...
如果资源不存在,pathForResource 将返回 nil。用 NSFileManager 再次检查是多余的。
对象-C:
if (![[NSBundle mainBundle] pathForResource:@"FileName" ofType:@"plist"]) {
NSLog(@"The path could not be created.");
return;
}
斯威夫特 5:
guard Bundle.main.path(forResource: "FileName", ofType: "plist") != nil else {
print("The path could not be created.")
return
}
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:@"filename"];
if(![fileManager fileExistsAtPath:path])
{
// do something
}
与@Arkady 相同,但使用 Swift 2.0:
首先,调用一个方法mainBundle()
来帮助创建资源的路径:
guard let path = NSBundle.mainBundle().pathForResource("MyFile", ofType: "txt") else {
NSLog("The path could not be created.")
return
}
然后,调用 on 方法defaultManager()
检查文件是否存在:
if NSFileManager.defaultManager().fileExistsAtPath(path) {
NSLog("The file exists!")
} else {
NSLog("Better luck next time...")
}