클라이언트

[iOS] Siri Shortcuts 구현 방법과 동작 원리

애기공룡훈련병 2025. 2. 19. 12:15
반응형

Siri Shortcuts란?

Siri Shortcuts는 사용자가 자주 수행하는 작업을 자동화하고, 음성 명령을 통해 쉽게 실행할 수 있도록 도와주는 기능입니다. iOS 12에서 처음 도입된 Siri Shortcuts는 앱의 특정 기능을 사용자 맞춤형 음성 명령으로 실행할 수 있도록 합니다. 또한, 앱이 학습된 사용자 패턴을 기반으로 적절한 작업을 추천해 주는 기능도 포함하고 있습니다.

Siri Shortcuts의 동작 원리

Siri Shortcuts는 두 가지 방식으로 동작합니다.

  1. NSUserActivity 기반: 사용자가 앱에서 특정 작업을 수행하면 해당 작업을 기록하고, 이를 Siri에게 추천할 수 있도록 만듭니다.
  2. Intents Framework 기반: 사용자가 특정 명령을 실행할 수 있도록 명확하게 정의된 Intent를 생성하고, 이를 Siri에서 실행할 수 있도록 설정합니다.

이를 통해 앱의 특정 기능을 단축어로 제공하고, 사용자는 간단한 음성 명령이나 단축어 앱을 통해 이를 실행할 수 있습니다.

Siri Shortcuts의 사용 사례

  1. 음식 배달 앱: "내 지난 주문 반복해줘"라는 명령으로 최근 주문을 다시 요청
  2. 음악 스트리밍 앱: "출근 플레이리스트 틀어줘"라고 말하면 특정 플레이리스트 재생
  3. 운동 앱: "오늘의 운동 시작해줘"라고 말하면 운동 기록 시작
  4. 메모 앱: "새로운 메모 추가해줘"라고 하면 메모 작성 화면으로 이동

NSUserActivity를 사용한 Siri Shortcuts 구현

NSUserActivity를 활용하면 사용자가 앱 내에서 수행하는 작업을 Siri에 추천할 수 있습니다. 이는 비교적 간단하게 설정할 수 있으며, 앱이 실행될 때 특정 작업을 자동으로 추천하는 데 유용합니다.

1. NSUserActivity 객체 생성

import UIKit

class ViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUserActivity()
    }

    func setupUserActivity() {
        let activity = NSUserActivity(activityType: "com.example.myapp.orderFood")
        activity.title = "최근 주문 반복"
        activity.userInfo = ["orderID": "12345"]
        activity.isEligibleForSearch = true
        activity.isEligibleForPrediction = true
        activity.persistentIdentifier = NSUserActivityPersistentIdentifier("com.example.myapp.orderFood")
        self.userActivity = activity
        activity.becomeCurrent()
    }
}

2. NSUserActivity 핸들링

사용자가 Siri Shortcuts를 실행하면 앱이 해당 Activity를 받아 처리할 수 있습니다.

import UIKit

class AppDelegate: UIResponder, UIApplicationDelegate {
    func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([UIUserActivityRestoring]?) -> Void) -> Bool {
        if userActivity.activityType == "com.example.myapp.orderFood" {
            if let orderID = userActivity.userInfo?["orderID"] as? String {
                print("사용자가 주문을 반복하려고 합니다. 주문 ID: \(orderID)")
            }
        }
        return true
    }
}

Intents Framework를 사용한 Siri Shortcuts 구현

Intents Framework는 NSUserActivity보다 더 강력한 기능을 제공합니다. 직접적인 명령을 통해 앱의 특정 기능을 실행할 수 있으며, SiriKit을 활용하여 더욱 자연스러운 대화를 만들 수 있습니다.

1. Intent 정의

Siri Shortcuts의 첫 단계는 IntentDefinition 파일을 생성하여 Intent를 정의하는 것입니다.

  1. Xcode에서 File > New > File로 이동하여 Intent Definition File을 추가합니다.
  2. 새로운 Intent를 만들고 이름을 설정합니다. (예: OrderFoodIntent)
  3. Intent 속성을 설정합니다.
    • Parameters: 주문 ID (String)
    • Responses: 주문 완료 메시지

2. Intent 핸들러 구현

Siri가 사용자의 음성 명령을 받으면 IntentHandler가 실행됩니다.

import Intents

class OrderFoodIntentHandler: NSObject, OrderFoodIntentHandling {
    func handle(intent: OrderFoodIntent, completion: @escaping (OrderFoodIntentResponse) -> Void) {
        if let orderID = intent.orderID {
            let response = OrderFoodIntentResponse.success(orderID: orderID)
            completion(response)
        } else {
            completion(OrderFoodIntentResponse.failure())
        }
    }
}

3. Intent 핸들러 연결

Intent 핸들러를 Intent Extension에서 연결해야 합니다.

class IntentHandler: INExtension {
    override func handler(for intent: INIntent) -> Any? {
        if intent is OrderFoodIntent {
            return OrderFoodIntentHandler()
        }
        return nil
    }
}

Siri Shortcuts 사용자 정의 및 파라미터 전달

사용자가 Siri Shortcuts을 직접 설정할 수 있도록 앱에서 제공할 수 있습니다.

1. 단축어 추가 기능 제공

import IntentsUI

func addSiriShortcut() {
    let intent = OrderFoodIntent()
    intent.orderID = "12345"
    let interaction = INInteraction(intent: intent, response: nil)
    interaction.donate { error in
        if let error = error {
            print("단축어 기부 실패: \(error.localizedDescription)")
        }
    }
}

2. Siri Shortcuts 설정 화면 제공

사용자가 직접 단축어를 설정할 수 있도록 INUIAddVoiceShortcutViewController를 활용할 수 있습니다.

import IntentsUI

class ViewController: UIViewController, INUIAddVoiceShortcutViewControllerDelegate {
    func presentSiriShortcut() {
        let intent = OrderFoodIntent()
        intent.orderID = "12345"
        let shortcut = INShortcut(intent: intent)
        let viewController = INUIAddVoiceShortcutViewController(shortcut: shortcut)
        viewController.delegate = self
        present(viewController, animated: true, completion: nil)
    }

    func addVoiceShortcutViewControllerDidFinish(_ controller: INUIAddVoiceShortcutViewController) {
        controller.dismiss(animated: true, completion: nil)
    }
}

결론

Siri Shortcuts를 활용하면 사용자의 앱 사용 경험을 더욱 편리하게 만들 수 있습니다. NSUserActivity와 Intents Framework를 적절히 활용하면 음성 명령을 통한 자동화를 쉽게 구현할 수 있습니다.

반응형