<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Bangkangchen on Medium]]></title>
        <description><![CDATA[Stories by Bangkangchen on Medium]]></description>
        <link>https://medium.com/@bangkangchen?source=rss-1357baeba4d7------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Fjq1qbHR_mQ83UT2Q6ETIA.jpeg</url>
            <title>Stories by Bangkangchen on Medium</title>
            <link>https://medium.com/@bangkangchen?source=rss-1357baeba4d7------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 14:25:21 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@bangkangchen/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[iOS App Intent自動生成捷徑開發紀錄]]></title>
            <link>https://medium.com/@bangkangchen/ios-app-intent%E8%87%AA%E5%8B%95%E7%94%9F%E6%88%90%E6%8D%B7%E5%BE%91%E9%96%8B%E7%99%BC%E7%B4%80%E9%8C%84-c4f4f3418a89?source=rss-1357baeba4d7------2</link>
            <guid isPermaLink="false">https://medium.com/p/c4f4f3418a89</guid>
            <category><![CDATA[siri]]></category>
            <category><![CDATA[app-intent]]></category>
            <category><![CDATA[中文]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Bangkangchen]]></dc:creator>
            <pubDate>Tue, 05 Mar 2024 07:57:28 GMT</pubDate>
            <atom:updated>2024-03-05T07:57:28.350Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>Xcode 15.0.1, 本文內容中關於App Intent的部分為iOS 16.0以上適用，但範例專案使用到SwiftData，需17.0</blockquote><blockquote>code: <a href="https://github.com/LeoBKChen/AppIntentWithShortcutProviderDemo">github</a></blockquote><p>本文紀錄了如何開發一個可以生成 iOS App Intent 的語音 Intent，同時使用 AppShortcutsProvider 在手機的「捷徑」中生成預先填好參數的捷徑的過程。以下是逐步的說明：</p><h4>1. 初始環境</h4><p>專案內需要有任何使用者可與App交互的業務邏輯，本專案以本地端資料讀寫顯示在畫面上為例，本專案同時也探討了 SwiftData 的使用，但在實作過程中可忽略該部分。</p><p>請參照專案內DataProvider class，其實作了Item Data的讀寫protocol</p><pre>protocol ItemDataController {<br>    func getAllItems() throws -&gt; [Item]<br>    func getItem(with name: String) throws -&gt; Item<br>    func insertItem(_ item: Item)<br>    func updateItem(_ item: Item) throws<br>    func updateItem(_ item: ItemShortcutEntity) throws<br>    func deleteItem(_ item: Item) throws<br>}</pre><h4>2. 建立App Intent Entity</h4><p>本專案探討了如何設計一個多參數的Intent，且參數間存在依賴的狀況，可先參照Item的資料結構中，觀察其含有代表了狀態的陣列。</p><pre>@Model<br>final class Item {<br>    var timestamp: Date<br>    <br>    @Attribute(.unique) var id: UUID<br>    <br>    var title: String<br>    <br>    var status: [ItemStatus]<br>    ...</pre><p>在設計改變Item狀態的Intent時，status需要傳入index的參數，因此需要方便取得status.count，此時就可以實作一個Intent Entity。此外若是在開發較複雜的Intent時，可能也需要與Data Model相關的資料來決定Intent行為。</p><p>在專案內以ItemShortcutEntity為範例說明如何實作AppEntity</p><p>首先宣告與原始資料結構相同的struct</p><pre>struct ItemShortcutEntity {<br>    <br>    var id: UUID<br><br>    var title: String<br><br>    var timestamp: Date<br>        <br>    var status: [ItemStatus]<br>    <br>}</pre><p>接著繼承Identifiable, AppEntity，並補上typeDisplayRepresentation, defaultQuery, displayRepresentation:</p><pre>struct ItemShortcutEntity: Identifiable, AppEntity {<br>    ...<br><br>    static var typeDisplayRepresentation = TypeDisplayRepresentation(name: &quot;Item&quot;)<br>    <br>    static var defaultQuery: ItemQuery = ItemQuery()<br>    <br>    var displayRepresentation: DisplayRepresentation {<br>        return DisplayRepresentation(<br>            title: &quot;\(title)&quot;,<br>            subtitle: &quot;&quot;,<br>            image: .init(systemName: &quot;cube.box&quot;)<br>        )<br>    }<br>}</pre><p>typeDisplayRepresentation和displayRepresentation在文件中都是關於此Entity在UI上呈現，不過筆者找不到typeDisplayRepresentation具體影響的畫面是哪一個，displayRepresentation則可以在新增捷徑時，對應的參數選項看見效果：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wCA_g3azhLJ_DG8m7PFk7w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u-j6SPKhRHWR1C3yxpaSqQ.png" /><figcaption>圖一 displayRepresentation 在捷徑中的呈現</figcaption></figure><p>再實作defaultQuery：</p><pre>struct ItemQuery: EntityStringQuery {<br>    //#1<br>    func entities(matching title: String) async throws -&gt; [ItemShortcutEntity] {<br>        <br>        return try await DataProvider.shared.getAllItems().filter {<br>            $0.title == title<br>        }.map {<br>            ItemShortcutEntity(<br>                id: $0.id,<br>                title: $0.title,<br>                timestamp: $0.timestamp,<br>                status: $0.status<br>            )<br>        }<br>    }<br>    //#2<br>    func entities(for identifiers: [UUID]) async throws -&gt; [ItemShortcutEntity] {<br>        <br>        let items = try await DataProvider.shared.getAllItems().map {<br>            ItemShortcutEntity(<br>                id: $0.id,<br>                title: $0.title,<br>                timestamp: $0.timestamp,<br>                status: $0.status<br>            )<br>        }<br>        <br>        return identifiers.compactMap { id in<br>            items.first { $0.id == id }<br>        }<br>    }<br>    //#3<br>    func suggestedEntities() async throws -&gt; [ItemShortcutEntity] {<br>        try await DataProvider.shared.getAllItems().map {<br>            ItemShortcutEntity(<br>                id: $0.id,<br>                title: $0.title,<br>                timestamp: $0.timestamp,<br>                status: $0.status<br>            )<br>        }<br>    }<br>}</pre><p>說明：#1, #2 在本專案中尚未利用到，應是與在實作App Entity時，系統會多生成一個FindItem的捷徑相關</p><p>#3則是我們的App Intent有帶入這個Entity的參數時，會呈現在建議選項中的內容，如上方圖一所示</p><h4>3. 實作AppIntent</h4><p>本專案目前實作兩個Intent：AddItemIntent和ModifyItemIntent</p><p>AddItemIntent為簡單的傳入一個參數後，在DB中新增對應的資料，其呈現效果可直接操作新增捷徑來對照查看</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p3n98eNFlHLabpxfbqqAow.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mIySKn4un9ixCNKrTZ_ahQ.png" /><figcaption>圖二 Intent 成員變數在新增捷徑時呈現結果</figcaption></figure><p>其關鍵在perform()的實作：</p><pre>func perform() async throws -&gt; some IntentResult &amp; ProvidesDialog {<br>    let item = Item(timestamp: Date(), id: UUID(), title: self.title, status: [.off, .off, .off])<br>    <br>    await DataProvider.shared.insertItem(item)<br>    <br>    return .result(dialog: &quot;Item added succeed&quot;)<br>}</pre><p>perform回傳值有多種protocol可指定，依據該intent執行時的互動設計決定，最基礎的執行時彈跳文字視窗可用ProvidesDialog</p><p>而App Intent不像Sirikit custom intent在handler內即有便利的resolve function可以直接處理參數間互相影響的邏輯(註1)，目前查看其他範例專案都是在perfom內處理所有參數相關邏輯，依據不同需要，可以使用以下方式來獲取參數值或插入其他對話視窗</p><pre>// 1. 在捷徑中執行intent成員變數設置的取值視窗<br>throw self.$variableName.needsValueError(...)<br><br>// 2. 在捷徑中執行動態範圍的取值視窗<br>self.statusIndex = try await self.$statusIndex.requestDisambiguation(among: Array(0..&lt;self.item.status.count), dialog: IntentDialog.itemStatusIndexParameterPrompt)<br><br>// 3. 彈跳出確認視窗<br>try await requestConfirmation(result: .result(dialog: &quot;Are you sure ...?&quot;) </pre><h4>4. 實作AppShortcutsProvider</h4><pre>struct ShortcutsProvider: AppShortcutsProvider {<br>    static var appShortcuts: [AppShortcut] {<br>        AppShortcut(<br>            intent: AddItemIntent(),<br>            phrases: [<br>                &quot;Add an item to\(.applicationName)&quot;,<br>            ],<br>            shortTitle: &quot;Add Item&quot;,<br>            systemImageName: &quot;plus.app&quot;<br>        )<br>        AppShortcut(<br>            intent: ModifyItemIntent(),<br>            phrases: [<br>                &quot;Modify an item in\(.applicationName)&quot;<br>            ],<br>            shortTitle: &quot;Modify Item&quot;,<br>            systemImageName: &quot;rectangle.and.pencil.and.ellipsis&quot;<br>        )<br>        AppShortcut(<br>            intent: ModifyItemIntent(.on),<br>            phrases: [<br>                &quot;Turn on \(\.$item) in \(.applicationName)&quot;<br>            ],<br>            shortTitle: &quot;Turn on an item&#39;s status&quot;,<br>            systemImageName: &quot;lightswitch.on&quot;<br>        )<br>        AppShortcut(<br>            intent: ModifyItemIntent(.off),<br>            phrases: [<br>                &quot;Turn off \(\.$item) in \(.applicationName)&quot;<br>            ],<br>            shortTitle: &quot;Turn off an item&#39;s status&quot;,<br>            systemImageName: &quot;lightswitch.off.fill&quot;<br>        )<br>    }<br>    static var shortcutTileColor: ShortcutTileColor = .blue<br>}</pre><p>appShortcuts可包含多個AppShortcut()，利用這點我們可以支援大量不同的捷徑。在AppShortcutsProvider的使用上，需注意我們需要在app內找一個時機點呼叫updateAppShortcutParameters()，AppShortcutsProvider就會依據每個AppShortcut的phrases內參數的case或entity的suggestedEntities更新捷徑列表，在本專案中是監聽SwiftData資料有變化時呼叫ShortcutsProvider.updateAppShortcutParameters()</p><h4>5. 完成結果圖</h4><p>在「捷徑」中，會列出App捷徑群組，點進去即可看到我們在AppShortcutsProvider設定的捷徑，並可順利運行</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H3lyLIPvRcpku-3Id6Uk_g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UgeOK3kfZ5GslhXSeINQWw.png" /></figure><blockquote>註1:</blockquote><blockquote>App Intent雖也可在<a href="http://twitter.com/Parameter">@Parameter</a> Wrapper中傳入resolvers func，不過依照文件描述更像是專門處理字串與其他資料型態的轉換，這部分筆者尚未實驗</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*0jCiXLl0-JCIca8Eyq2JoQ.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c4f4f3418a89" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SiriKit Custom Intent Shortcut 開發紀錄(二)-Framework]]></title>
            <link>https://medium.com/@bangkangchen/sirikit-custom-intent-shortcut-%E9%96%8B%E7%99%BC%E7%B4%80%E9%8C%84-%E4%BA%8C-framework-3709037c575e?source=rss-1357baeba4d7------2</link>
            <guid isPermaLink="false">https://medium.com/p/3709037c575e</guid>
            <category><![CDATA[framework]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[custom-intent]]></category>
            <category><![CDATA[sirikit]]></category>
            <category><![CDATA[中文]]></category>
            <dc:creator><![CDATA[Bangkangchen]]></dc:creator>
            <pubDate>Thu, 04 Jan 2024 07:03:35 GMT</pubDate>
            <atom:updated>2024-01-04T07:03:35.105Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><em>Swift 5, Xcode 15.0.1<br>source code: </em><a href="https://github.com/LeoBKChen/SiriShortCutDemo"><em>github</em></a>, branch: Version_Framework</blockquote><h3>大綱</h3><p>延續 <a href="https://medium.com/@bangkangchen/sirikit-custom-intent-shortcut-%E9%96%8B%E7%99%BC%E6%B5%81%E7%A8%8B%E7%B4%80%E9%8C%84-8baab054c4b5">SiriKit Custom Intent Shortcut 開發紀錄(一)-continueInApp</a><br>本文紀錄將app部分核心程式庫(Realm local database)抽離製作成framework, 以便在intent extension中直接處理指令。</p><p>通常我們想透過捷徑處理的指令可能會涉及網路連線、資料庫存取或其他原本app中既有的業務邏輯，如果要在intent extension中也能access到相關程式碼，我們就需要將對應service抽離製作成framework，除了避免專案內出現大量重複程式碼，也能確保在intent extension和main app中的邏輯一致。</p><h3>專案先備環境</h3><p>本文以專案main app使用RealmSwift為範例，將相關程式抽離至Framework，接下來會先說明抽離前專案的設置，可參考git中commit點: 4d64fe3</p><ol><li>專案內使用pod安裝RealmSwift</li><li>新增RealmService管理realm相關邏輯</li><li>新增DemoObject作為本地資料儲存結構</li><li>ViewModel訂閱realm中DemoObject的變動</li><li>ViewController新增按鈕點擊後更新realm中DemoObject資料</li></ol><h3>製作Framework</h3><p>我們想要透過捷徑能讀寫資料庫的資料，因此最直接的方式是將RealmService抽離至新建的framework中，其步驟如下：</p><ol><li>在專案的targets中新增Framework</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/395/1*mzh9aT7z7gDsGgpX_VXZBg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/719/1*KPl2bc3lAnT9PY5gjYV2qA.png" /></figure><p>2. 將 Shared資料夾搬移至framwork目錄底下</p><p>記得確認檔案的target membership要變更成framework</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/236/1*UNixd_rm3bnanCaIql8fdA.png" /></figure><p>3. 調整podfile內容及層級，將framework置於最上層</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/542/1*P2GytldOhx9xWwZd4TOVlQ.png" /></figure><p>4. 將framework嵌入至intent extension的target中</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/918/1*x5egherGAzoMxxHsUCHYoA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/661/1*xPJjv4_5rb-t1r4JIDr5GQ.png" /></figure><p>5. 原本直接取用singleton的程式碼檔案都需額外import framework</p><p>6. 將開放給外部使用的函式、變數、structure等都需改成public</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/707/1*5G-_8sGL5hxF8h6Xb7VYeQ.png" /></figure><p>此時我們試著編譯新建的framework，遭遇到編譯錯誤，發現是在編譯framework的bridge header時無法編譯Realm，這是因為把Realm的Object直接public的原因</p><p>透過新建一個DemoModel，將DemoObject封裝在內，並改為將DemoModel開放，就可以避免直接將第三方套件內容直接開放，也解決此編譯問題。</p><p>7. 現在我們已將一切準備就緒，可以試著編譯並執行原有的app，且一切應該運作正常</p><p>8. 接下來調整intent extension的邏輯，我們試著取用realm的資料，並將使用者的輸入值存入其中</p><p>調整SiriDeviceOperationInfoIntentHandler中的handle如下，並進行捷徑的測試</p><pre>func handle(intent: SiriDeviceOperationInfoIntent, completion: @escaping (SiriDeviceOperationInfoIntentResponse) -&gt; Void) {<br>    guard let deviceName = intent.deviceName,<br>          let operation = intent.operation<br>    else {<br>        completion(SiriDeviceOperationInfoIntentResponse(code: .failure, userActivity: nil))<br>        return<br>    }<br><br>    let originalRealmValue = RealmService.shared.getDemoData().first?.value ?? &quot;nil&quot;<br>    let newValue = &quot;\(deviceName) \(operation)&quot;<br>    RealmService.shared.updateDemoData(id: 1, value: newValue)<br>    <br>    completion(.success(result: &quot;將\(originalRealmValue)改為\(newValue)&quot;))<br>}</pre><p>測試後會發現從realm取出的值與直接執行app時不同，其原因是在iOS 中app執行時的檔案路徑和extension執行的檔案路徑是被區隔開來的，因此realm預設的檔案路徑在兩者執行時，也就無法取到同一個realm檔案，這點我們可以分別在main app target和intent extension中印出Realm.Configuration.defaultConfiguration.fileURL來驗證</p><p>9. 引入App Group</p><p>為了要在intent extension中直接執行指令，我們需要能直接在intent extension中取得和app相同的database, 這可以透過引入App Group</p><p><a href="https://medium.com/%E5%BD%BC%E5%BE%97%E6%BD%98%E7%9A%84-swift-ios-app-%E9%96%8B%E7%99%BC%E5%95%8F%E9%A1%8C%E8%A7%A3%E7%AD%94%E9%9B%86/%E8%AE%93%E4%B8%8D%E5%90%8C-app-%E5%85%B1%E4%BA%AB%E8%B3%87%E6%96%99%E7%9A%84-app-group-928e22fd37df">讓不同 App 共享資料的 App Group</a></p><p>引入App Group後，我們在RealmService的configRealm內，進行向下相容的處理，將預設的db路徑改為app group的路徑，這樣app和extension就能取用到同一份db了，記得在intent extension中使用前要呼叫configRealm()</p><pre>public class func configRealm() {<br>    var config = Realm.Configuration(<br>        // do extra config setting...<br>    )<br>    <br>    let fileManager = FileManager.default<br>    if let containerURL = fileManager.containerURL(forSecurityApplicationGroupIdentifier: AppGroupName.Realm) {<br>        <br>        let newRealmURL = containerURL.appendingPathComponent(&quot;db.realm&quot;)<br>        <br>        if let oldRealmURL = config.fileURL,<br>           fileManager.fileExists(atPath: oldRealmURL.path) {<br>            // Move the file to the new location<br>            do {<br>                try fileManager.moveItem(at: oldRealmURL, to: newRealmURL)<br>                print(&quot;Realm file moved successfully&quot;)<br>            } catch {<br>                print(&quot;Error moving Realm file: \(error.localizedDescription)&quot;)<br>            }<br>        }<br>        <br>        config.fileURL = newRealmURL<br>    }<br>    Realm.Configuration.defaultConfiguration = config<br>}</pre><p>10. 完成</p><p>將db路徑統一使用app group的路徑後，從捷徑和app都能讀寫相同的db檔案了，不過由於我們剛剛有在實作向下相容前先測試捷徑，造成app和extension的路徑下都有db.realm，會有其中一個檔案搬移時出錯，若一開始就直接做好向下相容的話就不會有這個問題</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6pFt5YjVahKbrQUaQkJrWg.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PK4gLPANcEv0UcVFaIbGEQ.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g7CtI2hNs9EBE8HpcjOY4A.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*BgMgKq69PLONnjAn.png" /></figure><h4>參考：</h4><p><a href="https://www.mongodb.com/developer/code-examples/swift/realm-swiftui-scrumdinger-migration/">Adapting Apple&#39;s Scrumdinger SwiftUI Tutorial App to Use Realm | MongoDB</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3709037c575e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SiriKit Custom Intent Shortcut 開發流程紀錄]]></title>
            <link>https://medium.com/@bangkangchen/sirikit-custom-intent-shortcut-%E9%96%8B%E7%99%BC%E6%B5%81%E7%A8%8B%E7%B4%80%E9%8C%84-8baab054c4b5?source=rss-1357baeba4d7------2</link>
            <guid isPermaLink="false">https://medium.com/p/8baab054c4b5</guid>
            <category><![CDATA[中文]]></category>
            <category><![CDATA[custom-intent]]></category>
            <category><![CDATA[xocde]]></category>
            <category><![CDATA[sirikit]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Bangkangchen]]></dc:creator>
            <pubDate>Mon, 06 Nov 2023 05:39:37 GMT</pubDate>
            <atom:updated>2024-01-04T06:52:29.268Z</atom:updated>
            <content:encoded><![CDATA[<h3>SiriKit Custom Intent Shortcut 開發紀錄(一)-continueInApp</h3><blockquote>Swift 5, Xcode 14.3.1 <br>source code: <a href="https://github.com/LeoBKChen/SiriShortCutDemo">github</a></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/828/1*yIZsDcWVPXxD7T_zTd4CEg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/828/1*nF7cw4DDin61v1TO2dfn5Q.png" /></figure><h3>大綱</h3><p>研究目的： 讓app可透過siri語音輸入後執行相關指令</p><p>方式：本文主要紀錄以custom intent方式，透過建立「捷徑」，來讓app可以收到語音資料以便後續處理，其中處理資料方式有兩種。<br>其一為收到資料後的處理邏輯在intent extension處理，而如果與主程式target有共用邏輯，可以將共用程式碼抽離製作成新的framework，在主程式與intent extension import使用。<br>本文示範使用另一種方式：將資料傳給主程式，在主程式處理邏輯，下一篇將示範如何製作framework,在intent extension中直接處理指令。</p><h3>步驟</h3><ol><li>Create extension target</li></ol><blockquote>要在ios中支援捷徑，我們需要在專案內新增intent extension的target</blockquote><p>在xcode project 中，新增target，類型選擇intent extension(App Intents Extension應是iOS 16.0以上新增使用純coding方式製作intent definition，筆者還沒研究)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/733/1*YeUBj0X_S9Uw9a5rp0e2hQ.png" /></figure><p>名稱可依照用途命名，其中Starting Point 因為我們要使用客製化intent，所以選擇None, Include UI Extension 因為這次沒用到，可選可不選</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/725/1*xT4pZOV0VS2bw0AQyCfoHg.png" /></figure><p>建立完成後跳出的詢問視窗，若選Activate，應只是把目前的scheme切換過去新建立的target對應的scheme而已，不影響後續操作</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/533/1*mUuTQeoEzG8o1UNYt1tRtA.png" /></figure><p>以上我們就新增完intent extension了，接下來可以進行下一階段</p><p>2. 建立.intentdefinition 檔案</p><blockquote>.intentdefinition 定義了整個intent的資料架構及在捷徑中運行時的行為模式</blockquote><p>在project navigator 中新建檔案，選擇SiriKit Intent Definition File，檔名依據需求命名，注意確認Targets至少需勾選到剛剛建立的Intent extension，如果後續要製作建議捷徑時，則需要再勾選主app的target</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L__2Yqu8x4MOj-9HC_r4Xg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/728/1*xdPKb0hI5zzNYCinL48uVQ.png" /></figure><p>新增Intent:左下方 + ， 選New Intent，然後將其命名為喜歡的樣子</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/363/1*50y_2nBkNy-Dz3K-oacCmw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/763/1*knW2wZaZa4_gDCt60hQlWw.png" /></figure><p>再來就是設定Intent內容，這裡的Title和Description會顯示在捷徑的選項中</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/813/1*IbeTMpF20GyuABBBd_Ogag.png" /></figure><p>設定參數欄位，在Parameters中點 “＋”，建立會使用到的參數，並修改名稱，新增Siri Dialog問句內容</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/763/1*Ka-mmgXx5ibl42k_T0Nj7w.png" /></figure><p>最後設定shortcuts app 上的描述”Summary”(下方Suggestions會自動同步)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/932/1*qFV0uqSyX8FfejpKnBc_lw.png" /></figure><p>由於我們要將資料傳入Main App target中，Response可以先只設定failure的部分，至此完成intentdefinition file 的建置。</p><p>3. IntentHandler邏輯</p><p>在原本的IntentHandler.swift中將handler function改寫成這樣，這裡的SiriDeviceOperationInfoIntent是剛剛定義好的custom intent名字加上Intent，透過下面這個方式來將多個intent處理方式分流。</p><pre>    override func handler(for intent: INIntent) -&gt; Any {<br>        if intent is SiriDeviceOperationInfoIntent {<br>            return SiriDeviceOperationInfoIntentHandler()<br>        }<br>        else {<br>            fatalError(&quot;Unhandled Intent error : \(intent)&quot;)<br>        }<br>        <br>    }</pre><p>建立對應的handler class, ex: SiriDeviceOperationInfoIntentHandler.swift<br>遵循SiriDeviceOperationInfoIntentHandling(”SiriDeviceOperationInfo”+ IntentHandling)</p><pre>class SiriDeviceOperationInfoIntentHandler: NSObject, SiriDeviceOperationInfoIntentHandling {<br>}</pre><p>此時會跳出提示缺少協議內的函式，需補上resolveXXX，其作用是在使用者填入intent對應欄位的內容時做預處理及系統的回應(例如回傳needsValue的話就會要求重新輸入，此處的completion回傳結果種類可參照<a href="https://developer.apple.com/documentation/sirikit/resolving_and_handling_intents/resolving_the_parameters_of_an_intent#2864163">apple文件</a>)，範例如下:</p><pre>func resolveDeviceName(for intent: SiriDeviceOperationInfoIntent, with completion: @escaping (INStringResolutionResult) -&gt; Void) {<br>    if let deviceName = intent.deviceName,<br>       deviceName.count &gt; 0,<br>       deviceName != &quot;裝置名稱&quot;{<br>        completion(INStringResolutionResult.success(with: deviceName))<br>    }<br>    else {<br>        completion(INStringResolutionResult.needsValue())<br>    }<br>}</pre><p>最後實作handle function如下，因傳入的intent 欄位資料型別會是optional，可再一次處理資料。傳入main app的關鍵是建立NSUserActivity，自訂義activityType內容，透過addUserInfoEntries填入資料，透過completion傳入對應intent response，並將response初始化參數帶入.continueInApp及建立好的userActivity。</p><pre>func handle(intent: SiriDeviceOperationInfoIntent, completion: @escaping (SiriDeviceOperationInfoIntentResponse) -&gt; Void) {<br><br>    guard let deviceName = intent.deviceName,<br>          let operation = intent.operation<br>    else {<br>        completion(SiriDeviceOperationInfoIntentResponse(code: .failure, userActivity: nil))<br>        return<br>    }<br><br>    let activity = NSUserActivity(activityType: &quot;tw.com.bk.DeviceOperationActivity&quot;)<br><br>    activity.addUserInfoEntries(from: [<br>        &quot;deviceName&quot; : deviceName,<br>        &quot;operation&quot; : operation<br>    ])<br>    <br>    completion(SiriDeviceOperationInfoIntentResponse(code: .continueInApp, userActivity: activity))<br>}</pre><p>以上步驟我們已經完成main App以外的工作，接下來處理main App</p><p>4. 處理main App</p><p>新增main App 的capability:在xcodeproj介面選取main App target，切換至Signing &amp; Capabilities 點選+Capability，新增Siri</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1015/1*zaQGElTMIPYJFyUhZfiIDA.png" /></figure><p>在main App的info.plist 新增屬性”Privacy - Siri Usage Description”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/608/1*WwpsvYbmDV-bNsXZ265ZOw.png" /></figure><p>最後再依據你的專案<br>有使用SceneDelegate的話需在SceneDelegate內新增以下function</p><pre>func scene(_ scene: UIScene, continue userActivity: NSUserActivity){<br>}</pre><p>只有AppDelegate的話在AppDelegate內新增</p><pre>func application(_ application: UIApplication, <br>continue userActivity: NSUserActivity, <br>restorationHandler: @escaping ([UIUserActivityRestoring]?) -&gt; Void) -&gt; Bool {<br><br>}</pre><p>其中userActivity用法都一樣，以SceneDelegate為範例如下:</p><pre>func scene(_ scene: UIScene, continue userActivity: NSUserActivity) {<br>        print(&quot;continue userActivity in scene&quot;)<br>        <br>        if userActivity.activityType == &quot;tw.com.bk.DeviceOperationActivity&quot; {<br>            // Extract parameters and perform actions.<br>            guard let deviceName = userActivity.userInfo?[&quot;deviceName&quot;] as? String,<br>                  let operation = userActivity.userInfo?[&quot;operation&quot;] as? String<br>            else { return }<br>            <br>            print(&quot;application userActivity : deviceName = \(String(describing: deviceName)), operation = \(String(describing: operation))&quot;)<br>        }<br>    }</pre><p>依據activityType去判斷是哪個intent導過來的，再透過userActivity.userInfo取出資料，就可以在app內進行後續的動作了。</p><h3>使用方式</h3><p>手機打開「捷徑」or 「shortcut」，新增捷徑，在app中找到你的app，如果以上設置都正確的話，就會出現可以加入的捷徑。之後就可以使用「hey, Siri」加上你設定的捷徑名稱觸發。</p><h3>參考：</h3><ul><li><a href="https://developer.apple.com/documentation/sirikit/dispatching_intents_to_handlers">Dispatching intents to handlers | Apple Developer Documentation</a></li><li><a href="https://www.kodeco.com/600-sirikit-tutorial-for-ios">SiriKit Tutorial for iOS</a></li><li><a href="https://www.infoq.cn/article/lsuikfdr0eyv2lusatjt">爱奇艺iOS深度实践：SiriKit详解应用篇_移动_爱奇艺技术产品团队_InfoQ精选文章</a></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*foiAuEE84mMoB0sZ.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8baab054c4b5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Swift 5 CoreData 學習記錄]]></title>
            <link>https://medium.com/@bangkangchen/swift-5-coredata-%E5%AD%B8%E7%BF%92%E8%A8%98%E9%8C%84-2e6b0158fcf4?source=rss-1357baeba4d7------2</link>
            <guid isPermaLink="false">https://medium.com/p/2e6b0158fcf4</guid>
            <dc:creator><![CDATA[Bangkangchen]]></dc:creator>
            <pubDate>Mon, 11 Sep 2023 08:15:13 GMT</pubDate>
            <atom:updated>2023-09-11T08:15:57.337Z</atom:updated>
            <content:encoded><![CDATA[<p>xcode version: 14.3.1</p><p>建立簡單core data並熟悉其使用方式</p><p>第一步：建立xcode專案</p><p>建立專案時要勾選Use Core Data</p><figure><img alt="Check the “Use Core Data” below" src="https://cdn-images-1.medium.com/max/725/1*xeZKdFnr-PpfU7ZJg8gxeA.png" /></figure><p>第二步：新增資料結構</p><p>在專案內自動生成的「專案名.xcdatamodeld」檔案中新增Entity(實體)，Entity為欲在程式中使用到的儲存資料結構名稱，可參考SQL相關資料。新增Entity後再新增Entity內的Attribute</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_ynLp1eshEvODw-99XSGTA.png" /></figure><p>此時專案內已自動生成對應Entity的class檔案，不過在xcode的file navigator內看不到，如果沒有自動生成的話，需確認entity的設定是不是Class Definition</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/603/1*GgE_wT6y1c6PHeaZ7h8kKA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/965/1*RC-RaAf5mnBf1135D9o88A.png" /></figure><p>第三步：建立存取資料的方法</p><p>基本的存取包含CRUD(Create、Read、Update、Delete)，這裡我先定義CoreDataService protocol方便未來擴充，其內容如下</p><pre>import CoreData<br><br>protocol CoreDataService {<br>    associatedtype Entity: NSManagedObject<br>    <br>    func create(entity: Entity)<br>    func fetchAll() -&gt; [Entity]<br>    func update(entity: Entity)<br>    func delete(entity: Entity)<br>}</pre><p>這裡使用到associatedtype，定義了一個替代的名字”Entity”，並約束其需繼承NSManagedObject(也就是coredata中entity model的基礎類別)，接下來實作FavoriteMapDataService的類別，遵循CoreDataService</p><pre>import CoreData<br>import UIKit<br><br>class FavoriteMapDataService: CoreDataService {<br>    typealias Entity = FavoriteMap<br>    <br>    static let shared = FavoriteMapDataService()<br>    <br>    let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext<br>    <br>    func create(entity: FavoriteMap) {<br>        do {<br>            try context.save()<br>        } catch {<br>            print(&quot;Error saving context: \(error)&quot;)<br>        }<br>    }<br>    <br>    func fetchAll() -&gt; [FavoriteMap] {<br>        var FavoriteMaps = [FavoriteMap]()<br>        let request: NSFetchRequest&lt;FavoriteMap&gt; = FavoriteMap.fetchRequest()<br>        <br>        do {<br>            FavoriteMaps = try context.fetch(request)<br>        } catch {<br>            print(&quot;Error fetching FavoriteMaps: \(error)&quot;)<br>        }<br>        <br>        return FavoriteMaps<br>    }<br>    <br>    func update(entity: FavoriteMap) {<br>        do {<br>            try context.save()<br>        } catch {<br>            print(&quot;Error saving context: \(error)&quot;)<br>        }<br>    }<br>    <br>    func delete(entity: FavoriteMap) {<br>        context.delete(entity)<br>        <br>        do {<br>            try context.save()<br>        } catch {<br>            print(&quot;Error saving context: \(error)&quot;)<br>        }<br>    }<br>}</pre><p>實際上使用時須以service的context建立entity實體</p><pre>let newFavorite = FavoriteMap(context: FavoriteMapDataService.shared.context)<br>newFavorite.mapTitle = mapTitle<br>FavoriteMapDataService.shared.create(entity: newFavorite)</pre><p>參考文章：</p><p><a href="https://medium.com/%E5%BD%BC%E5%BE%97%E6%BD%98%E7%9A%84-swift-ios-app-%E9%96%8B%E7%99%BC%E6%95%99%E5%AE%A4/%E7%A0%94%E7%A9%B6coredata%E9%81%8B%E4%BD%9C%E6%A9%9F%E5%88%B6-38c44c49a6e6">研究Coredata運作機制(一)</a></p><p><a href="https://lionjohn.gitbooks.io/coredatacookbook/content/CHAPTER1/FirstLesson.html">CoreData从入门到精通</a></p><p>chatGPT</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2e6b0158fcf4" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>