申し訳ありませんが、今日は愚かな質問 2 です。ファイルが App Bundle に含まれているかどうかを判断することはできますか? ファイルに問題なくアクセスできます。つまり、
NSString *pathAndFileName = [[NSBundle mainBundle] pathForResource:fileName ofType:@"plist"];
しかし、そもそもファイルがそこに存在するかどうかを確認する方法がわかりません。
よろしく
デイブ
[[NSFileManager defaultManager] fileExistsAtPath:pathAndFileName];
リソースが存在しない場合、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
}
次に、メソッドを呼び出してdefaultManager()、ファイルが存在するかどうかを確認します。
if NSFileManager.defaultManager().fileExistsAtPath(path) {
NSLog("The file exists!")
} else {
NSLog("Better luck next time...")
}