Search code examples
iosswiftuiviewwatchkit

Capture UIImage from UIView then use it in WatchKit WKInterfaceImage


So I have a view that I programmatically snapshot using a function basically similar to this:

func captureImage() -> UIImage{

UIGraphicsBeginImageContextWithOptions(bounds.size, false, 0.0)

    drawViewHierarchyInRect(self.bounds, afterScreenUpdates: true)

    // old style: layer.renderInContext(UIGraphicsGetCurrentContext())

    let image = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    return image
}

the function works as intended, and returns a UIImage.

What I need to know: Is there a way to capture the UIImage of the UIView when triggered from the WatchKit extension without opening the actual iPhone app, then how to retrieve that image and display it as a WKInterfaceImage?


Solution

  • You can save this image as NSData to your shared user defaults.

    enter image description here

    Quoted from App Extension Programming Guide: https://developer.apple.com/library/ios/documentation/General/Conceptual/ExtensibilityPG/ExtensionScenarios.html#//apple_ref/doc/uid/TP40014214-CH21-SW1

    And then retrieve it from the WatchKit Extension. However if you want some sort of a trigger. You can use this class method + openParentApplication:reply: to backgroundly tell your containing iOS to do something. And implement its delegate method in the App Delegate func application(application: UIApplication!, handleWatchKitExtensionRequest userInfo: [NSObject : AnyObject]!, reply: (([NSObject : AnyObject]!) -> Void)!)