How to access local files within project

I want to add some static files (image, binary, etc…) to my app. I’ve placed them under a folder named Resources and have added it to my XCode project.

Next, I have those files added to the Copy Bundle Resources in the Build Phases tab in the project settings.

  • Screenshot for AVPlayer and Video
  • How do you disable back and forward caching on iOS Safari?
  • Load resources from relative path using local html in uiwebview
  • Use native iOS compass within an app
  • Swift: can't configure custom table cell programmatically? Init not called?
  • iOS: How does one animate to new autolayout constraint (height)
  • However, I can’t seem to refer to them in the right way.

    For instance, reading a binary file:

    NSInputStream *is = [[NSInputStream alloc] initWithFileAtPath:@"data.bin"];
    if(![is hasBytesAvailable]) NSLog(@"wrong");
    

    This always fails & prints wrong

    I tried a similar approach with NSData initWithContentsOfFile: but this wouldn’t even execute. Another attempt was to use [NSBundle mainBundle] but this also didn’t execute fully.

    I’m new to iOS please help I can access my local files! Any help would be appreciated.

    Thank you,

    3 Solutions Collect From Internet About “How to access local files within project”

    You need to ensure that you’re accessing the file in the right place. Xcode places your resource files in the application’s “application bundle” in the Resources directory. There are many ways to dig ’em out.

    A common way is to get the pathname of a file in your bundle:

    NSBundle *mainBundle = [NSBundle mainBundle];
    NSString *myFile = [mainBundle pathForResource: @"data" ofType: @"bin"];
    

    If you have other files in nonstandard places in your bundle, there are variations to pathForResource that let your specify a directory name.

    If you want to see the actual location on your hard-drive that the simulator is using so you can inspect it, you can say:

    NSLog(@"Main bundle path: %@", mainBundle);
    NSLog(@"myFile path: %@", myFile);
    

    Search for the “Bundle Programming Guide” in the Xcode documentation library to get started. 🙂

    Use NSBundle class for that. For Example:

    NSString *path = [[NSBundle mainBundle] pathForResource:@"data" ofType:@"bin"];
    NSInputStream *is = [[NSInputStream alloc] initWithFileAtPath:path];
    ...
    

    Indeed calling [is open] is needed even though you “initialiseWithFileAtPath”. I would think the initialisation would automatically open the file for you, but it doesn’t.