Подтвердить что ты не робот

Как определить, существует ли файл в комплекте приложения?

Извините, немой вопрос №2 сегодня. Можно ли определить, содержится ли файл в приложении Bundle? Я могу получить доступ к файлам без проблем, т.е.,

NSString *pathAndFileName = [[NSBundle mainBundle] pathForResource:fileName ofType:@"plist"];

Но не могу понять, как проверить, существует ли файл там в первую очередь.

Привет

Дейв

4b9b3361

Ответ 1

[[NSFileManager defaultManager] fileExistsAtPath:pathAndFileName];

Ответ 2

Этот код работал у меня...

NSString *pathAndFileName = [[NSBundle mainBundle] pathForResource:fileName ofType:nil];
if ([[NSFileManager defaultManager] fileExistsAtPath:pathAndFileName])
{
    NSLog(@"File exists in BUNDLE");
}
else
{
    NSLog(@"File not found");
}

Надеюсь, это поможет кому-то...

Ответ 3

NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSString *path = [documentsDirectory stringByAppendingPathComponent:@"filename"];
    if(![fileManager fileExistsAtPath:path])
    {
        // do something
    }

Ответ 4

pathForResource будет возвращать нуль, если ресурс не существует. Проверка снова с помощью NSFileManager является избыточной.

Obj-C:

 if (![[NSBundle mainBundle] pathForResource:@"FileName" ofType:@"plist"]) {                                              
      NSLog(@"The path could not be created.");
      return;
 }

Swift 4:

 guard Bundle.main.path(forResource: "FileName", ofType: "plist") != nil else {
      print("The path could not be created.")
      return
 }

Ответ 5

То же, что и @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...")
}