Search code examples
iosarraysswiftwatchkitapple-watch

Creating an array of Images and display one at random on Apple Watch


I'm trying to add my first ever extension for Apple Watch but having issues with creating an array for the app. When I run the app it crashes and I get this error show up at my array:

Thread 1: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)

Below is my code, all I want is my image to change to a random image from the array every time the button is tapped:

import WatchKit
import Foundation

class InterfaceController: WKInterfaceController {

    let runeArray = [UIImage(named: ("Fehu.png"))!, UIImage(named: ("Uruz.png"))!, UIImage(named: ("Thurisaz.png"))!]

    @IBOutlet var runeImage: WKInterfaceImage!

    override func awake(withContext context: Any?) {
        super.awake(withContext: context)

        // Configure interface objects here.
    }

    override func willActivate() {
        // This method is called when watch view controller is about to be visible to user
        super.willActivate()
    }

    override func didDeactivate() {
        // This method is called when watch view controller is no longer visible
        super.didDeactivate()
    }

    @IBAction func castRuneButton() {

        let randomRune = runeArray[Int(arc4random_uniform(UInt32(runeArray.count)))]
        runeImage.setImage(randomRune)
    }
}

enter image description here


Solution

  • Make sure you have selected both the iOS and watch extension targets for your asset catalog.