<?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 Kenny Lemon on Medium]]></title>
        <description><![CDATA[Stories by Kenny Lemon on Medium]]></description>
        <link>https://medium.com/@kennylemon?source=rss-6a39ef480c3b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Stories by Kenny Lemon on Medium</title>
            <link>https://medium.com/@kennylemon?source=rss-6a39ef480c3b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 08:37:57 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kennylemon/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[SwiftUI 踩坑]]></title>
            <link>https://medium.com/@kennylemon/swiftui-%E8%B8%A9%E5%9D%91-f37dacc98473?source=rss-6a39ef480c3b------2</link>
            <guid isPermaLink="false">https://medium.com/p/f37dacc98473</guid>
            <category><![CDATA[tvos]]></category>
            <category><![CDATA[swiftui]]></category>
            <dc:creator><![CDATA[Kenny Lemon]]></dc:creator>
            <pubDate>Fri, 18 Nov 2022 02:56:24 GMT</pubDate>
            <atom:updated>2022-11-30T06:19:56.555Z</atom:updated>
            <content:encoded><![CDATA[<p>SwiftUI, tvOS</p><p><strong><em>前情提要</em></strong></p><p>原先以為只是開發產品中的一個小小小功能。基本上就是要在 tvOS 上面有許多文字，且文字會超過螢幕高度許多，然後讓使用者可以捲動的功能以便觀看所有的內容；想當然耳，在行動裝置上就是直接用 ScrollView 與 Text 就可以簡單實現了。</p><p><strong><em>踩坑實錄</em></strong></p><p>接下來就這麼先在行動裝置上試試，照想法把一長串的文字（<strong>content</strong>）放入 Text 元件中，外面再包一層 ScrollView，跑起模擬器；噠拉，一切如想像中的完美，就像下方的程式碼以及模擬器，超過畫面的文字就可以順暢的滑動。</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ce848eab2185745b6d23bb3bb09f846d/href">https://medium.com/media/ce848eab2185745b6d23bb3bb09f846d/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/592/1*a3HQYk2PBcmDgqfrpziTfg.gif" /></figure><p>接下來，就是把這段程式碼真正的放到 tvOS 上運行囉！登愣，沒想到整個無法滑動，也無法看到螢幕外的文字。如下圖。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sADoVnfcsD3ROXZ-EQR4rw.png" /></figure><p>tvOS 具有平台特有的 focus engine，根據官方文件所示，ScrollView 、Text 或 Label 都不是預設可得到 focus 的元件，因此需要些加工，才能讓畫面中的 <strong>content </strong>如我們所預期的滑動，並看到全部的文字。專案最低支援 tvOS 14，我們可使用 Text(“xxx”).focusable() 讓元件可被 focus。</p><p>首先，就是要讓幾個在 ScrollView 中的 Text 元件可被 focus，再來前後添加幾個內容長度超過 0 的 Text 元件，最後跑起模擬器就可以用遙控器滾動來看 content 的內容囉！這邊需要多注意一下，上下 Text(“ ”) 元件內最少要是一個空白，才會有效，若只是 Text(“”) 仍會有無法 scroll 的問題存在！</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4085691ae6b5dfa62ab49bd347ecf44c/href">https://medium.com/media/4085691ae6b5dfa62ab49bd347ecf44c/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LDRtua0F3qHtKr-vP7lpJg.gif" /></figure><p><strong><em>延伸閱讀</em></strong></p><ul><li><a href="https://developer.apple.com/documentation/swiftui/view/focusable(_:)">Apple Developer Documentation</a></li><li><a href="https://developer.apple.com/documentation/uikit/focus-based_navigation/about_focus_interactions_for_apple_tv">Apple Developer Documentation</a></li><li><a href="https://developer.apple.com/documentation/uikit/focus-based_navigation/adding_user-focusable_elements_to_a_tvos_app">Apple Developer Documentation</a></li><li><a href="https://developer.apple.com/library/archive/documentation/General/Conceptual/AppleTV_PG/WorkingwiththeAppleTVRemote.html">Controlling the User Interface with the Apple TV Remote</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f37dacc98473" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Swift Package Manager 踩坑]]></title>
            <link>https://medium.com/@kennylemon/swift-package-manager-%E8%B8%A9%E5%9D%91-2f0470d05f1d?source=rss-6a39ef480c3b------2</link>
            <guid isPermaLink="false">https://medium.com/p/2f0470d05f1d</guid>
            <category><![CDATA[swift-package-manager]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Kenny Lemon]]></dc:creator>
            <pubDate>Mon, 17 Oct 2022 02:16:21 GMT</pubDate>
            <atom:updated>2022-10-17T02:26:13.122Z</atom:updated>
            <content:encoded><![CDATA[<p>Swift Package Manager, SPM</p><h3>前情提要</h3><p>為了要在專案上達成 Modular Architecture Pattern，我們把 API 相關的部分利用 Swift Package Manager（以下簡稱：SPM）抽出來變成 SDK。除了 Modular Architecture Pattern 外，實作過程我們也採用 TDD（Test Driven Development），先從 Unit Test 開始寫起，直接打 Server API 的 Unit Test。其後，為了讓 Unit Test 跑的過程脫離真實網路環境的影響，把 API Response 的部分都從 JSON 檔讀入時，踩到了這個坑。</p><h3>踩坑實錄</h3><p>簡單的說，在 SPM 裡取得 Resource 檔案路徑的方式跟專案中不一樣。以往在專案中在 target 裡面包含有 Mock 的 JSON 檔，並使用 Bundle 的 url API 即可取得像是下列的檔案路徑；“file:///Users/xxx/Library/Developer/CoreSimulator/Devices/14EEBB6B-3E28–4B8E-B8A3–54968A898D18/data/Containers/Bundle/Application/ABF214B7–6571–49E5-B2B9-F23957CEBC0C/project-name.app/PlugIns/test-target.xctest/file-name.json”。</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3a8924e864bbc46efcddc33cc3093534/href">https://medium.com/media/3a8924e864bbc46efcddc33cc3093534/href</a></iframe><p>接著再使用 Data 的 API 即可把 JSON 相關檔案讀取到記憶體中。</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bf2aaf55970d959bbcb33df7920f7c9c/href">https://medium.com/media/bf2aaf55970d959bbcb33df7920f7c9c/href</a></iframe><p>而在 SPM 中本以為可以使用一樣的方式取得路徑且可直接使用，應該是一塊小蛋糕的。但事情總是沒有想的這麼簡單。</p><p>首先，我們得先在 Package file 中加入 resources，此外，還要明確指出想怎麼使用 resource；其中有兩個方式，a. <a href="https://developer.apple.com/documentation/packagedescription/resource/process(_:localization:)">process</a>，b. <a href="https://developer.apple.com/documentation/packagedescription/resource/copy(_:)">copy</a>，其實差異就在有沒有 copy 以及有沒有讓系統幫忙做優化。</p><p>在設定好 Package 中的 resources 之後，我們才能在 SPM 中使用 Bundle.module 這樣的 API 去取得對應名稱的 resource。</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/38ed81b5b4f3e512d6f7990fe6377f1b/href">https://medium.com/media/38ed81b5b4f3e512d6f7990fe6377f1b/href</a></iframe><p>但 SPM 中用來取得 Bundle 內 Resource 檔案路徑的，僅是像下列這樣的檔案路徑而已；”/Users/xxx/Library/Developer/Xcode/DerivedData/project-name-dmnngyhbitvouueoudvvrvvfzolm/Build/Products/Debug-appletvsimulator/target-name.xctest/project-name.bundle/file-name.json”。若是沒有處理過，會跳這樣的錯誤，無法正常取得並讀取檔案。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/755/1*dC2X1SDAKANOrdFt41m1gQ.png" /></figure><p>那怎麼樣才能正確的取得檔案內的路徑呢？簡單來說，就是在上述的檔案路徑前加上，“file://”即可。接下來就使用簡單的 Data API 即可正確取得 JSON 的內容使用了！Cheers！</p><h3>附註</h3><ul><li><a href="https://developer.apple.com/documentation/xcode/bundling-resources-with-a-swift-package">Apple Developer Documentation</a></li><li><a href="https://www.fabrizioduroni.it/2020/10/19/swift-package-manager-resources/">Swift Package Manager: bundling resources with a Swift Package</a></li><li><a href="https://stackoverflow.com/questions/26080120/cfurlcopyresourcepropertyforkey-failed-because-passed-url-no-scheme">CFURLCopyResourcePropertyForKey failed because passed URL no scheme</a></li><li><a href="https://blog.griddynamics.com/modular-architecture-in-ios/">iOS Modular Architecture Patterns for Large-Scale Development</a></li></ul><p><a href="https://en.wikipedia.org/wiki/Test-driven_development">https://en.wikipedia.org/wiki/Test-driven_development</a></p><p><a href="https://www.guru99.com/test-driven-development.html">What is Test Driven Development (TDD)? Example</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2f0470d05f1d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SwiftUI 踩坑]]></title>
            <link>https://medium.com/@kennylemon/swiftui-%E8%B8%A9%E5%9D%91-fcc1178737ae?source=rss-6a39ef480c3b------2</link>
            <guid isPermaLink="false">https://medium.com/p/fcc1178737ae</guid>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[qr-code]]></category>
            <category><![CDATA[image]]></category>
            <category><![CDATA[uiimageview]]></category>
            <dc:creator><![CDATA[Kenny Lemon]]></dc:creator>
            <pubDate>Mon, 19 Sep 2022 01:28:54 GMT</pubDate>
            <atom:updated>2022-09-19T01:28:54.410Z</atom:updated>
            <content:encoded><![CDATA[<p>UIImageView, Image</p><h3>前情提要</h3><p>寫 tvOS App 的登入頁面過程中，需要登入網址讓使用者可以藉由掃描 QR Code 進行登入動作時，碰到這個問題。</p><h3>踩坑實錄</h3><p>流程是由使用者可登入的網址產生出對應 QR Code，並顯示在 tv 上讓使用者用手機掃描後，藉由手機這種對使用者輸入比較友善的平台進行帳號密碼輸入以及登入。產生出 QR Code 的原始碼如下。</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/755879393a937b2670984f9932911e1b/href">https://medium.com/media/755879393a937b2670984f9932911e1b/href</a></iframe><p>就直接把上面這段程式碼產出的 UIImage 放入 SwiftUI 的 Imae 裡使用吧！登愣！怎麼沒有圖呢？（理想狀態 QR Code 應該出現在深綠色的區塊內）</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/634/1*tH8njxWTtA-bLZJo9jWnaQ.jpeg" /></figure><p>為什麼會這樣呢？因為 CIImage 就像是一個預定要產生出來的圖，但尚未經過 reder 的過程，所以實際上圖並不存在。如果使用 UIImage(ciImage:) 生成 UIImage，還需要經過 reder 的過程，圖才會實際呈現在畫面上；而 UIImageView 就完美的填補了這個空缺；也就是說 UIImageView 會幫忙完成圖 render 的工作。</p><p>然而，SwiftUI 中的 Image 貌似少了 UIImageView 這般把圖 render 成點陣圖的這段，因此，我們需要自己完成這個部分，以免得到上述一片空白的結果。</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7ffa964f96d49f756f588c636a92b0e9/href">https://medium.com/media/7ffa964f96d49f756f588c636a92b0e9/href</a></iframe><p>上述原始碼中加上了第 21 行，用 CIContext 實際把圖 reder 成點陣圖後再放入 SwiftUI 的 Image 中，結果…終於看到想像中的 QR Code 了。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/604/1*KcN7JAtHI-tmT2q5OwJBNw.jpeg" /></figure><h3>延伸閱讀</h3><ul><li><a href="https://medium.com/@MedvedevTheDev/generating-basic-qr-codes-in-swift-63d7222aa011">Generating Basic QR Codes in Swift 3.0</a></li><li><a href="https://stackoverflow.com/questions/58239980/generating-qr-code-with-swiftui-shows-empty-picture">Generating QR Code with SwiftUI shows empty picture</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fcc1178737ae" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Framework 踩坑]]></title>
            <link>https://medium.com/@kennylemon/framework-%E8%B8%A9%E5%9D%91-7a2fb07454d2?source=rss-6a39ef480c3b------2</link>
            <guid isPermaLink="false">https://medium.com/p/7a2fb07454d2</guid>
            <category><![CDATA[framework]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[xcode]]></category>
            <dc:creator><![CDATA[Kenny Lemon]]></dc:creator>
            <pubDate>Sun, 14 Aug 2022 22:03:06 GMT</pubDate>
            <atom:updated>2022-08-14T22:03:06.389Z</atom:updated>
            <content:encoded><![CDATA[<p>Carthage, eGoogleCast</p><h3>前情提要</h3><p>有個開發已久的專案（以下簡稱 V 專案），規劃新增功能，而這個功能已經有個共用模組存在於公司內；為什麼呢？設計上，前輩大神們覺得未來其他專案用到就可以直接套用，何樂而不為！先講，真正的坑在於，專案同時使用了 <strong>Carthage</strong> 和 <strong>GoogleCast</strong>；如果你的專案運氣很好沒有同時使用它倆，恭喜你，這篇就當鬼故事看看就好了 XD。</p><p>既然公司內部已經有現成又好用的 Framework，想當然的就直接套用到現有的專案中就好啦！偏偏事情總是沒有想像中這麼順利！</p><h3>踩坑實錄</h3><p>事情是這麼開始的，要套用現有的 Framework 方法有很多，我先用 carthage.sh 產生出要用的 Framework，然後在 V 專案中引用。</p><p>完成上述設定，萬事就緒，按下 Command+R ，泡杯開咖啡等著測試。</p><p>驚！無法安裝 app 到實機。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/516/1*UgvTMhdQ8PHQ65xfJgULag.png" /><figcaption>圖 1. Unable to install “your app”</figcaption></figure><p>點了 Details 進去一探究竟，”<strong>No code signature found.</strong>”，也看不出什麼東西沒有 signature！</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o1VoARQgNd9DqaR9MxQRhg.png" /><figcaption>圖 2. Unable to install “your app”, Details</figcaption></figure><p>來看看 Xcode build 的時候是不是出了什麼問題。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KUt-xaOP8aVjIeMm0X_RSA.png" /><figcaption>圖 3. fatal error: lipo 失敗</figcaption></figure><p>lipo 失敗，原來壓根沒有 input file 可以做 lipo。</p><p>正常來說，Framework library 就是這個被 Finder 判定為 Unix Executable File 的檔案，但上述 lipo 要操作的 Framework 資料夾中就出現了 can’t open input file 的錯誤了。登愣，就是它了。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0F2A8lL6X7_d4ebmYEx26Q.png" /><figcaption>圖 4. Framework Library</figcaption></figure><p>猜想可能是針對 Framework 做了兩次，所以就什麼都不剩了。試試先在 GoogleCast 上架前用的 strip_unused_archs.sh 加上這段。目的是讓 shell script 略過這幾個 carthage.sh 產出的 Framework，不要再 remove unused architectures。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UrT4EOLoVbZhaoyAGDzL7g.png" /><figcaption>圖 5. 解</figcaption></figure><p>實際驗證上傳 ipa 也可成功。這坑花了不少時間處理，記錄下來，也希望對大家有幫助。</p><h3>附註</h3><h4><a href="https://medium.com/r?url=https%3A%2F%2Fgithub.com%2FCarthage%2FCarthage%2Fblob%2Fmaster%2FDocumentation%2FXcode12Workaround.md">Carthage</a></h4><p>在 M1 的機器上打包 XCFramework 會同時產出 device 使用的 arm64 binary 以及 simulator 使用的 arm64 binary，但間接導致 Carthage 在 link 的時候會不知道要 ling 到哪個導致錯誤的產生。而 Carthage 也意識到這點，出了個 workaround；也就是 carthage.sh 如下。</p><pre># carthage.sh<br># Usage example: ./carthage.sh build --platform iOS<br><br>set -euo pipefail<br> <br>xcconfig=$(mktemp /tmp/static.xcconfig.XXXXXX)<br>trap &#39;rm -f &quot;$xcconfig&quot;&#39; INT TERM HUP EXIT<br> <br># For Xcode 12 make sure EXCLUDED_ARCHS is set to arm architectures otherwise<br># the build will fail on lipo due to duplicate architectures.<br> <br>CURRENT_XCODE_VERSION=&quot;$(xcodebuild -version | grep &quot;Xcode&quot; | cut -d&#39; &#39; -f2 | cut -d&#39;.&#39; -f1)00&quot;<br>CURRENT_XCODE_BUILD=$(xcodebuild -version | grep &quot;Build version&quot; | cut -d&#39; &#39; -f3)<br><br>echo &quot;EXCLUDED_ARCHS__EFFECTIVE_PLATFORM_SUFFIX_simulator__NATIVE_ARCH_64_BIT_x86_64__XCODE_${CURRENT_XCODE_VERSION}__BUILD_${CURRENT_XCODE_BUILD} = arm64 arm64e armv7 armv7s armv6 armv8&quot; &gt;&gt; $xcconfig<br> <br>echo &#39;EXCLUDED_ARCHS__EFFECTIVE_PLATFORM_SUFFIX_simulator__NATIVE_ARCH_64_BIT_x86_64__XCODE_&#39;${CURRENT_XCODE_VERSION}&#39; = $(EXCLUDED_ARCHS__EFFECTIVE_PLATFORM_SUFFIX_simulator__NATIVE_ARCH_64_BIT_x86_64__XCODE_$(XCODE_VERSION_MAJOR)__BUILD_$(XCODE_PRODUCT_BUILD_VERSION))&#39; &gt;&gt; $xcconfig<br>echo &#39;EXCLUDED_ARCHS = $(inherited) $(EXCLUDED_ARCHS__EFFECTIVE_PLATFORM_SUFFIX_$(EFFECTIVE_PLATFORM_SUFFIX)__NATIVE_ARCH_64_BIT_$(NATIVE_ARCH_64_BIT)__XCODE_$(XCODE_VERSION_MAJOR))&#39; &gt;&gt; $xcconfig<br><br>export XCODE_XCCONFIG_FILE=&quot;$xcconfig&quot;<br>carthage &quot;$@&quot;</pre><h4><a href="https://developers.google.com/cast/docs/ios_sender">Google Cast</a></h4><p>GoogleCast 的 Develop iOS Sender App 的最後一段，Publishing your app to app store 提到，要在 shell script 使用 strip_unused_archs.sh。可以看到 shell script 就是移除用不到的 architecture；讓他變成不是一個 fat library。</p><pre>#!/bin/bash</pre><pre># This script strips unused architectures from any frameworks embedded in an<br># app bundle. It should be called from an Xcode project as a post-build step.</pre><pre>if [ -z &quot;${TARGET_BUILD_DIR}&quot; ]; then<br>  echo &quot;This script should be invoked from an Xcode project.&quot;<br>  exit 1<br>fi</pre><pre>app_dir=&quot;${TARGET_BUILD_DIR}/${WRAPPER_NAME}&quot;</pre><pre>framework_dirs=($(find &quot;${app_dir}&quot; -type d -name &#39;*.framework&#39;))<br>for framework_dir in &quot;${framework_dirs[@]}&quot;; do<br>  framework_name=$(defaults read &quot;${framework_dir}/Info.plist&quot; CFBundleExecutable)<br>  framework_path=&quot;${framework_dir}/${framework_name}&quot;</pre><pre>echo &quot;Removing unused architectures from framework: ${framework_name}&quot;</pre><pre>slice_paths=()<br>  for arch in ${ARCHS}; do<br>    slice_path=&quot;${framework_path}_${arch}&quot;<br>    lipo &quot;${framework_path}&quot; -extract &quot;${arch}&quot; -output &quot;${slice_path}&quot;<br>    slice_paths+=(&quot;${slice_path}&quot;)<br>  done</pre><pre>lipo &quot;${slice_paths[@]}&quot; -create -output &quot;${framework_path}_thinned&quot;<br>  rm -f &quot;${slice_paths[@]}&quot;</pre><pre>rm -f &quot;${framework_path}&quot;<br>  mv &quot;${framework_path}_thinned&quot; &quot;${framework_path}&quot;<br>done</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7a2fb07454d2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[如何整合 SwiftUI 與現存專案]]></title>
            <link>https://medium.com/@kennylemon/%E5%A6%82%E4%BD%95%E6%95%B4%E5%90%88-swiftui-%E8%88%87%E7%8F%BE%E5%AD%98%E5%B0%88%E6%A1%88-84d7a1df5418?source=rss-6a39ef480c3b------2</link>
            <guid isPermaLink="false">https://medium.com/p/84d7a1df5418</guid>
            <category><![CDATA[wwdc-2019]]></category>
            <category><![CDATA[wwdc19]]></category>
            <category><![CDATA[wwdc]]></category>
            <category><![CDATA[swiftui]]></category>
            <dc:creator><![CDATA[Kenny Lemon]]></dc:creator>
            <pubDate>Tue, 13 Aug 2019 06:42:43 GMT</pubDate>
            <atom:updated>2019-08-13T08:51:08.833Z</atom:updated>
            <content:encoded><![CDATA[<p>整理並紀錄 WWDC 19 的 session [231] Integrating SwiftUI；瞭解既有專案與 SwiftUI 之間該如何整合．</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/956/1*4I4B8xhyQZ1Dk0kB1NdWCA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/955/1*oC2dODNkbdDgXH-2D_VxXw.png" /><figcaption>Goals of session [231] Integrating SwiftUI</figcaption></figure><h3>Hosting SwiftUI views in your app</h3><p>Apple 針對不同的平台提供相對應的 Hosting Controller；除了下列三種之外，也提供 AppKit 相對應的 NSHostingView．</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/955/1*DeX-F6nV4aauUfXdna5jSQ.png" /><figcaption>Hosting Controller</figcaption></figure><p>將 SwiftUI 以 Hosting Controller 包起來之後，不論在 Code 或 Interface Builder 中都可直接使用該 class 名稱．若需要更新 SwiftUI 也是直接針對該 class 名稱進行操作．</p><h3>Embedding existing views in SwiftUI</h3><p>根據 <a href="https://developer.apple.com/documentation/swiftui/uiviewrepresentable">官方文件</a>，在 SwiftUI 中使用 Swift 寫好的 UI 元件，得先讓原有的 UI 元件 conform Representable protocol，並實作 Make 和 Update method，即可於 SwiftUI 中使用該 structure 或 class．</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/954/1*O7ljyRgAEo7RAF3xDm0Wfg.png" /><figcaption>Representable Protocol</figcaption></figure><p>另外，還有 makeCoordinator 及 Dismantle method 供開發使用．</p><p><strong>MakeCoordinator method (required)：</strong>已提供預設實作，可忽略．要實作 delegate, target/action⋯等 pattern 需要額外實作 coordinator 及 makeCoordinator method．</p><p><strong>Make method (required)：</strong>中產生 UI 元件或 class 的 instance；此 method 只會在這個 class 被 init 時執行一次</p><p><strong>Update method (required)：</strong>中則是針對目前狀態更新 UI；任何 SwiftUI 需要更新這個 class 的 UI 或是有呼叫更新 UI 的時候都會呼叫到這個 method．</p><p><strong>Dismantle method</strong> <strong>(optional)：</strong>提供 View/Controller 被 remove 之前一個 callback 的時間點讓開發者做適當的處理．</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/955/1*Kx9cZpFLKeyDQY4q-dYwow.png" /><figcaption>Life cycle of Representable Protocol</figcaption></figure><ol><li>若有實作 makeCoodinator，此 method 會是第一個被呼叫．</li><li>接著 Make method 被呼叫並產生出對應的 instance．</li><li>需要更新畫面時呼叫 Update method．</li><li>在該 View/Controller 被 remove 前呼叫 Dismantle ．</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/957/1*ZDY4jzM_JvfCQ6RQtIkJ4Q.png" /><figcaption>Representable Context</figcaption></figure><p>Representable Context 是 SwiftUI 與 UIKit/AppKit/WatchKit 的互相溝通的媒介，且會由 Make 及 Update method 當作參數提供．Context 包含的資訊有 Coordinator，Environment 與 Transaction．而</p><p><strong>Coordinator：</strong>作為 view/view controller 與 SwiftUI 之間的溝通橋樑，並可實作 pattern 達成溝通的目的；例如，target/action，delegation pattern ⋯等．若需要使用 Coordinator 開發者需要自行建立，並 override makeCoordinator method．</p><p><strong>Environment：</strong>藉此可取得系統相關的 configuration；例如，color schemes, layout direction⋯等．</p><p><strong>Transaction：</strong>藉此可知 SwiftUI 是否包含 Animation．</p><h3>Integrating your data model</h3><p>藉由wrapper和combine framework讓 Data Model 及其中的 Dynamic data 得以被 SwiftUI Binding 甚至藉有前綴字$讓 SwiftUI 直接操作 Data Model 中的 data</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/953/1*sspCvUpmhQkoHkF8uQuM1w.png" /><figcaption>BindableObject 與 ObjectBinding 之間的關係</figcaption></figure><p>p.s. 根據 iOS 13 Release Notes</p><blockquote>@BindableObject 更名為 @ObservableObject<em>，且使用方式也有些微調整</em></blockquote><blockquote>@ObjectBinding 更名為 @ObservedObject</blockquote><p><a href="https://developer.apple.com/documentation/ios_ipados_release_notes/ios_ipados_13_beta_6_release_notes">iOS &amp; iPadOS 13 Beta 6 Release Notes</a></p><h3>Integrating with the system</h3><p>SwiftUI 不僅提供簡單的方式以整合目前的專案，也提供 function 可直接於 SwiftUI 使用以整合各平台不同的功能；例如，Drag and Drop, Focus, Command</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/954/1*T0APDQdsfw8axmN9SN_zqQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/955/1*nUX9lF2lKqCwl5u0gKbX8g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/955/1*QTIA8pxsfppatL3bYtXCMw.png" /></figure><h3>Integrating with Objective-C</h3><p>簡而言之，要先用 Swift 把 SwiftUI 包起來，並使用 Swift 和 Objective-C Bridging 使用的 wrapper 及 class．</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/955/1*Wv1W9s7iG1TY5wFMb0E6Mg.png" /><figcaption>Wrap SwiftUI in Swift class and use @objc</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/956/1*K5YFIC4XR4HOI9H2xhCnSQ.png" /><figcaption>Wrap Data model in Swift</figcaption></figure><h3>延伸閱讀</h3><ul><li><a href="https://developer.apple.com/tutorials/swiftui">Introducing SwiftUI | Apple Developer Documentation</a></li><li><a href="https://developer.apple.com/documentation/combine">Combine | Apple Developer Documentation</a></li><li><a href="https://developer.apple.com/documentation/ios_ipados_release_notes/ios_ipados_13_beta_6_release_notes">iOS &amp; iPadOS 13 Beta 6 Release Notes</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=84d7a1df5418" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>