swift: Bundle.main.path returns nil - swift

i created a folder in my assets called "json" into there i dragged&dropped a file called code.json from the finder. Now i want to open the file but
Bundle.main.path(forResource: "code", ofType: "json", inDirectory: "json")
just returns nil.
I also tried to put it in the assets without the subfolder and using following way
Bundle.main.path(forResource: "code", ofType: "json")
with the same result.
Can anyone help me? What am i doing wrong?

You need to make the folder reference when you drag it to xcode , it's color is blue not yellow
//

It is clear from your question that you are trying to add the code.json file in Assets.xcassets and trying to access it's path with Bundle.main.path(forResource: ), which will always returns nil, because Assets.xcassets is present in Bundle and then your file exists in it.
Try adding the files directly to the project, as suggested in previous answer, approach is right, Bundle.main.path(forResource: "code", ofType: "json")

Related

Is there a way to set up AVPlayer without specifying filetypes?

I am using a TableViewController to list content of multiple filetypes, say ".mov" and ".wav".
I want to open these files in AVPlayer. However, I can only get these to play if I hardcode the filetype extension.
The problem with that is that if I designate ".mov" then my .wav files will not play, or vice versa.
[This is my code ][2]
If your path contains a name already, you can pass nil for type:
Bundle.main.path(forResource: path, ofType: nil)
Just make sure that your itemArray contains not only file names, but also file extensions, like this:
itemArray = [
"file1.mov",
"file2.wav",
...
]

Get path of file from a SubGroup in project with Swift 5

I want to access the path of plist file
I am accessing path with following line
I can access when file is in root folder with following line
let filePath = Bundle.main.path(forResource: Constants.googleServiceFileName, ofType: "plist")
but when i move files in sub group and use following code its return nil
let filePath = Bundle.main.path(forResource: Constants.googleServiceFileName, ofType: "plist",inDirectory: "Firebase")
but it's return nil ..
The group in which you keep a resource in Xcode is not necessarily related to its final location in the bundle. Your file is probably still in the top level Resources directory.
If you want to be completely sure where the build puts your file, look for the build log in the Report Navigator, locate the "Copy " line and expand it using the button at the right hand edge. That will tell you exactly where it is.
In the above, I have an Excel spreadsheet in the group testData. You can see that the build has put it in the top level Resources directory.

How to hide packages file like example.app?

I am listing directories on a outlineView and I can't find how to hide package files.
let urls = try FileManager.default.contentsOfDirectory(at: url,
includingPropertiesForKeys: [.isDirectoryKey],
options: [.skipsHiddenFiles, .skipsPackageDescendants])
I can only so skip regular files like text.txt
All files with .app extension are listed
The skipsPackageDescendants option is meant to prevent deep directory traversal from traversing into the packages. The flag doesn't mean "ignore all packages". It actually means "don't enumerate the contents inside the package".
contentsOfDirectory() doesn't do a deep directory traversal, so the option is meaningless in that context. The enumerator(at:...) method would honor that flag by not enumerating files inside the .app bundle; it would still enumerate the .app itself.
If you're not interested in certain kinds of files, you would use
let urls = try FileManager.default.contentsOfDirectory(
at: url,
includingPropertiesForKeys: [.isDirectoryKey],
options: [.skipsHiddenFiles]
).filter { $0.pathExtension != "app" }

Issue opening file in swift

I am trying to read text from a file and I am currently using this statement to read from a file.
When I try to print the path it shows 'nil' and I am not sure why it is not opening the file since it prints the else statement. Can someone tell me how I can go about doing this possibly another way?
if let path = Bundle.main.path(forResource: "knapsack", ofType: "txt")
{
print("File opened")
}
else
{
print("failed to load file from bundle")
}
The solution that worked for me was to add the text file in the product path that is located in Library -> Developer -> Xcode -> Derived Data -> "Your Project" -> Build -> Products -> Debug.
I added the file to this path and this solved issue and had no issue opening the file. I guess Xcode has two different paths that needs to have a file added.
1- create a file named knapsack.txt
2- drag the file to project and select copy
3- reference the file as you currently do
see demo here readFile

Getting path for resource in Command Line Tool

I'm trying to get the path of a resource in a Command Line Tool in Xcode (8 beta 2). Here's what I've got:
The resource, file.xyz, has been dragged into the project and the target membership matches the main project.
Under Build Phases -> Copy Files, the destination is set to "Resources" and the subpath is empty. "Copy only when installing" is unchecked and file.xyz is listed in the table below.
In my main.swift file, I have the following code:
guard let filePath = Bundle.pathForResource("file",
ofType: "xyz",
inDirectory: "Resources") else{
fatalError("Could not find file")
}
The fatalError is triggered every time. Any ideas? I understand that Command Line Tools don't have an application bundle and that's why the resource is being copied into the Resources folder instead, but my inDirectory argument is a bit of a wild guess… Thanks for reading.
EDIT: My primary goal is to access a resource file (text file, in this case) from a CLT—I'm not attached to this specific way of doing it, so if there's an alternate approach that's great too!
With Xcode 13.2 and Swift 5, I had same issue: I've dragged a JSON file into my Command Line Tool project and was not able to use it directly in my code. As CLT does not seems to have a Bundle, I have found a workaround.
I have created a struct with only a static let property containing my JSON as string:
struct CategoriesJSON {
static let string = """
... my JSON is here as plain text ...
"""
}
Now I can use it by simply call: CategoriesJSON.string.
I know it's a bit ugly, but now my JSON is in my project as I needed.
As a workaround, you can use the absolute path of the source file
For example if on iCloud drive :
let path = "/Users/myName/Library/Mobile
Documents/com~apple~CloudDocs/myDirectory/file.xyz"