3

I am trying to read a .obj file into a SCNNode from the local drive on a macOS app (not iOS) with the following code:

let url = NSURL(string: objPath!)
let asset = MDLAsset(url: url! as URL)
       
let node = SCNNode(mdlObject: asset.object(at: 0))
node.geometry?.firstMaterial?.diffuse.contents = NSColor.red
        
scnView.scene?.rootNode.addChildNode(node)

The objPath is correct and absolute path to a local folder (not inside app build). But it's giving "Could not open OBJ file" error while reading. I need to access local path only.

halfer
  • 19,824
  • 17
  • 99
  • 186
Sarbartha Sengupta
  • 316
  • 1
  • 4
  • 11

1 Answers1

6

This should let you load an obj/dae file in swift/xcode 10.2+:

Create a scenekit model catalog by going to File --> New --> File and selecting "SceneKit Catalog" from the list.

import SceneKit.ModelIO

Then:

guard let url = Bundle.main.url(forResource: "your_obj_filename", withExtension: "obj", subdirectory: "your_folder.scnassets") 
     else { fatalError("Failed to find model file.") }

let asset = MDLAsset(url:url)
guard let object = asset.object(at: 0) as? MDLMesh 
     else { fatalError("Failed to get mesh from asset.") }

let newNode  = SCNNode(mdlObject: object)
Jubei
  • 1,686
  • 1
  • 17
  • 28