5

I've imported a Wavefront OBJ file from a URL and now I'd like to insert it into my scene (SceneKit) on my iOS 9 app (in Swift). What I've done so far is:

let asset = MDLAsset(URL: localFileUrl)
print("count = \(asset.count)")  // 1

Any help converting this to a SCNNode would be appreciated. According to to Apple's docs:

Model I/O can share data buffers with the MetalKit, GLKit, and SceneKit frameworks to help you load, process, and render 3D assets efficiently.

But I'm not sure how to get buffer from an MDLAsset into a SCNNode.

rickster
  • 124,678
  • 26
  • 272
  • 326
Jason Leach
  • 3,889
  • 7
  • 37
  • 54

1 Answers1

11

Turns out this quite easy as many of the ModelIO classes already bridge. I was doing import ModelIO which gave me access to all the ModelIO classes and likewise import SceneKit which gave me the SceneKit classes, but, I was missing import SceneKit.ModelIO to bring in the SceneKit support for ModelIO.

let url = NSURL(string: "url-to-your-obj-here")
let asset = MDLAsset(URL: url!)
let object = asset.objectAtIndex(0)
let node = SCNNode(MDLObject: object)

Easy as that...

Jason Leach
  • 3,889
  • 7
  • 37
  • 54
  • 5
    note that `+[SCNScene sceneWithURL:options:error:]` will also work. – mnuages Jan 12 '16 at 11:43
  • 2
    Also note that there's some cost to parsing/importing OBJ. If this is an asset that you're shipping in/with your app, consider converting it to `.scn` in Xcode (or with your own tools that run on the Mac, using Model I/O) first. – rickster Jan 15 '16 at 19:24
  • I see the `SCNNode` initializer in the documentation, with its signature changed to `SCNNode(mdlObject:)`. But.. Xcode 9.4.1 claims this initializer does not exist, and right-command-clicking on `SCNNode` shows a class definition that does not have that initializer. Where is it? – Andrew Duncan Aug 13 '18 at 17:24
  • Similarly, Xcode denies that `SCNScene(mdlObject:)` exists. – Andrew Duncan Aug 13 '18 at 17:35
  • Thanks for the solution my problem is i am working with server url to download it on local memory and then load it on camera with your solution and its working fine but problem is i am getting .obj 3d object with grey colour no colour my question is how could i load assets as well? – Ali Aqdas Dec 16 '20 at 07:05