
Introduction to Siri Shortcuts
Siri Shortcuts are a powerful new feature in iOS 12 that allow your app to expose its functionality to Siri. This enables Siri to suggest your shortcut at relevant times based on various context. Shortcuts can also be added to Siri to run with a voice phrase on iOS, HomePod and watchOS. Learn how to expose shortcuts in your app using NSUserActivity and discover the benefits of creating custom intents with SiriKit for a richer user experience.
Resources
- Deleting Donated Shortcuts
- Donating Shortcuts
- Learn more about SiriKit
- SiriKit
- Soup Chef: Accelerating App Interactions with Shortcuts
- Presentation Slides (PDF)
Related Videos
WWDC21
Hi, everybody.My name is Ari Weinstein, andI'm really excited to be herealong with Willem Mattelaer totell you about Siri Shortcuts.So, two years ago, we announcedthe first version of SiriKit,which enables your apps to workwith Siri, and it has greatdomain-specific knowledge forthings like sending messages,requesting rides, makingpayments, and more.But we know that you want to doeven more with SiriKit, and sothat's why, this year, we're soexcited to announce Shortcuts.
This central idea behindShortcuts is that it lets youexpose the key capabilities ofyour app to Siri, and this isreally great, because it enablespeople to use the features ofyour apps in new ways and in newplaces.And it's a really powerful wayto engage your users.
So, exposing a shortcut opens upa ton of new possibilities forhow people can use your apps, solet's explore all of the placeswhere Shortcuts can be used.Shortcuts takes Siri'ssuggestions to the next level bysurfacing what you want to donext, not just with your apps,but inside of your apps, and itdoes it by surfacing them insearch at just the right time.
And Siri can suggest shortcutson the Watch, so you can usethem right from your wrist onthe Siri Watch Face.
When Siri is confident that it'sthe exact right time for aShortcut, it will be surfaced onthe lock screen.And, when you tap on a shortcut,you can use it right in linewith a rich custom UI specificto that app.And you can also add shortcutsto Siri, so you can use themwith your voice just by askingSiri.And in Siri you'll see the samecustom UI that you see in searchand on the lock screen.
And apps can provide a greatvoice experience in Siri byproviding custom response dialogthat Siri will read out loud totell you things like how long itwill take for your coffee to beready.So, when the user adds ashortcut to Siri, they get topick a custom personal phrase,so the user chooses what to sayto Siri to invoke your shortcut.And, as a developer, you get tosuggest what phrase to use, so,in this case, a suggestion is"coffee time."And, once a shortcut has beenadded to Siri, it works acrossall of your iOS devices, and onApple Watch, and even onHomePod.So, we also have the newShortcuts app, and with the newShortcuts app, anyone can buildtheir own shortcuts, and you doit just by dragging and droppinga series of steps together.And those steps can even includethe shortcuts exposed by yourapp.So, today, we're going to talkabout how to adopt shortcuts foryour apps, and then we'll talkabout how to optimize yourshortcuts for great suggestions.And we'll also cover someprivacy considerations that areimportant to keep in mind, andwe'll talk about how to makegreat shortcuts for mediaplayback.
So, first, we'll talk about howto adopt the new Shortcut'sAPIs.
There were three steps forcreating a shortcut, and thefirst step is to define yourshortcut. That means you have to decidewhat you want to expose as ashortcut and define each one soSiri knows everything that yourapp can do.
Next, you'll need to donate yournew shortcut.That means you need to tell thesystem every time the user doessomething in your app that youexpose a shortcut for, whichwill let Siri learn when andwhere is the right time tosuggest your shortcut.And the third step is to handleyour shortcut.That means, when the user wantsto go and use your shortcut inSiri, on the lock screen, insearch, you need to be ready foryour app or app extension to beinvoked and be handed theshortcut to handle.
So, before you define shortcuts,you'll need to decide whatexactly it is that you want toexpose.And you should start by thinkingthrough what are the mostimportant things that peoplelike to do with your apps?Because those are the thingsthat you might want to considerexposing shortcuts for.So, every shortcut that youexpose should accelerate theuser, to perform a key functionof your app.That means it should takesomething that the user alreadywanted to do with your app andhelp them do it even faster.
The acceleration that you offershould be substantial, so youshouldn't just expose a shortcutthat does about the same thingas opening your app normally.If you expose a shortcut thatdoesn't provide very muchacceleration to the user, itwon't be suggested asfrequently.And, next, every shortcut thatyou expose should be ofpersistent interest to the user,so that means it should besomething that the user mightwant to do multiple times.It's not a good idea to expose ashortcut for something that theuser might only want to use onceor twice.And you should also expose onlyshortcuts that are executable atany time, because you can't relyon the user being in someparticular state before yourshortcut will be ready for use.
So, once you've decided whatshortcuts to expose, you'reready to check out theshortcuts' APIs.
There were two APIs that wesupport for adopting shortcuts.The first is NSUserActivity.NSUserActivity is a lightweightway to represent the state ofyour app, and it integrates withother Apple features likeSpotlight and Handoff.
And the second is intents.Intents are a way ofrepresenting, in detail, a typeof action that your app canperform, and Siri includes abunch of great built-in intentsthat support a range ofcapabilities that apps can useto integrate with Siri.And, this year, we're introducing something reallycool, which is the ability foryou to define your own customintents for use with Shortcuts.
So, for every shortcut youexpose, you'll need to decidewhether it should be anNSUserActivity or an intent.So, let's talk about how to makethat decision.
Now, NSUserActivity is a greatchoice for building a shortcut.If you're just building a simpleshortcut that opens something inyour app, or if you're exposinga shortcut for something thatyou already index in Spotlightsearch, or that you alreadyoffer in NSUserActivity for, forexample, for Handoff.But for the best Shortcutsexperience, you'll want to adoptintents, and intents-basedshortcuts are really cool,because they can run inlinewithout launching your app.And they can include customvoice responses and custom UIslike we saw earlier.And they can also includegranular parameter predictions,which Willem tell you a littlebit about later.
So, once you've decided how toadopt, you're ready to dive intothe implementation, so let's dothat now. First, let's go over how toadopt shortcuts withNSUserActivity, and the firststep is to define your shortcut.For NSUserActivity, that meansyou need to declare aUserActivityType in your app'sInfo.plist file to register youractivity type with the system.
Next, you need to donate yourshortcut.For NSUserActivity, that meansevery time the user is lookingat the screen in your app thatyou want to provide a shortcutto, you should make anNSUserActivity object available.
So, there's one key new thinghere, which is theisEligibleForPrediction flag.Setting this on any useractivity turns it into ashortcut, and what's really coolis if you have an existing useractivity in your app, you justhave to set this to true andthat user activity will become ashortcut automatically.
Now, note that theisEligibleForSearch flag has tobe true in order forisEligibleForPrediction to havean effect.And, by the way, you might alsowant to consider theisEligibleForHandoff flag, whichdefaults to true.So, by default, all of your useractivities will be able to behanded off between devices.Now, when you're creating youruser activity, you want to makesure to include all of theinformation in your user infodictionary that you'll need torestore the activity later on.
And the last step is to markyour activity current byattaching it to a UIviewController or a UI responderobject that's onscreen.Now, the last step is to handleyour shortcut, once you'vedefined and donated it.And every time the user uses anNSUserActivity from your app, itwill be opened in your app.And so you need to handle it byimplementing the app delegatemethod for handlingNSUserActivity, which is calledcontinueUserActivity.So, all you have to do isimplement this method, check ifthe activity type matches theone that you registered, and, ifit does, then you want torestore the state of your app towhat it was when the useractivity was saved.
So, that's everything you needto do to get Siri to startsuggesting shortcuts for yourapps with NSUserActivity.
Now, let's talk about how toexpose Shortcuts throughintents.
The first step, again, is todefine your shortcut.And so with intents, you'll needto start by deciding what typeof intent you'd like to adopt.And, as you know, Siri includesmany great built-in intents,like for messaging, workouts,lists, and more.
And now we're introducing theability to define custom intentsin Xcode for Shortcuts.
And so if the shortcut that youwant to build corresponds to oneof the default built-in SiriKitintents, then you should adoptthat.But, otherwise, you can defineyour own.And whether you want to defineyour own or adopt an existingone to customize it, you want toget started by creating anintent definition file in Xcode.So, believe it or not, in myspare time, I've been workingwith a couple friends on a newapp, and it's a soup deliveryapp, and it's called Soup Chef.It's the easiest way to ordersoup, and I'm really excitedabout the potential of hookingit up to Siri.So, let's step through how touse the new Intent Editor tobuild an intent for Soup Chef.I'm going to start by going toFile, New File in Xcode, andI'll choose the SiriKit IntentDefinition File type.And then I'll see the new IntentEditor.So, let's get started byclicking the plus button in thebottom left. Next, I want to give my intent aname. And, so in this case, I'm makingan intent for ordering a soup,so I'm going to call itOrderSoup.
Then I want to fill out myintent's metadata.So, let's look at that one stepat a time.
The first piece of metadata iscategory and defining a categoryhelps Siri know how to talkabout your intent and how todisplay it in the UI.So, for example, in this case,I'm choosing the Order category,and when I choose Order, Siriwill say something like, "Okay,I ordered it," when I use itwith Siri. And it'll display a buttonconfirmation title like Order.So, we offer several differentcategories, and you shouldchoose the one that matches yourintent's purpose the mostclosely.
Next, you want to fill out yourintent's title and description,and that will be used in all theplaces where people can discoverwhich shortcuts your appsupports.
And then there's the Userconfirmation required checkbox,which determines whether or notwe'll ask the user for aconfirmation before using yourshortcut.So, Siri might say somethinglike, "Are you ready to orderwith Soup Chef?"That's really great for my app,because I want to make sure thatpeople aren't accidentallyordering soup .
So, then, you'll see the intenseparameters.And these define all of theparameters that are passed toyour shortcut. For example, in my case, I havetwo parameters.They are the list of items beingordered and the location todeliver to.Now, parameters support a shortlist of types, and those typesinclude things like string,number, person, and location.But if you're building aparameter that represents anobject that's in your app that'snot on the short list of typesthen you can choose the customtype.Once you've defined yourparameters, you'll want to lookat shortcut types.These define all of the types ofshortcuts that you'd like to besuggested to the user.
Each type includes a particularcombination of parameters thatwill be predicted, and formatsfor how to display the title andsubtitle of each one, filling inthe values for your parameters.So, if your shortcut can't beperformed in the backgroundbecause it needs to launch yourapp when you use it, you shoulduncheck the Supports backgroundexecution checkbox.Now, in some cases, one intentmay have multiple shortcuttypes, where some supportbackground execution and somedon't.Now, in the case of Soup Chef,that's especially relevant,because we can supportbackground execution when boththe items and delivery locationare predicted, because we haveall we need to place an order.But if we add a shortcut typethat only includes deliverylocation, Siri may predict that,and we won't actually haveenough information to place anorder. So, we'll need our app to opento ask the user what location todeliver to, and, in that case,we'll want to not supportbackground execution for thatshortcut type.Now, you should specify shortcuttypes for every variation ofyour shortcut that you thinkwill be useful so that Siri canmake the best predictions.And, for the best experience,you should-- on all the shortcuttypes, you can-- supportbackground execution.Shortcut types that supportbackground execution providemore acceleration to the user,and so they'll actually besuggested more frequently.
You can provide up to 16shortcut types for every intentthat you define.
Now, once your intent isdefined, Xcode willautomatically code generate anintent class and an intenthandling protocol.In my case, we've generated theOrderSoupIntent class and anOrderSoupIntentHandling protocolwith properties that correspondto what I just defined in myintent definition file.Because Xcode is doing codegeneration, it's reallyimportant to consider in whichtargets Xcode is doing this codegeneration, because you don'twant to end up with duplicateinstances of the same classesthat conflict with each other.
So, let's look at the targets inthe target membership section ofthe inspector on my intentdefinition file.
Your intent definition fileshould be included in everytarget in which your intent isused, so you should check thebox under Target Membership.But you'll want to make surethat if you have a framework,you don't do code generation inmultiple targets that areincluded from each other.So, if you have a framework, setthe target membership to onlygenerate intent classes for thatframework by choosing intentclasses and choosing nogenerated classes for everyother target.But if you don't have anyframeworks in your app becauseyou haven't separated your appinto frameworks yet, you shouldcheck the target for everysingle target.
And that's how you define customintents in Xcode.
Once you've defined your customintent, it's really easy todonate it.All you have to do isinstantiate your intent objectand then populate its parametersand create and donate anINInteraction object.
Make sure to do this every timethe user performs the equivalentof your shortcut in your app.In this case, every time theuser orders soup, I want todonate this intent, becausethat's going to help Siri learnwhen is the best time to predictit?So, all that's left, now thatwe've defined our custom intent,is to handle it.And, just like withNSUserActivity, you shouldimplement thecontinueUserActivity method inyour app delegate in order tohandle your intent.So, when an intent is opened inyour app, it's passed in as anNSUserActivity object, whoseactivity type is the name of theintent class that you generatedearlier. In this case, it'sOrderSoupIntent.
But if you only implementcontinueUserActivity, yourshortcut will open your appevery time.It won't run in the background,or work inline in Siri, orsupport things like custom voiceresponses.So, for the best experience, youwant to create an extension tohandle your shortcut in thebackground.
And to do that, create a newtarget in your Xcode project andchoose the Intents Extensiontemplate.Make your intent handler conformto the intent handling protocol.In this case, it'sOrderSoupIntent handling andthen implement these methods,which are confirm and handle.Now, note that unliketraditional SiriKit, you don'tneed to implement any resolvemethods, because your intent isready to go without anycustomization needed or anyfollow-ups from the user.So, in confirm, you should checkall of the values of theproperties of your intent tomake sure that they're valid.And, if they're not, you shouldreturn an error code if youdon't think you'll be able to handle that intent.And then you should handle,actually perform your shortcut.So, in this case, that meansactually placing an order forthe soup.And then you return a responseobject that indicates theoutcome, such as success.
Again, you should implement anintents extension for everyshortcut that can run in thebackground, because then they'llrun right in line inside ofSiri, on the lock screen, insearch, in the Shortcuts app,and on the Siri Watch Face,without having to launch yourapp.The most valuable shortcuts arethe ones that run in thebackground, but you can alsobuild a lot of great othershortcuts.And keep in mind that, even ifyou implement an intentsextension, you should alwaysimplement continueUserActivity,because the user will have theopportunity to open the shortcutin your app from Siri, forexample, by tapping on the cardin Siri that shows your apps'custom UI.So, there's one more thing thatI want to tell you about, whichis INRelevantShortcut.Now, INRelevantShortcut is theway to expose shortcuts to theSiri Watch Face, and you do itjust by providingINRelevantShortcut objects thatinclude your intents or useractivities.
You can, optionally, includerelevance information in yourrelevant shortcuts, which is ahint to the Siri Watch Face asto when your shortcuts will berelevant and when's the besttime to show your shortcut?Now, the really cool thing aboutINRelevantShortcut is that itworks even if you don't have aWatch app.So, you can actually exposerelevant shortcuts from your iOSapps, and if they run in thebackground, they'll appear righton the Siri Watch Face.Okay, now that we've exploredall the ways that Shortcuts canbe used and how to adopt theAPIs, I'm going to turn it overto my colleague Willem who'sgoing to give you a great demoof how to adopt shortcuts inXcode.
Willem?Thanks, Ari.
I'm so excited to be the firstone to demo adopting Shortcuts.Before I dive into Xcode, let meshow you the app we've beenworking on.As Ari mentioned, we've beenworking on a soup-ordering appcalled Soup Chef.Let me show it to you.
So, this is Soup Chef.When I launch the app, I'mpresented with my order history.Since I haven't ordered anythingyet, this is still empty.I can place a new order bytapping the plus button.
This presents me with the soupmenu, where you can see theavailable soups I can order.Let's order a tomato soup.Next, I can specify the quantityand options for my soup.I'll order a single tomato soupwith red pepper, and when I'mready to order, I tap the PlaceOrder button.
I'm brought back to the orderhistory where you can now seethe order that I just placed.I can tap the order to see moredetails about a specific order.
This view has an associated useractivity.I think it would be pretty coolto suggest this to our users,since our users like toreminisce about the good soupsthey've ordered in the past.And it would be great if thiscould be suggested to them.So, let's go to Xcode and seehow we can do that.
Here, I'm looking at theviewController for the orderdetail view.
I'm creating a user activity,and I'm setting therequiredUserInfoKeys.I'm also making sure that it'sEligibleForSearch.
For it to be suggested, I alsoneed to make it eligible forprediction.
And that's it.Let's try it out.
First, I need to make sure thatI donate the user activity, soI'll go back to the view.That should be enough.Now we want to make sure thatthe donation actually happened,and, to do that, we added twonew developer settings that makeit super easy to see a recentdonations in search and on thelock screen.To enable it, I go to Settings,and I scroll down to thedeveloper section.
At the bottom, there are two newtoggles, Display RecentShortcuts and Display Donationson Lock Screen.Let's enable both.
I can now go back to the homescreen and pull down to go tosearch, and I see the donationthat I just did.
Great.
I can tap it, and the app islaunched with that useractivity, and I'm back to theorder that I was just donated.Great. So, this is pretty good,but I think we can do a lotmore.Since the main capability of ourapp is ordering soup, it wouldbe great if this could besuggested to our users.And I want users to be able todo that without having to launchthe app.So, I'll implement it using anintent.There isn't a built-in souporder intent, but now in iOS 12,I can create a custom intent, soI'll do that.
And to start by creating anintent definition file, I'll goto File, View.File and select the SiriKit andthen definition file.
Click Next.
Now I can give it a name.I'll keep it to Intents, andI'll put it in the Resourcesgroup.All right, and I'm ready.I click Create.
I'm presented with our intentdefinition file and our newIntent Editor.
Before I add the intent, I'llmake sure to include the intentdefinition file in the righttargets.As Ari said, we need to add itto all the targets where theintents are used.So, I'll add it to our sharedframework, and, since we'reusing a shared framework, Idon't want it to generate go forapp target.So, in the dropdown, next to theapp target, I'll select Nogenerated classes.
Now that that's done, we'reready to add our intent.I'll click the plus button inthe lower left corner and selectNew Intent.
I'll give it a name OrderSoup.
Next, I'll select the category.In this case, it's an orderintent.Fill out the title, OrderSoup,and the description, Order asoup from Soup Chef.
Since this involves a real-worldtransaction, I want to use it toconfirm this order beforeplacing it, so I'll select Userconfirmation required.
Next, let's define theparameters.I'm going to define threeparameters, one for the soup,one for the quantity, and onefor the options that the userselects.I'll start with soup.I click the plus button in theparameter section and fill outthe name, soup.Since soup is a custom object ofour app, I'm going to select thecustom type.Next, I'll add quantity.I click plus again, fill out thename, and this is going to be aninteger.
Next, options.
Again, options is a customobject of our app, so I'll usethe custom type.
And since the user can selectmultiple options, I'll alsocheck the array checkbox.
Finally, we need to define theshortcut types. At this point, I'm just going todefine a single shortcut typethat contains all theparameters.
I'll click the plus button inthe shortcut type section andselect the parameters I want toinclude in the shortcut type, soI'll select soup, quantity andoptions.When I'm ready, I click the AddShortcut Type button.
I fill out the title Order, andthen I'm going to insert thequantity and the soup withoptions, and I'll leave thesubtitle empty, because I'vealready conveyed all theinformation I need to in thetitle. I'll also leave Supportbackground execution checked,because I want the user to runthis intent in the background.So, we just defined our firstintent.Let's start using it.I'll start by adding two helpermethods to our order object tomake it easier to convertbetween it and the intent.
I'll go to the order class and,at the bottom, I'll add an orderextension.It contains a computer variablethat returns an intent.In it, I create the intent.I set the soup quantity andoptions, and I return theintent.
Extension also defines a newinitializer that dates anintent.In it, I extract the soup,quantity, and options, and thenI initialize the order withthose values.
Great, this will be veryhelpful.
Next, we need to make sure thatwe donate the intent every timethe user places an order.So, I'll go to the soup orderdata manager, and, in theplaceOrder method, I'll add ourdonation logic.
I create an INInteraction thatcontains the intent of theorder, and then I just donatethat interaction, and that's it.
Finally, we need to handle theintent.I'll start by adding support inthe app itself, so I'll go tothe AppDelegate, and, in thecontinueUserActivity, I'll addsupport for it.I check if the activityType ofthe userActivity is equal to theclass name of the intent that Iwant to handle.If that's the case, I extractthe intent from theuserActivity, and I generate anorder with it.Finally, I present the orderview.So, since we're launching theapp, I'm assuming that the userdoesn't want to immediatelyplace the order but wants tomake some customizations beforeplacing it, so that's why I'mpresenting the order viewinstead.And, finally, let's add supportwith an intents extension so theuser can run this intent in thebackground.
I'll need to add an intentsextension first, so I'll go toFile, View, Target and selectthe Intents Extension target.
I'll give it a name,SoupChefIntents, and I clickFinish.
Since I've added a new targetwhere I'll use the intents, Ineed to make sure that theintent definition file isincluded in that target.So, I go back to the intentdefinition file and add it tothat target.Again, I don't want to generatecode in that target, so, in thedropdown, I'll select Nogenerated classes.
I also want the extension tohave access to the same data asthe app, so I'll add it to thesame app group.
In the Project Settings, Iselect the intents target and inthe capability step, I'll add itto the same app group.Great. Now, we're ready toimplement the intent handlerthat was created with thistarget.
First, I'll import our sharedframework, SoupKit .
Since we're going to handle theOrderSoupIntent, this intenthandler needs to conform to theOrderSoupIntentHandlingprotocol.
This was generated as part ofour intent.
This protocol has one requiredmethod, the handle method.Let's implement it.In the handle method, I get anintent.I create an order from thatintent, and, if that succeeds, Iplace the order, and I call thecompletion with an intentresponse with a success code.If I'm unable to create an orderfrom the intent, I callcompletion with an intentresponse with a failure code.And that's it.I've just added support for anew intent in my app.Let's try it out.
First, I'll need to donate theintent. So, I'll place another order.Click the plus button and thistime I'm going to order a clamchowder with croutons, and I'llplace the order.
Now, if we go back to the homescreen and pull down, I see mydonated intent.Great.I can tap it, and I'm presentedwith a shortcut view and theorder button.If I tap the order button, theorder will be placed in thebackground, and it's ordered.
I can go back to the app and seeif it was actually ordered, and,yeah, there is a new order in myapp.Great, so easy.I can also, instead of tappingthe order button, tap theshortcut view, itself, whichwill launch the app with theshortcut, and, as I implementedit, it shows the order view,where I can customize the order.So, I'll add cheese, too.Who knows?And I'll place the order.
Great. Finally, let's add theshortcut to Siri.
I'll go to Settings, and Iscroll up to the Siri andsearch.
Here I can select the shortcutthat I want to add to Siri.In this case, I'll add the orderone clam chowder with croutons.
When I tap the record button, Ican say the phrase I want toassociate with the shortcut.Soup time.
Now, they got it.Let's take a step back and lookat what we just did.We started by making anNSUserActivity that was alreadyimplemented in our app eligiblefor prediction.This allowed it to be suggestedand is a really easy way toexpose the content of your app.
Next, we defined a customintent.This is really the best way torepresent a piece of keyfunctionality of your app.In our case, that was ordering asoup. After defining the intent, wemade sure that we donate theintent every time the userplaced an order inside of theapp. And, finally, we handled theintent, both in an extension tosupport background execution andin the app itself so the usercan launch the app with theshortcut.
So, now that we've seen how youcan adopt shortcuts, let's takea look at how those shortcutsare suggested and what you cando to make sure your users seethe best possible suggestions.Every time a user performs anaction in your app and your appdonates this, the system willlook at the time, location, andother signals.
For a time, we consider, amongother things, the time of dayand the day of the week.Well, for the location, we lookat the overall location of theuser and see if it's asignificant location for thatuser.Let's see how the system nowuses these to make a suggestion.
Here, we'll just consider thetime.Monday, at lunch, I order atomato soup with croutons.
That evening, I don't feel likecroutons, so I order a tomatowith red pepper instead.Next day at lunch, I, again,order a tomato soup withcroutons.
I keep doing this throughout theweek, and, on Friday, at lunch,Siri might try to find asuggestion for me.
It will look at my past behaviorand try to find a pattern in it.And since it's lunchtime, and Iusually order a tomato soup withcroutons at lunchtime, Sirimight notice this and suggestthis to me, which is great.It's exactly what I wanted.
So, this is all pretty highlevel, so let's take a look athow it actually works, startingwith NSUserActivity.Imagine a user activity for theplace order screen in Soup Chef.The user info dictionary couldcontain three keys, soup,quantity, and scroll position.The last one is there, so, inHandoff, you can bring the userback to the exact position theywere last in.
Let's take a look at how thiscan be suggested to the user.We start by donating a useractivity where the soup istomato, the quantity is 1, andthe scroll position is 79points.Next, we donate a similar useractivity, but now scrollposition is changed to 110points.
We keep doing this, and, at somepoint, Siri will try to find asuggestion again.It will look at past behaviorand try to find a pattern ofequal user activities.But since the scroll position isso inconsistent over time, itmight not be able to find asuggestion.
So, how can we fix this?We can use therequiredUserInfoKeys.
RequiredUserInfoKeys is anexisting property of a useractivity.It represents the minimal amountof information that is necessaryto restore the app to the statethat the user activityrepresents.And for suggestions it will beused to determine which keys ofthe user info dictionary will beused to compare when looking forpatterns.
Let's apply this to a previousexample.
Now we specify thatrequiredUserInfoKeys are soupand quantity.Again, we donate the useractivity where the soup istomato, the quantity is 1, andthe scroll position is 79points. But now the scroll position willbe ignored.
Next, we donate somethingsimilar, and, again, the scrollposition is ignored.
We keep doing this, and, at somepoint, Siri will try suggestionagain.
Now, I will look back and try tofind a pattern of equal useractivities.And since it's no longerconsidering the scroll position,it might be able to say, "AnNSUserActivity with soup tomatoand quantity 1 is a goodsuggestion for this user."So, as you just saw, it's reallyimportant to specify the rightset of keys as being required.Otherwise, your users might notget any suggestions at all.So, that's how it worked foruser activity.
Intents work similarly but offeryou a lot more flexibility.
The main signal for intents arethe shortcut types that youdefine.
Each shortcut type defines acombination of parameters thatis valid for suggestion.It's similar to therequiredUserInfoKeys, butinstead of having just one set,you can define multiple.Let's apply this to our SoupChef app.Earlier, I defined anOrderSoupIntent with threeparameters, soup, quantity, andoptions.At the time, I only defined asingle shortcut type thatcombined all of theseparameters, but, ideally, youwould define more shortcuttypes, since that gives moreoptions to the system to findpatterns in your user'sbehavior.So, now I'll define three.
One shortcut type that combinessoup and quantity, one thatcombines soup and options, andone that combines all threeparameters.
Let's apply this to anotherexample.
Again, I start on Monday, atlunch, by ordering a tomato soupwith croutons.
The Soup Chef app donates thisto the system, and the systemwill split us up into all thepossible combinations based onthe shortcut types that I justdefined.That evening, I order a tomatosoup with red pepper.Again, it gets donated, and itwill be split up in all thepossible combinations.
Next day, at lunch, I order atomato soup with croutons.It gets donated and split up.I keep doing this throughout theweek, and, on Friday, at lunch,Siri might try to find asuggestion.
It might see that I often ordera single tomato soup.
But since it's lunchtime, italso can see that, at lunchtime,usually order a tomato soup withcroutons.
Since that is a more specificshortcut, it will end uppreferring to suggest that.So, I might get a suggestion toorder a tomato soup withcroutons.Great. So, that's howsuggestions are made.
Let's now take a look at how tomake sure those suggestions aregood, and it all starts frommaking good donations.A good donation should besomething that is likely to berepeated.
For user activity, there couldbe some content they might lookat often.Or, for an intent, there couldbe an action the user would takeregularly.You should make sure that thepayload of what you're donatingis consistent across all yourdonations, since that is whatwill be compared when lookingfor patterns.A good donation should also notinclude a timestamp, since thatmight not longer be relevant bythe time this donation would besuggested.
For instance, a shortcut thatshows appointments for aspecific day is probably notthat useful, since, if you seethat the next day or later,you're probably no longerinterested in the meetings ofthat specific day.
A shortcut with a relative time,however, is a lot more useful.You should also make sure thatyou donate exactly once for eachuser action, even if that useraction involves multiple actionsinside your app.Finally, selecting the correctparameters of your intent isalso important.So, let's take a look at twopossible types, starting withenums.You can define enums in yourintent definition file next toyour intents, and use it as thetypes of your parameters.We recommend that you use enumswhenever the values for aparameter are bounded.For instance, if you would add asize parameter to a order soupintent, it might make sense tomake that an enum, since thepossible sizes are probably justsmall, medium, and large.
Using an enum will lead tobetter suggestions and clearertitles and subtitles for yourusers.
To learn more about how enumsare used to generate titles andsubtitles, I recommend that youwatch the localization session.Another type you can use is thecustom type.
Using a custom type will resultin an INObject and yourgenerated intent code.
An INObject combines anidentifier with a displaystring.The identifier can be used torefer to an object internal toyour app, while the displaystring contains the userreadable representation of thatobject.
That way both your users andyour app always understands whatthe value of this parameter is.
Finally, using an INObject alsoprevents the possible dependencybetween parameters.Let me illustrate that.There are two ways to representthe combination of an identifierwith a display string.You could add two parameters toyour intent, one for theidentifier, one for the displaystring, or you could add asingle parameter using theINObject.With the first approach, youhave a dependency.Since the display string dependson the object as referenced bythe identifier, we discouragehaving these dependencies asthey could cause issues when wesuggest this intent later.A good shortcut should also havean understandable title,subtitle, and image.It should represent what willhappen when the user taps theshortcut, since it will be theonly thing the user will seebefore interacting with it.And, of course, you want to testyour shortcuts to make sure thatthey look right and that theybehave as expected.There are a couple of ways to dothat. As I showed you earlier, weadded two new developer settingsthat allow you to see yourrecent donations on search andon the lock screen, instead ofyour regular Siri suggestions.
By enabling these, you can seewhat your users will see whenthose donations would besuggested, and you can tryinteracting with them to makesure that they behave asexpected.Another way to test yourshortcuts is by adding them toSiri.An easy way to test them then isby editing the Xcode scheme toautomatically invoke Siriwithout constantly having to saythe phrase.
In the scheme editor of anintents extension there is theSiri Intent Query field that youcan use to provide the utteranceto invoke Siri with.And, finally, you can create acustom shortcut in the Shortcutsapp that uses your shortcut.
This allows you to test thebehavior of your shortcut whenit's chained together with othershortcuts or steps from theShortcuts app.
So, now that we've seen what agood shortcut donation is andhow does donation get suggestedto your users, let's take a lookat a couple of privacyconsiderations and how you canmake sure your user are neverupset by what is suggested tothem.
Your users expect that when theydelete something from withinyour app that it's deleted forgood. It's important to honor this soyou maintain your users' trustand your so users aren'tpresented with suggestions forthings that are not relevant tothem anymore.
So, if you donate shortcuts thatcontain information that theuser can delete, you should makesure to delete those donationsat the appropriate time.Let's take a look at how todelete donations, starting withNSUserActivity.
There are two ways to delete adonated user activity.
If you use Spotlight indexingand you set therelatedUniqueIdentifier, thendeleting the content fromSpotlight will automaticallydelete the donated useractivity.
Just set therelatedUniqueIdentifier on thecontentAttributeSet to theidentifier of the searchableitem that it matches with.
Then, when that searchable itemwould be deleted, it wouldautomatically delete the useractivity.If you don't use Spotlightindexing, you can use thepersistent identifier propertyon NSUserActivity.This is a new property that youcan set so you can keep track ofyour user activities and deletethem at the appropriate time.
To use it, just set thepersistentIdentifier propertybefore donating user activity.
Then, when you want to deleteit, you calldeleteSavedUserActivities withthe identifiers that you want todelete.You can also delete all yourdonated user activities.
For instance, when your userlogs out, you can do that bycallingdeleteAllSavedUserActivities.
Intents have an existing API,which is similar to this newuser activity API.
Since you donate intents throughINInteraction the leading anddonated intent also happensthrough INInteraction.
An INInteraction has anidentifier and a groupidentifier property that you canset and then later use to deleteone or more donatedinteractions.Just set the identifier and orgroup identifier before donatingthe interaction.
Then, when you want to deleteit, you call delete with anarray of the identifiers thatyou want to delete.
You can also delete all donatedintents with a shared groupidentifier by calling deletewith the group identifier.And, finally, just likeNSUserActivity, there is a wayto delete all your donatedintents by calling deleteAll onINInteraction.
Please make sure to delete yourdonations at the appropriatetime.This will give your users thebest possible suggestions andnever make them wonder whythey're seeing suggestions forthings that are no longerrelevant to them.
So, now that we've looked atdifferent things to considerwhen creating and donatingshortcuts, let's end by brieflylooking at what you can use tocreate the best possible mediashortcuts.We created a new intent thatworks great with Shortcuts.This intent is calledINPlayMediaIntent and allows youto create and donate shortcutsto play audio or video content.
When handling this intent inyour extension, you can chooseto have it handled by your appin the background .This allows you to start audioplayback straight from your app.
Besides being suggested insearch and on the lock screen,shortcuts with this intent willalso be suggested in theplayback controls on the lockscreen when the user connectstheir headphones, making it eveneasier for them to startlistening to your content.
And, finally, shortcuts withthis intent work great on theHomePod.
Just add a play media shortcutto Siri on your iPhone andinvoke it on your HomePod.The audio will start playingfrom your phone through HomePod.
We also created a new API thatallows you tell the system aboutnew content they might beinterested in.
This is great for periodicalcontent, where the content thatyou would want to be suggestedto your users isn't somethingthey've listened to or watchedbefore.
So, those are a couple of thingsthat we have added to make greatmedia shortcuts.
Now, let's summarize what wejust talked about.
Shortcuts enable powerful, newexperiences with your apps.It provides new ways to engageyour users by exposing your appthroughout the system in avariety of places.So, just search the lock screen,the Siri Watch Face on yourApple Watch, and in Siri itself.You can also use it in the newshortcuts app.
You can adopt shortcuts by usingNSUserActivity, which is areally easy way to expose thecontent of your app.
Or you can use intents whichprovides you with a deeperintegration in the system andcan unlock entirely newexperiences for your users.For more information, oursession is 211, and you can findour page on developer.apple.com.You can also find us in the labsthroughout the week.Thank you so much for coming.And we can't wait to see whatshortcuts you'll create.Enjoy the rest of yourconference.[ Applause ]
[8]ページ先頭