How to catch an error on SCNReferenceNode.referenceURL property (SceneKit)?

Viewed 32

The problem is that if I create SCNReferenceNode and try to get referenceURL

...
        let refNode: SCNReferenceNode = SCNReferenceNode()
        let curUrl = refNode.referenceURL
...

in order to check if it is nil, I got an exception

Thread 1: EXC_BREAKPOINT (code=1, subcode=0x186d06dd0)

And looks like there is no way to work around this.

P.S. I know there is an option to give an URL to the constructor like SCNReferenceNode(myURL), but I have to use an approach where I create SCNReferenceNode before then refURL is available.

1 Answers

It seems like the reference URL property should be marked as nullable in the Objective-C implementation, which would make the property an optional, but that isn't the case. Any attempt to access it via the referenceURL property will cause a crash, as you've found.

However, since the node is an NSObject, you can use key-value coding, and add an extension to it, like this:

extension SCNReferenceNode {
    var optionalReferenceURL: URL? {
        value(forKey: "referenceURL") as? URL
    }
}

This will give you safe access to the reference URL property. In the meantime, you should also file this as a bug with the SceneKit team.

Related