抱歉,今天又问了一个愚蠢的问题。是否有可能确定文件是否包含在应用程序包中?我可以轻松访问文件,例如:
对不起,今天又问了一个愚蠢的问题。是否有可能确定文件是否包含在应用程序包中?我可以轻松访问文件,例如:
NSString *pathAndFileName = [[NSBundle mainBundle] pathForResource:fileName ofType:@"plist"];
但是我无法弄清楚如何首先检查文件是否存在。
敬礼
Dave
抱歉,今天又问了一个愚蠢的问题。是否有可能确定文件是否包含在应用程序包中?我可以轻松访问文件,例如:
对不起,今天又问了一个愚蠢的问题。是否有可能确定文件是否包含在应用程序包中?我可以轻松访问文件,例如:
NSString *pathAndFileName = [[NSBundle mainBundle] pathForResource:fileName ofType:@"plist"];
但是我无法弄清楚如何首先检查文件是否存在。
敬礼
Dave
[[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进行检查是多余的。
Obj-C:
if (![[NSBundle mainBundle] pathForResource:@"FileName" ofType:@"plist"]) {
NSLog(@"The path could not be created.");
return;
}
Swift 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
}
然后,调用defaultManager()
上的一个方法来检查文件是否存在:
if NSFileManager.defaultManager().fileExistsAtPath(path) {
NSLog("The file exists!")
} else {
NSLog("Better luck next time...")
}