I'm trying to pass a stored CLLocation
object from my iOS app back to an extension (in that case: an Apple Watch extension).
For that, I'm using the recommended openParentApplication(userInfo: [NSObject : AnyObject]!, reply: (([NSObject : AnyObject]!, NSError!) -> Void)!) -> Bool
function from the WKInterfaceController
class in the extension code. I'm successfully receiving the request in my iOS app through the application delegate's application(application: UIApplication!, handleWatchKitExtensionRequest userInfo: [NSObject : AnyObject]!, reply: (([NSObject : AnyObject]!) -> Void)!)
function.
Now, I'm trying to pass data back to the app extension using this code:
var results = [NSObject: AnyObject]()
if let loc = getLastKnownLocation() {
results["hasLoc"] = "yes"
results["locStr"] = "\(loc)"
results["results"] = loc // at this point, loc is actually a valid CLLocation object
}
reply(results)
All this code is executed in the iOS app's context and everything is working fine. However, when the reply
function gets called in the extension's context, the dictionary ultimately becomes nil
.
InterfaceController.openParentApplication(parentValues, reply: {(values, error) -> Void in
NSLog("\(values) (err: \(error))") // echoed back to the console: "nil (err: nil)"
})
I realised that the faulty line is this one:
results["results"] = loc
When this line is commented, the extension successfully gets a dictionary filled with the two first items as strings ("hasLoc"
and "locStr"
):
[locStr: Optional(<+37.33756323,-122.04115699> +/- 10.00m (speed 5.00 mps / course 272.00) @ 21/12/2014 19:20:05 heure normale d’Europe centrale), hasLoc: yes] (err: nil)
So it seems like inserting a CLLocation
object in my dictionary makes it all fail and become nil
, but I can't understand why. What am I doing wrong?
Thanks for your help.
EDIT: per @matt's request, here's the code for getLastKnownLocation()
:
class func getLastKnownLocation() -> CLLocation? {
return NSKeyedUnarchiver.unarchiveObjectWithData(NSUserDefaults(suiteName: AppHelper.appGroupName)!.dataForKey("UserLastLocation")!) as CLLocation?
}
I read in the docs: "The contents of the dictionary must be serializable to a property list file." But a CLLocation is not serializable in this way. Presumably you must wrap it up (again) in an NSData before you stick it into the dictionary to be passed across the barrier.