Integrating Siri Shortcuts into SwiftUI Apps with App Intents

0
2
Integrating Siri Shortcuts into SwiftUI Apps with App Intents


Have you ever ever puzzled the best way to make your app’s options accessible from the built-in Shortcuts app on iOS? That’s what the App Intents framework is designed for. Launched in iOS 16 and macOS Ventura, the framework has been round for over two years. It offers builders with a strong technique to outline actions that customers can set off by means of Shortcuts. With App Intents, your app can combine seamlessly with the Shortcuts app, Siri, and even system-wide Highlight search.

On this tutorial, we’ll discover the best way to use the App Intents framework to convey your app’s performance into Shortcuts by creating an App Shortcut. Utilizing the Ask Me Something app as our instance, we’ll stroll by means of the method of letting customers ask questions proper from Shortcuts.

This tutorial assumes you are conversant in the Ask Me Something app from our Basis Fashions tutorial. If you have not learn it but, please evaluate that tutorial first.

Utilizing App Intents

The Ask Me Something app permits customers to ask questions after which it offers solutions utilizing the on-device LLM. What we’re going to do is to show this function to the Shortcuts app. To try this, all it is advisable to do is to create a brand new Struct and undertake the App Intents framework.

Let’s create a brand new file named AskQuestionIntent within the AskMeAnything venture and replace its content material like under:

import SwiftUI
import AppIntents

struct AskQuestionIntent: AppIntent {
    static var title: LocalizedStringResource = "Ask Query"
    static var description = IntentDescription("Ask a query to get an AI-powered reply")
    
    static let supportedModes: IntentModes = .foreground
    
    @Parameter(title: "Query", description: "The query you wish to ask")
    var query: String
    
    @AppStorage("incomingQuestion") var storedQuestion: String = ""
    
    init() {}
    
    init(query: String) {
        self.query = query
    }
    
    func carry out() async throws -> some IntentResult {
        storedQuestion = query
        
        return .outcome()
    }
}

The code above defines a struct known as AskQuestionIntent, which is an App Intent utilizing the AppIntents framework. An App Intent is mainly a approach to your app to “speak” to the Shortcuts app, Siri, or Highlight. Right here, the intent’s job is to let a consumer ask a query and get an AI-powered reply.

On the high, we now have two static properties: title and description. These are what the Shortcuts app or Siri will present the consumer once they take a look at this intent.

The supportedModes property specifies that this intent can solely run within the foreground, which means the app will open when the shortcut is executed.

The @Parameter property wrapper defines the enter the consumer wants to offer. On this case, it is a query string. When somebody makes use of this shortcut, they will be prompted to kind or say this query.

The @AppStorage("incomingQuestion") property is a handy technique to persist the offered query in UserDefaults, making it accessible to different components of the app.

Lastly, the carry out() operate is the place the intent truly does its work. On this instance, it simply takes the query from the parameter and saves it into storedQuestion. Then it returns a .outcome() to inform the system it’s completed. You’re not doing the AI name instantly right here — simply passing the query into your app so it may well deal with it nevertheless it needs.

Dealing with the Shortcut

Now that the shortcut is prepared, executing the “Ask Query” shortcut will robotically launch the app. To deal with this habits, we have to make a small replace to ContentView.

First, declare a variable to retrieve the query offered by the shortcut like this:

@AppStorage("incomingQuestion") non-public var incomingQuestion: String = ""

Subsequent, connect the onChange modifier to the scroll view:

ScrollView {

...


}
.onChange(of: incomingQuestion) { _, newQuestion in
    if !newQuestion.isEmpty {
        query = newQuestion
        incomingQuestion = ""
        
        Activity {
            await generateAnswer()
        }
    }
}

Within the code above, we connect an .onChange modifier to the ScrollView so the view can reply every time the incomingQuestionvalue is up to date. Contained in the closure, we examine whether or not a brand new query has been obtained from the shortcut. In that case, we set off the generateAnswer() technique, which sends the query to the on-device LLM for processing and returns an AI-generated reply.

Including a Preconfigured Shortcut

In essence, that is the way you create a shortcut that connects on to your app. If you happen to’ve explored the Shortcuts app earlier than, you’ve most likely seen that many apps already present preconfigured shortcuts. As an example, the Calendar app contains ready-made shortcuts for creating and managing occasions.

Preconfigured app shortcuts

With the App Intents framework, including these preconfigured shortcuts to your personal app is easy. They can be utilized instantly within the Shortcuts app or triggered hands-free with Siri. Constructing on the AskQuestionIntent we outlined earlier, we will now create a corresponding shortcut so customers can set off it extra simply. For instance, right here’s how we might outline an “Ask Query” shortcut:

struct AskQuestionShortcut: AppShortcutsProvider {
    static var appShortcuts: [AppShortcut] {
        AppShortcut(
            intent: AskQuestionIntent(),
            phrases: [
                "Ask (.applicationName) a question",
                "Ask (.applicationName) about (.applicationName)",
                "Get answer from (.applicationName)",
                "Use (.applicationName)"
            ],
            shortTitle: "Ask Query",
            systemImageName: "questionmark.bubble"
        )
    }
}

The AskQuestionShortcut adopts the AppShortcutsProvider protocol, which is how we inform the system what shortcuts our app helps. Inside, we outline a single shortcut known as “Ask Query,” which is tied to our AskQuestionIntent. We additionally present a set of instance phrases that customers may say to Siri, resembling “Ask [App Name] a query” or “Get reply from [App Name].”

Lastly, we give the shortcut a brief title and a system picture identify so it’s visually recognizable contained in the Shortcuts app. As soon as this code is in place, the system robotically registers it, and customers will see the shortcut prepared to make use of—no further setup required.

Testing the Shortcut

Shortcuts in Shortcuts app and Spotlight Search

To provide the shortcut a attempt, construct and run the app on both the simulator or a bodily iOS gadget. As soon as the app has launched at the least as soon as, return to the House Display screen and open the Shortcuts app. It’s best to now discover the “Ask Query” shortcut we simply created, prepared so that you can use.

The brand new shortcut not solely seems within the Shortcuts app however can also be accessible in Highlight search.

While you run the “Ask Query” shortcut, it ought to robotically immediate you for query. When you kind your query and faucet Executed, it brings up the app and present you the reply.

shortcut-demo-homescreen.png

Abstract

On this tutorial, we explored the best way to use the App Intents framework to show your app’s performance to the Shortcuts app and Siri. We walked by means of creating an AppIntent to deal with consumer enter, defining a preconfigured shortcut, and testing it proper contained in the Shortcuts app. With this setup, customers can now ask inquiries to the Ask Me Something app instantly from Shortcuts or through Siri, making the expertise quicker and extra handy.

Within the subsequent tutorial, we’ll take it a step additional by exhibiting you the best way to show the AI’s reply in a Dwell Exercise. It will let customers see their responses in actual time, proper on the Lock Display screen or within the Dynamic Island—with out even opening the app.

LEAVE A REPLY

Please enter your comment!
Please enter your name here