Keloo
Keloo

Reputation: 1408

Swift Metal MTLCreateSystemDefaultDevice returns nil

I try to develop something on Metal iOS and receive the following error:

Code:

let device = MTLCreateSystemDefaultDevice()!

Error:

Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value

I'm on xcode 9.4.1

iOS SDK: 11.4

Architecture: arm64 armv7 armv7s

Can someone please help.

Upvotes: 7

Views: 2876

Answers (2)

Andris Gauračs
Andris Gauračs

Reputation: 418

It works on the simulator, but I have macOS 11.1 and I still encountered this problem.

In my case, the problem I found was that the MTLCreateSystemDefaultDevice() result needs to be explicitly assigned to an MTLDevice variable, before passing it to the metalView.

This works:

class ViewController: UIViewController {
    
    var metalView: MTKView {
        return view as! MTKView
    }
    var device: MTLDevice!
    var commandQueue: MTLCommandQueue!

    override func viewDidLoad() {
        override func viewDidLoad() {
        super.viewDidLoad()
        device = MTLCreateSystemDefaultDevice()
        metalView.device = device
        metalView.clearColor = MTLClearColor(red: 0.0, green: 0.0, blue: 1.0, alpha: 1.0)
        metalView.delegate = self
        commandQueue = device.makeCommandQueue()
    }
    }
}

If we try to assign it directly to metalView.device, it throws the error:

override func viewDidLoad() {
        super.viewDidLoad()
        metalView.device = MTLCreateSystemDefaultDevice()
        metalView.clearColor = MTLClearColor(red: 0.0, green: 0.0, blue: 1.0, alpha: 1.0)
        metalView.delegate = self
        commandQueue = device.makeCommandQueue()
    }

Upvotes: 0

aBilal17
aBilal17

Reputation: 3132

Test it on real device iPhone or iPad, it will not work on Simulator.

Upvotes: 4

Related Questions