Passing a UIImage from phone to watch is not working

133 views Asked by At

For watchOS 2 and Xcode 7.3, I am trying to send an image I have in the iPhone side to the watch side. In the phone side, I have this:

func sendImage() {
    if WCSession.isSupported() {
        let session = WCSession.defaultSession()
        if session.watchAppInstalled {
            do {
                let image = UIImage(named: "myPic")
                let imgData = NSKeyedArchiver.archivedDataWithRootObject(image!)
                let dictionary = ["img": imgData]
                try session.updateApplicationContext(dictionary)
            } catch {
                print("ERROR: \(error)")
            }
        }
    }
}

Then, in the WatchKit Extension side (ExtensionDelegate file), I have:

func session(session: WCSession, didReceiveApplicationContext applicationContext: [String : AnyObject]) {

    let initialController = WKExtension.sharedExtension().rootInterfaceController as! InterfaceController
    initialController.showImage(applicationContext["img"] as! NSData)
}

and in InterfaceController:

func showImage(imageData: NSData) {
    let image = UIImage(data: imageData, scale: 1.0)
    self.myImage.setImage(image!)
}

where myImage is a WKInterfaceImage outlet. When showImage method is called, imageData is not nil, but image is when self.myImage.setImage(image!) called. What am I doing wrong?

2

There are 2 answers

0
Vanessa Forney On

I'm unfamiliar with NSKeyedArchiver but this is what I suggest.

You are archiving the image on the phone and then just trying to use the data on the Watch side. I think you would need some type of unarchiving if that makes sense. I found that there exists a NSKeyedUnarchiver which has a unarchiveObjectWithData function. Try this instead of using the archived data, so you will first unarchive the data and then construct a UIImage.

You could also instead use the function UIImagePNGRepresentation which takes a UIImage on the phone side and send the NSData over. Then you skip the extra step of archiving, which I'm not sure you even need. Then you just construct the UIImage with the NSData that was sent.

If this doesn't work, add a print of the data you are sending and the data received on the Watch and compare them.

0
WhiteTiger On

It considers that the approach you used is not the one recommended by Apple (though in part with the necessary precautions can be used), Apple recommends using the following method for exchanging files (you can save your image to a temporary file and send her to watch)

func transferFile(_ file: NSURL, metadata metadata: [String : AnyObject]?) -> WCSessionFileTransfer

Of course you have to remember that the exchange of data between Apple Watch and iPhone is limited as a dimension.