Siri Shortcut in iOS App
In iOS 12 Apple provides the capability to add the Siri within the App where you can execute or perform a task by informing to Siri. Here we are taking the example of showing the cart data using
Siri.
Cart Data means : It is viewcontroller class which show the cart item .
Siri Shortcut is basically a voice command where you have to registered first after that when the siri detect the same voice command then it will automatically execute your task.
For this Follows this Steps:
1: Create a Unique ID for Siri Shortcut :
Here we have taken the bundle ID of Application :
1 2 3 4 5 6 7 |
func getBundleID()->String{ if let data = Bundle.main.bundleIdentifier{ return data }else{ return "com.siri.ios" } } |
2: Create a class for Siri :
Here we have created the CartShortcut Class , it will return the Siri Shortcut Object.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 |
// /** ShowMyCartShortCut @Category Webkul @author Webkul <support@webkul.com> FileName: CartShortcut.swift Copyright (c) 2010-2018 Webkul Software Private Limited (https://webkul.com) @license https://store.webkul.com/license.html */ import Foundation import UIKit import Intents import CoreSpotlight import MobileCoreServices public let kNewArticleActivityType = NetworkManager.sharedInstance.getBundleID() @available(iOS 12.0, *) public class CartShortcut{ public let title: String public let content: String public let published: Bool public static func newArticleShortcut(with thumbnail: UIImage?) -> NSUserActivity { let activity = NSUserActivity(activityType: kNewArticleActivityType) activity.persistentIdentifier = NSUserActivityPersistentIdentifier(kNewArticleActivityType) activity.isEligibleForSearch = true activity.isEligibleForPrediction = true let attributes = CSSearchableItemAttributeSet(itemContentType: kUTTypeItem as String) // Title activity.title = "welocometo".localised+" "+"applicationname".localised // Subtitle attributes.contentDescription = "You can view cart details" // Thumbnail attributes.thumbnailData = thumbnail?.jpegData(compressionQuality: 1.0) // Suggested Phrase activity.suggestedInvocationPhrase = "Show My Cart" activity.contentAttributeSet = attributes return activity } // MARK: - Init public init(title: String, content: String, published: Bool) { self.title = title self.content = content self.published = published } } |
3: Now Go to Class where you have to give this feature , I have given this facility in my Setting class of App.
a: take UIButton , name as Siri Shortcut or you can add the image.
b: take a UITableView where you can show the previous & current phrase of Siri Shortcut . you can edit or delete this phrase as well.
c:Write the Function of this class.
1 2 3 4 5 6 7 8 9 10 11 12 |
import UIKit import IntentsUI @available(iOS 12.0, *) class CartSiriShortcutController: UIViewController, INUIAddVoiceShortcutViewControllerDelegate,INUIEditVoiceShortcutViewControllerDelegate { @IBOutlet var tableView: UITableView! var voiceShortcut = [INVoiceShortcut]() } |
Note: Here we have taken the delegate of Siri Shortcut for Add & edit case
d: First we will check weather previous phrases are available or not , if available then show to user so they can edit or delete this.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 |
override func viewDidLoad() { super.viewDidLoad() self.getAllShortCut() } @available(iOS 12.0, *) extension CartSiriShortcutController:UITableViewDelegate,UITableViewDataSource{ func getAllShortCut(){ INVoiceShortcutCenter.shared.getAllVoiceShortcuts { (voiceShortcutsFromCenter, error) in if let voiceShortcutsFromCenter = voiceShortcutsFromCenter { self.voiceShortcut = voiceShortcutsFromCenter print("sfnsjfs",voiceShortcutsFromCenter) DispatchQueue.main.async{ self.tableView.delegate = self self.tableView.dataSource = self self.tableView.reloadData() } } else { if let error = error as NSError? { print("Failed to fetch voice shortcuts with error: %@") } } } } func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { if self.voiceShortcut .count > 0{ return "availablephrase".localised }else{ return "" } } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.voiceShortcut.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "settingcell", for: indexPath) cell.textLabel?.text = "\"\(self.voiceShortcut[indexPath.row].invocationPhrase)\"" cell.detailTextLabel?.text = "You can edit or delete this phrase"; return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let vc = INUIEditVoiceShortcutViewController(voiceShortcut:self.voiceShortcut[indexPath.row]) vc.delegate = self self.present(vc, animated: true, completion: nil) } } |
Note: It will show all the available phrases on TableView.
here you can see, on click of any Cell we are calling edit shortcut class so that it will help to edit or delete this phrase.
List of available phrase:
On Click on that:
Now we are aware about the available phrase edit & delete .
4: Now its time to Add the siri shortcut functionality.
create a Outlet of Button then write this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
@IBAction func siriShortCustClick(_ sender: UIButton) { let newArticleActivity = CartShortcut.newArticleShortcut(with: UIImage(named: "ic_cart")) let shortcut = INShortcut(userActivity: newArticleActivity) let vc = INUIAddVoiceShortcutViewController(shortcut: shortcut) vc.delegate = self present(vc, animated: true, completion: nil) } func addVoiceShortcutViewController(_ controller: INUIAddVoiceShortcutViewController, didFinishWith voiceShortcut: INVoiceShortcut?, error: Error?) { self.getAllShortCut() dismiss(animated: true, completion: nil) } func addVoiceShortcutViewControllerDidCancel(_ controller: INUIAddVoiceShortcutViewController) { dismiss(animated: true, completion: nil) } // for handling Editing the shortcut func editVoiceShortcutViewController(_ controller: INUIEditVoiceShortcutViewController, didUpdate voiceShortcut: INVoiceShortcut?, error: Error?) { self.getAllShortCut() controller.dismiss(animated: true, completion: nil) } func editVoiceShortcutViewController(_ controller: INUIEditVoiceShortcutViewController, didDeleteVoiceShortcutWithIdentifier deletedVoiceShortcutIdentifier: UUID){ self.getAllShortCut() controller.dismiss(animated: true, completion: nil) } func editVoiceShortcutViewControllerDidCancel(_ controller: INUIEditVoiceShortcutViewController) { controller.dismiss(animated: true, completion: nil) } |
Note: Now you can add the new siri shortcut in your App.
5: Lets go to handle this action.
when you add all the shortcut in your App then we have to handle this ,by which we can perform desired work for this.
a: Go to Appdelegate.swift class & write this.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
extension AppDelegate{ func application(_ application: UIApplication, willContinueUserActivityWithType userActivityType: String) -> Bool { if userActivityType == kNewArticleActivityType { return true } return false } func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([UIUserActivityRestoring]?) -> Void) -> Bool { if userActivity.activityType == kNewArticleActivityType { handleUserActivity() return true } return false } private func handleUserActivity() { NotificationCenter.default.post(name: NSNotification.Name(rawValue: "sirishortcutforcart"), object: nil, userInfo: nil) } } |
it will match with siri shortcut ID that you have given on creation .
here We have managed through Notification Center so it will inform when it will be execute.