7

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.

Keloo
  • 1,368
  • 1
  • 17
  • 36

2 Answers2

4

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

aBilal17
  • 2,974
  • 2
  • 17
  • 23
  • 2
    It will now work one the simulator. Metal **will work on the simulator** in **iOS 13** and tvOS 13 simulators only when running on macOS **Catalina (10.15)** or later. https://stackoverflow.com/a/57912423/4833705 – Lance Samaria Dec 02 '19 at 17:25
0

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()
    }
Andris Gauračs
  • 398
  • 6
  • 20