I am trying to load a .obj file into Xcode so I can load it using ModelIO.
I got a .obj file, along with a .model and .mtl file, from a website offering free 3D models. (unfortunately I can't remember the name, but I'm sure it's not important) I placed all 3 files into Assets.xcassets.
Then I use the following code to try and load the file. The OBJ file is specifically called "car.obj":
let modelURL = Bundle.main.url(forResource: "car", withExtension: "obj")!
It should be returning a URL that I can use to create an MDLAsset with, but if I try to build the app it just shows the following error:
Thread 1: Fatal error: Unexpectedly found nil while unwrapping an
Optional value
Which implies that the file was not found, according the Apple's documentation. This leads me to believe I haven't imported the file properly, or I have a corrupt file. Any ideas?
No need placed to Assets.xcassets. Try placed into project folder. Just like onimage
Related
I have a command line project in Xcode 9 and I'm trying to read a text file I added to the project via "Add files to...". I'm using the following line to grab the path to the file:
guard let filePath = Bundle.main.path(forResource: "stops", ofType: "csv") else {
fatalError("Cannot find CSV file")
}
When I run it, it prints out the fatalError message. I tried adding the text file in the "Copy Bundle Resources" build phase. It still doesn't find the file.
What am I doing wrong?
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)
Create a Swift file in your project that you can use to access the data (mine was Recipe.swift)
Drop your CSV into xcode (ignoring target membership - just for convenience (mine was Recipe.json))
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.
The issue for me was I have created first a ResponseJSON.swift then rename it to ResponseJSON.json (changed to .json extension) and it was not being detected.
Solution:
Remove the reference of the file
Adding it again on Xcode
Compile and smile while you cry with those Xcode bugs :)
I'm trying to create my own language definition, and use it for highlighting the syntax in my app.
The issue I have is that, when trying to access the language definition from my app's data folder (/usr/share/myapp/), even using the c.lang file copied from /usr/share/gtksourceview-3.0/language-specs/, just to test, I get this error at runtime:
GtkSourceView-WARNING **: Failed to load '/usr/share/myapp/c.lang': could not find the RelaxNG schema file
So it's asking for some schema file? So I went forward and copied every file from the language-specs folder that isn't a lang file, which includes: language.dtd, language.rng and language2.rng.
Now, when I run again, I get these errors:
GtkSourceView-WARNING **: in file /usr/share/com.github.aleksandar-stefanovic.urmsimulator/c.lang: style 'def:comment' not defined
GtkSourceView-WARNING **: Failed to load '/usr/share/com.github.aleksandar-stefanovic.urmsimulator/c.lang': unable to resolve language 'def'
What does that even mean? Is that something namespace-related? It is very peculiar, because the exact same file is working perfectly when in gtksourceview folder.
Any clues? Do these "RelaxNG" files work only in their original directories? If so, how can I change that? I've looked into the files, but failed to find any reference to their original folder...
This is the source-code (in Vala) related to the issue:
var manager = Gtk.SourceLanguageManager.get_default ();
string search_paths[] = {"/usr/share/myapp", null};
manager.set_search_path (search_paths);
var buffer = new Gtk.SourceBuffer.with_language (manager.get_language ("c"));
The application does in fact find the language "c", I've checked by debugging.
You have to preserve the Gtk.SourceLanguageManager's original search path when you add your own. Append to it instead of replacing it.
First of all, I am very new to Realm ecosystem.
I have tried this in AppDelegate's applicationDidFinishLaunching method,
print("Realm Path : \(realm.configuration.fileURL?.absoluteURL)")
But it gave me error because, I have added some new properties to the realm object, which produced conflicts with the old schema and crashed the app before even printing this.
If you are interested in the crash log. But it has nothing to do with the main question, right?
fatal error: 'try!' expression unexpectedly raised an error: Error Domain=io.realm Code=10 "Migration is required due to the following
errors:
- Property 'id' has been added to latest object model." UserInfo={NSLocalizedDescription=Migration is required due to the
following errors:
- Property 'id' has been added to latest object model., Error Code=10}: file
/Library/Caches/com.apple.xbs/Sources/swiftlang/swiftlang-703.0.18.8/src/swift/stdlib/public/core/ErrorType.swift,
line 54
I have one more doubt. I have added this, the realm has to deleteAll before even initialising the old objects right? But it just crashed with the log given above.
import Cocoa
import RealmSwift
import Realm
//MARK: Global Variables
public let realm = try! Realm()
func applicationDidFinishLaunching(aNotification: NSNotification) {
realm.deleteAll()
print("Realm Path : \(realm.configuration.fileURL?.absoluteURL)")
}
So now I want to delete the realm file, but I have no idea where to find it. I have searched in Mac using extension .realm, but could not the find the expected file. I have the Realm browser app, I thought it would redirect me to the file location, but it didn't, it just opened the Documents folder, there is no realm file.
How would you do it? Thanks it advance.
The Realm does change when you create new file.
Just add the following line to your ViewDidLoad method:
print(Realm.Configuration.defaultConfiguration.fileURL!)
This line will print the location to XCode console. Copy the file path, go to Finder -> Go -> Go go Folder... -> paste the path and hit Go.
I found the answer to my own question, Happiness :) It will be in this directory.
Users/UserName/Library/Application Support/appBundleIdentifer/default.realm)
Basically username stands for your computer's main users name, and the bundle identifier stands for something like this in your project com.yourCompany.yourApp
In case anyone is looking for it, I couldn't find the file in any of the locations above.
I'm on macOS 11.1 and the default.realm file is actually located under
~/Library/Containers/{app.bundle.identifier}/Data/Library/Application Support
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"
I created a project without checking "use CoreData". The Project name is "glossary"
Now I changed my mind and so for I added an data model usinng Add->New File->Resource->Data Model->gave it the name Glossary->didn`t select any class->Finish.
The next step was to design my Data Model.
Then I added the needed Code to my AppDelegate.
For all Steps i was following this Tutorial:
https://developer.apple.com/library/ios/#documentation/DataManagement/Conceptual/iPhoneCoreData01/Introduction/Introduction.html%23//apple_ref/doc/uid/TP40008305-CH1-SW1
My problem now is located in this line:
NSURL *modelURL = [[NSBundle mainBundle] URLForResource:#"glossary" withExtension:#"momd"]
modelURL is always nill
Creating an extra NSBundle Ref and calling mainBundle shows me that this is working, however i don`t know if it is really the right path.
Doing the same Steps on an project with selected "use CoreData" while creating works great.
Has anybody an idea?
It has to do with model versioning. You want to add a versioned model (item in Xcode project tree will have .xcdatamodeld extension) and then your code will run smoothly.
In Xcode 4 when you add a new Core Data file it is versioned by default. Even if you added Core Data support after project creation.
If you don't plan to have model versions, just use .mom in your code.
I'm not 100 % sure, but URLForResource does work for files only and momd is directory.
URLForResource documentation: The method first looks for a matching resource file in the nonlocalized resource directory of the specified bundle. (In Mac OS X, this directory is typically called Resources but in iOS, it is the main bundle directory.) If a matching resource file is not found, it then looks in the top level of any available language-specific “.lproj” directories. (The search order for the language-specific directories corresponds to the user’s preferences.) It does not recurse through other subdirectories at any of these locations. For more details see Bundles and Localization.