Read a File in a MACos Command Line Tool Project

Read a file in a macOS Command Line Tool project

There is no app bundle for a command-line tool. Just a binary.

You need to put the JSON file in a known location (current directory?) and construct the path yourself

Reading project data file in Mac OS Xcode project

As per HAS comment:

See comments. Hint from HAS pointed the way:

NSBundle *myBundle = [NSBundle mainBundle];
NSString *absPath= [myBundle pathForResource:@"the_file" ofType:@"dat"];

to get the path. Added the file to the project as a text file.

The path resolves to ...../Contents/Resource/the_file.dat. – TenG yesterday

How to copy bundle resources for command line tool project in Xcode?

A command-line-tool only consists of an executable. No bundle is created and what you are trying to do is not possible.

You’ll have to place the file in some other place and load it from there.

Bundle.main.path does not find text file added in project

Early last year I had this same issue - here is my workaround (and I must stress that this is a work around, hopefully there is another way to do it now)

  1. Create a Swift file in your project that you can use to access the data (mine was Recipe.swift)
  2. Drop your CSV into xcode (ignoring target membership - just for convenience (mine was Recipe.json))
  3. Create a run script phase to load the data from your CSV to into a Swift class:

    set -e
    DATA=$(cat "./MyProject/recipe.json" | base64)
    echo "import Foundation" > "./MyProject/Recipe.swift"
    echo "class Recipe {" >> "./MyProject/Recipe.swift"
    echo " static let data = \"$DATA\"" >> "./MyProject/Recipe.swift"
    echo "}" >> "./MyProject/Recipe.swift"

This generates a class in your Swift file that looks something like:

import Foundation
class Recipe {
static let data = "..."
}

And then you can decode Recipe.data when you need to use it.

Of course this isn't a very expandable solution, and I'm sure you can make it better by using lazy initialization, adding the base64 decode directly in the generated class, making paths in the script relative to $SRCROOT etc. This was just my quick solution that allowed me to continue working on the rest of the project.



Related Topics



Leave a reply



Submit