iosnsuseractivity

NSUserActivity for directions not working


I'm having some trouble implementing an NSUserActivity with a mapItem from my app.

All I want is to be able to use the "Get Directions" suggestion in the app switcher, like Foursquare does:

enter image description here

I'm using the following code in my viewDidLoad method, in the view controller which displays the location (a pub) I want to register.

NSUserActivity *activity = [[NSUserActivity alloc] initWithActivityType:@"co.pubmapper.ViewPub"];

CLLocationCoordinate2D coords = CLLocationCoordinate2DMake(self.pub.lat, self.pub.lng);
MKPlacemark *placemark = [[MKPlacemark alloc] initWithCoordinate:coords];
MKMapItem *mapItem = [[MKMapItem alloc] initWithPlacemark:placemark];
[mapItem setName:self.pub.name];
activity.mapItem = mapItem;

// not sure any of these are necessary for my use case
[activity setEligibleForSearch:YES];
[activity setEligibleForHandoff:YES];
[activity setEligibleForPublicIndexing:YES];

[activity becomeCurrent];

When this runs I see the following in the console:

[main] sendUserActivityToServer, called on activity C626E4B1-ADF8-49D8-80FB-C773DB71243D after it had been invalidated, so doing nothing.

Which suggests my activity item is being invalidated immediately for some reason. I added the following to set the expirationDate but still get the same message in the console.

activity.expirationDate = [NSDate distantFuture];

As far as I can tell I've followed everything in the docs here https://developer.apple.com/reference/foundation/nsuseractivity?language=objc

I've also added my activity type to NSUserActivityTypes , although I think this is only strictly necessary for launching my app and receiving an activity object, which is not what i'm concerned with right now.

SOLVED: based on correct answer from @raidfive below, activity is now a class property with a strong reference:

@property (strong) NSUserActivity *activity;
...
[_activity becomeCurrent];

Solution

  • I'm not sure if this applies to mapItem types, but the docs mention:

    Your app must maintain a strong reference to any activity objects that you use for search results.

    So maybe you need to store activity as a class level variable.