I am implementing AppIntent into my application as follows:
// MARK: - SceneDelegate
var window: UIWindow?
private var observer: NSObjectProtocol?
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
guard let windowScene = (scene as? UIWindowScene) else { return }
// Setup window
window = UIWindow(windowScene: windowScene)
let viewController = ViewController()
window?.rootViewController = viewController
window?.makeKeyAndVisible()
setupUserDefaultsObserver()
checkShortcutLaunch()
}
private func setupUserDefaultsObserver() {
// use NotificationCenter to receive notifications.
NotificationCenter.default.addObserver(
forName: NSNotification.Name("ShortcutTriggered"),
object: nil,
queue: .main
) { notification in
if let userInfo = notification.userInfo,
let appName = userInfo["appName"] as? String {
print("📱 Notification received - app is launched: \(appName)")
}
}
}
private func checkShortcutLaunch() {
if let appName = UserDefaults.standard.string(forKey: "shortcutAppName") {
print("🚀 App is opened from a Shortcut with the app name: \(appName)")
}
}
func sceneDidDisconnect(_ scene: UIScene) {
if let observer = observer {
NotificationCenter.default.removeObserver(observer)
}
}
}
// MARK: - App Intent
struct StartAppIntent: AppIntent {
static var title: LocalizedStringResource = "Start App"
static var description = IntentDescription("Launch the application with the command")
static var openAppWhenRun: Bool = true
@MainActor
func perform() async throws -> some IntentResult {
UserDefaults.standard.set("appName", forKey: "shortcutAppName")
UserDefaults.standard.set(Date(), forKey: "shortcutTimestamp")
return .result()
}
}
// MARK: - App Shortcuts Provider
struct AppShortcutsProvider: AppShortcutsProvider {
static var appShortcuts: [AppShortcut] {
AppShortcut(
intent: StartAppIntent(),
phrases: [
"let start \(.applicationName)",
],
shortTitle: "Start App",
systemImageName: "play.circle.fill"
)
}
}
the app works fine when starting with shortcut. but when starting with siri it seems like the log is not printed out, i tried adding a code that shows a dialog when receiving a notification from userdefault but it still shows the dialog, it seems like the problem here is when starting with siri there is a problem with printing the log.
I tried sleep 0.5s in the perform function and the log was printed out normally
try? await Task.sleep(nanoseconds: 500_000_000) // 0.5 seconds
I have consulted some topics and they said that when using Siri, Intent is running completely separately and only returns the result to Siri, never entering the Main App. But when set openAppWhenRun to true, it must enter the main app, right? Is there any way to find the cause and completely fix this problem?