Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
Tags
- Content Hugging priority
- IOS
- RxSwift요약
- OperationQueue
- ai expo
- CI/CD
- gitlab
- swift
- 자료구조
- 백준
- 애플인텔리전스
- mvvm
- 알고리즘
- 동시성프로그래밍
- gitlabci/cd
- swift알고리즘
- Autolayout
- 동작과정
- RxCocoa
- AI
- CICD
- LLM
- 클린아키텍처
- Content Compression Resistance priority
- 오토레이아웃
- apple intelligence
- cleanarchitecture
- rxswift
- ReactiveX
- Union-Find
Archives
- Today
- Total
JosephCha의 개발일지
App Intents를 통해 Siri(Apple Intelligence)에서 앱 기능 호출하기 본문
App Intents
- App Intents는 본인앱 사용자들에게 코어한 Action 및 컨텐츠의 기능들(Siri, Spotlight, Shortcuts, Widget 등)을 구성하기 위한 공통 토대라 생각하면 됨
- 하나의 기능(ex. Shortcuts)을 지원하기 위해 App Intents를 구현한 적이 있다면, 다른 기능들(Siri, Spotlight 등)에 유용하게 쓰일 수 있음. 왜냐하면 모두 App Intents를 기초로 하고 있음.
- 예를 들어, App Intents를 사용해 앱을 Siri와 Apple Intelligence에 통합하고, 그 코드를 재사용하여 WidgetKit과 함께 컨트롤 및 인터랙티브 위젯을 생성할 수 있음
- 하나의 기능(ex. Shortcuts)을 지원하기 위해 App Intents를 구현한 적이 있다면, 다른 기능들(Siri, Spotlight 등)에 유용하게 쓰일 수 있음. 왜냐하면 모두 App Intents를 기초로 하고 있음.
- App Intents 프로토콜을 채택함으로써, 앱과 사용자 간의 의사소통 핸들링함. Siri와 Spotlight 같은 시스템 기능에서 개발자가 정의한 기능을 알게끔 할 수 있음.
- 예를들어, 사용자가 앱에서 어떤 것을 하려고 Siri를 불렀다면, Siri는 어떤 것을 하기 위해 앱에 메세지를 보냄. 그런다음 너의 앱은 어떤것을 수행했다고 메세지를 사용자에게 회신함
- 지원되는 기기(ex. iPhone 15 Pro)에서, App Intents 프레임워크는 Apple Intelligence와 통합을 제공하며, Siri는 Apple Intelligence의 능력을 활용해 더욱 자연스럽고, 상황에 맞고, 개인화된 지원을 제공함.
앱을 여는 App Intents 코드
struct OpenFavorites: AppIntent {
static var title: LocalizedStringResource = "Open Favorite Trails"
static var description = IntentDescription("Opens the app and goes to your favorite trails.")
static var openAppWhenRun: Bool = true
@MainActor
func perform() async throws -> some IntentResult {
navigationModel.selectedCollection = trailManager.favoritesCollection
return .result()
}
@Dependency
private var navigationModel: NavigationModel
@Dependency
private var trailManager: TrailDataManager
}
- AppIntent 프로토콜의 title 요구사항을 구현하여 단축어 앱의 Action Library와 단축어 편집기에서 표시할 지역화된 텍스트를 제공
- 단축어 앱은 Action Library에서 설명을 표시함
- 추가 문맥을 제공하기 위해 description 요구사항을 구현하여 app intent의 동작을 설명하는 지역화된 텍스트를 제공
App Intents의 동작 수행
func perform() async throws -> some IntentResult & ReturnsValue<TrailEntity> & ProvidesDialog & ShowsSnippetView {
/// 모든 인텐트는 지역화된 제목과 같은 메타데이터를 포함해야 함. 인텐트의 제목은 시스템 전반에 걸쳐 표시됨.
static var title: LocalizedStringResource = "Open Favorite Trails"
/// 인텐트는 선택적으로 Shortcuts 앱에 표시할 지역화된 설명을 제공할 수 있음.
static var description = IntentDescription("Opens the app and goes to your favorite trails.")
static var openAppWhenRun = true
@MainActor
func perform() async throws -> some IntentResult {
navigationModel.selectedCollection = trailManager.favoritesCollection
return .result()
}
}
- .result()를 반환하여 App Intents가 완료되었음을 시스템에 알림
static var openAppWhenRun = true
- 인텐트가 실행될 때 앱을 전면으로 가져오도록 시스템에 지시함
@MainActor
func perform() async throws -> some IntentResult {
navigationModel.selectedCollection = trailManager.favoritesCollection
/// 인텐트가 완료되었음을 나타내는 빈 결과를 반환함.
return .result()
}
- 인텐트가 실행될 때 시스템은 `perform()`을 호출함
- 인텐트는 임의의 큐에서 실행됨. UI를 조작하는 인텐트는 `perform()`에 `@MainActor`를 어노테이트하여 UI 작업이 메인 액터에서 실행되도록 해야 하
func perform() async throws -> some IntentResult & ReturnsValue<TrailEntity> & ProvidesDialog & ShowsSnippetView {
let snippet = TrailInfoView(trail: trailData, includeConditions: true)
/**
이 인텐트는 트레일 상태를 뷰의 일부로 포함하는 커스텀 보기를 표시함. 시스템이 응답을 읽을 수만 있고 스니펫을 표시할 수 없을 때 대화에는 트레일 상태가 포함됨. 시스템이 응답을 표시할 수 있을 때 대화에서는 트레일 상태를 생략함.
*/
let dialog = IntentDialog(full: "The latest conditions reported for \(trail.name) indicate: \(trail.currentConditions).",
supporting: "Here's the latest information on trail conditions.")
return .result(value: trail, dialog: dialog, view: snippet)
}
- 단축어 앱에서 자신이 만든 단축어에 App Intents를 포함할 수 있음
- perform 함수 반환 타입
- ProvidesDialog 프로토콜: Siri가 대화형으로 결과를 제공할 수 있게됨
- ShowsSnippetView 프로토콜: 사용자에게 UI스니펫 UI를 제공할 수 있게됨
사람들이 정보를 볼 수 없는 상황(예: HomePod에서 인텐트 실행)이나 커스텀 UI를 표시하는 것이 부적절한 상황(예: CarPlay에서 인텐트 실행)에서, 시각적 경험과 음성 전용 경험 모두를 설계해야 함. 이 구현은 커스텀 UI가 표시될 때 사용할 짧은 지원 대화와 스니펫을 표시할 수 없을 때 추가 정보를 포함하는 다른 대화를 제공함. 커스텀 UI에는 투명한 배경을 사용해야 함. 불투명한 배경을 사용하면 최상의 결과를 얻기 어려움.
앱 단축어 생성 코드
AppShortcut(intent: OpenFavorites(), phrases: [
"Open Favorites in \(.applicationName)",
"Show my favorite \(.applicationName)"
],
shortTitle: "Open Favorites",
systemImageName: "star.circle")
- Siri 또는 Spotlight 검색을 통해 App Intent를 호출하려면, AppShortcut을 구현해야함
- AppShortcut은 App Intent와 사용자들이 Siri와 함께 사용할 수 있는 문구, 추가 메타데이터(아이콘 등)를 결합하고, 이 정보를 Spotlight 검색에서 사용함
- 시스템은 사용자들의 요청을 자동으로 매칭하여 유사하지만 동일하지 않은 문구를 식별함
SiriTipView(intent: OpenFavorites(), isVisible: $displaySiriTip)
- SiriTipView는 가시성 Bool값에 바인딩 되어 있어서, 사용자가 이를 해제하면 보기를 숨김
class PINEShortcuts: AppShortcutsProvider {
static var shortcutTileColor = ShortcutTileColor.navy
static var appShortcuts: [AppShortcut] {
AppShortcut(intent: BuyDayPass(), phrases: [
"파인 펀드 \(.applicationName)"
],
shortTitle: "파인 펀드",
systemImageName: "wallet.pass")
}
}
- AppShortcutsProvider를 통해 위에서 선언한 AppShortCut를 등록할 수 있음
- appShortcuts 연산 프로퍼티에 제공하길 원하는 AppShortCut들을 나열하면 됨
AppShortcutsProvider.updateAppShortcutParameters()
- Appdelegate의 didFinishLaunchingWithOptions 메소드에서 'AppShortcutsProvider.updateAppShortcutParameters()' 를 추가하면, 시스템에 AppShortcut이 등록함
앱을 Siri 및 Apple Intelligence와 통합하기
Apple Intelligence는 강력한 생성형 모델을 iPhone, iPad, Mac의 핵심에 깊이 통하는 새로운 개인 지능 시스템.
Siri는 이 능력을 활요하여 사용자에게 더 자연스럽고 상황에 맞는 개인적인 도움을 제공.
App Intents를 사용하면 앱의 기능과 콘텐츠를 시스템에 표현하고 Siri 및 Apple Intelligence와 통합할 수 있어, 사용자가 휴대폰 화면 어디에서나 앱과 상호 작용하는 방법을 제공함
- 앱을 Siri 및 Apple Intelligence와 통합하려면, Apple Intelligence가 사용하는 사전 훈련된 모델과 잘 작동하는 AppIntent, AppEntity, AppEnum 구현 해야함. 이를 위해 Swift 매크로를 사용하여 추가적인 프로퍼티를 생성하고 AppIntent, AppEntity, AppEnum 구현에 필요한 프로토콜 준수를 추가함. Xcode는 새로운 구현을 쉽게 만들 수 있는 템플릿을 제공하고 컴파일 시 코드의 프로토콜 준수를 검증함
- 보조 스키마(AssistantIntent)
- App Intents 구현의 경우, AssistantIntent(schema:) 매크로를 사용함
- AppEntity 구현의 경우, AssistantEntity(schema:) 매크로를 사용함
- AppEnum 구현의 경우, AssistantEnum(schema:) 매크로를 사용함
- 보조 스키마 매크로는 AppIntent, AppEntity, AppEnum 코드를 생성하기 위해 스키마 값을 제공해야함
- 예를 들어, 사진 라이브러리에서 사진을 여는 앱 의도는 @AssistantIntent(schema: .photos.openAsset)을 사용하여 의도가 필요한 메타데이터를 제공하도록 함으로써 Apple Intelligence가 이해할 수 있도록 해야 함.
- 모든 보조 스키마는 하기 제약 조건들을 포함함
- App Intents는 스키마가 기대하는 매개변수 외의 추가 매개변수를 요구할 수 없음. App Intents가 추가 매개변수를 사용하는 경우, 선택적으로 만듬
- 선택적 매개변수는 단축 앱에서만 App Intents에 사용할 수 있음
- 앱 엔티티는 스키마가 기대하는 속성 외에 필수 속성을 사용할 수 없음. 하지만 선택적 속성을 사용할 수 있음
- AppEnum은 열거 케이스에 대한 요구 사항이 없으며 전체 유연성을 제공하지만, 보조 스키마에 준수하는 AppEnum을 10개 이상 사용할 수 없음
관련 코드
(보조 스키마를 사용하여 앱 기능을 Apple Intelligence와 통합)
@AssistantIntent(schema: .photos.openAsset)
struct OpenAssetIntent: OpenIntent {
var target: AssetEntity
@Dependency
var library: MediaLibrary
@Dependency
var navigation: NavigationManager
@MainActor
func perform() async throws -> some IntentResult {
let assets = library.assets(for: [target.id])
guard let asset = assets.first else {
throw IntentError.noEntity
}
navigation.openAsset(asset)
return .result()
}
}
- App Intents가 컴파일 타임에 보조 스키마를 준수하면, 더이상 제목이나 title, description과 같이 기존에 제공했던 메타데이터가 필요하지 않음. (코드 단순화)
- 컴파일 시, 보조 스키마에 준수한 App Intents를 구현하면 컴파일 오류남
- 보조 스키마 요구 사항에 충족해야함
참고
'iOS' 카테고리의 다른 글
iOS GitLab CI/CD (3) | 2025.01.24 |
---|---|
클린 아키텍처 (iOS 전용 포함) (2) | 2024.05.20 |
동시성 프로그래밍(개념, GCD, OperationQueue) (0) | 2023.08.16 |
RxSwift? 이거 하나로 종결 (전체 요약) (2) | 2023.08.09 |
Coordinator 패턴 (1) | 2023.08.09 |
Comments