Common misconception when creating NSUserActivity in view controller

Edward Poot
1 min readJun 18, 2016

--

I noticed a lot of tutorials on the web set the userActivity property of UIResponder (ViewController is a subclass of this) and then also call the becomeCurrent() and resignCurrent() methods.

For example, this tutorial presents the following code:

let activity = NSUserActivity(activityType: "com.razeware.shopsnap.view")
activity.title = "Viewing"
activity.userInfo = ["shopsnap.item.key": ["Apple", "Orange", "Banana"]]
self.userActivity = activity;
self.userActivity?.becomeCurrent()

Although this does not appear to be documented clearly, when you set the userActivity property, UIKit will take care of this for you. After you set the property, the activity will become the current one, and when the user leaves the view the activity is automatically resigned. In addition, the activity is also invalidated if the view is left.

Thus, we can safely remove the call to becomeCurrent(). Below code will achieve the same behavior:

let activity = NSUserActivity(activityType: "com.razeware.shopsnap.view")
activity.title = "Viewing"
activity.userInfo = ["shopsnap.item.key": ["Apple", "Orange", "Banana"]]
self.userActivity = activity;

--

--