AppleWatch - "attempt to insert nil" when calling WKInterfaceDevice addCachedImage

221 views Asked by At

Calling WKInterfaceDevice addCachedImage(_:name:) to send an image from my iPhone app to the Apple Watch (where the extension can tell an image view to show it) crashes. The exception is this:

2015-06-09 20:47:57.079 TimeInterval[20195:5186462] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[__NSPlaceholderArray initWithObjects:count:]: attempt to insert nil object from objects[3]'

Various Google and StackOverflow searches show this has to do with using a shortcut to create an NSDictionary that doesn't allow passing in nil. However, my code isn't making a dictionary at all. Furthermore, when the debugger breaks (breakpoint on exceptions) I verify that the UIImage and the NSString name that I am passing are both definitely not nil.

Has anyone else seen this? Any idea why it happens or how to fix it? Has anyone actually been successful using addCachedImage? (Considering how new AppleWatch is, who knows!)

My chunk of code, in case it helps:

func application(application: UIApplication, handleWatchKitExtensionRequest userInfo: [NSObject : AnyObject]?, reply: (([NSObject : AnyObject]!) -> Void)!) {
    if let info = userInfo {
        NSLog("watch kit request: %@", info)
        if let element = info["element"] as? String {
            //Request to render an element
            if element == "timer" {
                let timerView = NPProgressLabel(size: CGSizeMake(48, 48))
                timerView.text = info["value"] as! String
                timerView.progressPercent = (info["progress"] as! NSNumber).floatValue
                timerView.render()

                let device = WKInterfaceDevice.currentDevice()
                var success = false
                if let image = timerView.currentImage {
                    success = device.addCachedImage(image, name: timerView.currentImageName()) // <------- crashing here ----------
                } else {
                    NSLog("no image");
                }
                if !success {
                    NSLog("failed")
                } else {
                    NSLog("addCachedImage success")
                }
                reply(["imageName": timerView.currentImageName()])
            } else {
                reply(["error": "Unknown element"])
            }
            return
        }
    }
    reply(["error": "Bad request"])
}
1

There are 1 answers

0
webjprgm On

The exact error I get may be an Apple bug, but I think the answer to my question is that WKInterfaceDevice's addCachedImage should not be called from the iPhone app but rather from the WatchKit Extension. Between iPhone app and WatchKit Extension I have to use a shared container to save then load the image, then the extension can call addCachedImage.