How can you determine if a file exists within the app bundle?

后端 未结 5 690
星月不相逢
星月不相逢 2021-02-01 12:55

Sorry, dumb question number 2 today. Is it possible to determine if a file is contained within the App Bundle? I can access files no problem, i.e.,

NSString *p         


        
相关标签:
5条回答
  • 2021-02-01 13:12
    [[NSFileManager defaultManager] fileExistsAtPath:pathAndFileName];
    
    0 讨论(0)
  • 2021-02-01 13:14
    NSFileManager *fileManager = [NSFileManager defaultManager];
        NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
        NSString *path = [documentsDirectory stringByAppendingPathComponent:@"filename"];
        if(![fileManager fileExistsAtPath:path])
        {
            // do something
        }
    
    0 讨论(0)
  • 2021-02-01 13:19

    This code worked for me...

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

    Hopefully, it will help somebody...

    0 讨论(0)
  • 2021-02-01 13:28

    Same as @Arkady, but with Swift 2.0:

    First, call a method on mainBundle() to help create a path to the resource:

    guard let path = NSBundle.mainBundle().pathForResource("MyFile", ofType: "txt") else {
        NSLog("The path could not be created.")
        return
    }
    

    Then, call a method on defaultManager() to check whether the file exists:

    if NSFileManager.defaultManager().fileExistsAtPath(path) {
        NSLog("The file exists!")
    } else {
        NSLog("Better luck next time...")
    }
    
    0 讨论(0)
  • 2021-02-01 13:34

    pathForResource will return nil if the resource does not exist. Checking again with NSFileManager is redundant.

    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
     }
    
    0 讨论(0)
提交回复
热议问题