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?
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 aunarchiveObjectWithData
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.