<?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 Jeff Lin on Medium]]></title>
        <description><![CDATA[Stories by Jeff Lin on Medium]]></description>
        <link>https://medium.com/@koloa1989?source=rss-29f0f755c933------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*WlwF3wfsC2uAv4dZAmT5zA@2x.jpeg</url>
            <title>Stories by Jeff Lin on Medium</title>
            <link>https://medium.com/@koloa1989?source=rss-29f0f755c933------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 23:44:14 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@koloa1989/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[# 37 初窺 Responder Chain]]></title>
            <link>https://medium.com/peter-pan-swift-ios-class/37-%E5%88%9D%E7%AA%BA-responder-chain-ac5116d65800?source=rss-29f0f755c933------2</link>
            <guid isPermaLink="false">https://medium.com/p/ac5116d65800</guid>
            <dc:creator><![CDATA[Jeff Lin]]></dc:creator>
            <pubDate>Wed, 09 Jul 2025 15:37:12 GMT</pubDate>
            <atom:updated>2025-07-10T01:18:08.224Z</atom:updated>
            <content:encoded><![CDATA[<p>最近有幸碰到 responder chain，因此有研究一下，以下是紀錄心得。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/374/1*VRprtdOl6PHrPurTOEzMmw.png" /><figcaption>請支持貓貓蟲咖波</figcaption></figure><pre><a href="#851c">定義</a><br><a href="#0470">傳遞過程</a><br> <a href="#cb98">1.傳遞過程分兩階段</a><br> <a href="#a878">2.範例</a><br><a href="#9802">應用</a><br> <a href="#9827">1.跨元件的訊息傳遞</a><br> <a href="#59c4">2.Menu 應用</a><br><a href="#fb0c">備註</a><br><a href="#6172">結語</a><br><a href="#4503">Reference</a><br><a href="#9238">GitHub</a></pre><h3>定義：</h3><p>由一群繼承 <strong>UIResponder</strong> 的 subClass 物件所組成的溝通路徑，負責傳遞觸控事件和其他訊息，採用單一的線性傳遞關係。</p><h3>傳遞過程：</h3><h4>傳遞過程分兩階段</h4><ol><li><strong>Hit Testing 階段：找尋響應元件</strong></li></ol><p>收到觸控事件時，會從 UIWindow 開始傳遞訊息，觸發每個 UIResponder 物件的 hitTest，他會找到會找到<strong>最深層且包含此觸碰點</strong>的元件，並回傳自己，因此上層的每個 hitTest method 就會回傳該元件，該元件就是 responder chain 的開端。</p><blockquote>UIKit 的 <strong>hitTest(_:with:)</strong>方法說明：Returns the farthest descendant of the receiver in the view hierarchy (including itself) that contains a specified point.</blockquote><p><strong>2. 找尋 First Responder：</strong></p><p>Responder chain 在傳遞時，會由 hitTest 回傳的元件開始，將事件傳遞給屬性 next 所指向的物件，UIKit 會尋找最適合處理該次事件的物件，該物件就稱為 <strong>First Responder</strong>。</p><p>需要補充的是，First Responder 是指能夠處理特定事件的物件，不一定是 hitTest 找到的元件。</p><p>如果最後傳到 UIApplication 時，都沒有適合的物件 handle 這次的觸控事件，此次觸控事件就會被丟棄。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7lz3RqRPjWr5EPDKfo3rjA.png" /></figure><p>但要注意的是，<strong>accelerometers</strong>、<strong>gyroscopes</strong>、<strong>magnetometer</strong> 不會將訊息傳遞給 responder chain。</p><h4>範例：</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*3ci61nFBvBblTF8jU4Mx5g.png" /></figure><p>上圖是這次要測試的 view Hierarchy，藉由觸碰 view，來觀察 action 的傳遞。</p><p><strong>測試一： hitTest 傳遞鏈</strong></p><p>View 的設定如下</p><pre>// ViewA<br>class ViewA: UIView <br>    override func hitTest(_ point: CGPoint, with event: UIEvent?) -&gt; UIView? {<br>        let view = super.hitTest(point, with: event)<br>        print(&quot;ViewA:\(view)&quot;)<br>        return view<br>    }<br>}</pre><pre>// ViewB<br>class ViewB: UIView<br>    override func hitTest(_ point: CGPoint, with event: UIEvent?) -&gt; UIView? {<br>        let view = super.hitTest(point, with: event)<br>        print(&quot;ViewB:\(view)&quot;)<br>        return view<br>    }<br>}</pre><pre>// ViewC<br>class ViewC: UIView {<br>   override func hitTest(_ point: CGPoint, with event: UIEvent?) -&gt; UIView? {<br>        let view = super.hitTest(point, with: event)<br>        print(&quot;ViewC:\(view)&quot;)<br>        return view<br>    }<br>}</pre><p>接著觸碰 ViewC，Log 如下：</p><pre>ViewC:Optional(&lt;ResponderChainDemo.ViewC: 0x10501f990; frame = (29 20; 211 249); autoresize = RM+BM; backgroundColor = UIExtendedSRGBColorSpace -0.0241361 0.599982 1.00121 1; layer = &lt;CALayer: 0x600000241ea0&gt;&gt;)<br>ViewB:Optional(&lt;ResponderChainDemo.ViewC: 0x10501f990; frame = (29 20; 211 249); autoresize = RM+BM; backgroundColor = UIExtendedSRGBColorSpace -0.0241361 0.599982 1.00121 1; layer = &lt;CALayer: 0x600000241ea0&gt;&gt;)<br>ViewA:Optional(&lt;ResponderChainDemo.ViewC: 0x10501f990; frame = (29 20; 211 249); autoresize = RM+BM; backgroundColor = UIExtendedSRGBColorSpace -0.0241361 0.599982 1.00121 1; layer = &lt;CALayer: 0x600000241ea0&gt;&gt;)<br>ViewC:Optional(&lt;ResponderChainDemo.ViewC: 0x10501f990; frame = (29 20; 211 249); autoresize = RM+BM; backgroundColor = UIExtendedSRGBColorSpace -0.0241361 0.599982 1.00121 1; layer = &lt;CALayer: 0x600000241ea0&gt;&gt;)<br>ViewB:Optional(&lt;ResponderChainDemo.ViewC: 0x10501f990; frame = (29 20; 211 249); autoresize = RM+BM; backgroundColor = UIExtendedSRGBColorSpace -0.0241361 0.599982 1.00121 1; layer = &lt;CALayer: 0x600000241ea0&gt;&gt;)<br>ViewA:Optional(&lt;ResponderChainDemo.ViewC: 0x10501f990; frame = (29 20; 211 249); autoresize = RM+BM; backgroundColor = UIExtendedSRGBColorSpace -0.0241361 0.599982 1.00121 1; layer = &lt;CALayer: 0x600000241ea0&gt;&gt;)</pre><p>可以發現，每個 view 的 hitTest 都回傳 ViewC，表示系統藉由 hitTest 找到開始 responding chain 傳遞的開端是 ViewC。</p><p><strong>測試二：觀察 responding chain 的傳遞</strong></p><p>首先，先進入 UIResponder 裡面看原始定義的內容，可以發現，只要有遵從 UIResponder，都會有 touch 事件的 method。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VqKThEESLolBpud4d55aMA.png" /></figure><p>當觸控事件在 responder chain 傳遞時，每個響應者都會觸發對應的 touches 方法，而這些 touches 的預設是再將 event 或訊息往上游傳遞。拿 touchesBegan 當範例：</p><blockquote><strong><em>Discussion<br></em></strong><em>UIKit calls this method when a new touch is detected in a view or window. Many UIKit classes override this method and use it to handle the corresponding touch events. The </em><strong><em>default implementation of this method forwards the message up the responder chain.</em></strong><em> When creating your own subclasses, call </em><em>super to forward any events that you don’t handle yourself, like in the following code.</em></blockquote><p>因為預設 touches 方法在元件接收到事件時會觸發，因此很適合拿來觀察事件的傳遞。接下來我會改寫每個 view 的 touchesBegan，當該元件接收到 action 後，會觸發 touchesBegan，讓他們 print 出 log。</p><pre>// ViewA<br>class ViewA: UIView <br>    ......<br>    <br>    override func touchesBegan(_ touches: Set&lt;UITouch&gt;, with event: UIEvent?) {<br>        print(&quot;ViewA 被觸碰了&quot;)<br>        super.touchesBegan(touches, with: event)<br>    }<br>}</pre><pre>// ViewB<br>class ViewB: UIView<br>    ......<br>    <br>    override func touchesBegan(_ touches: Set&lt;UITouch&gt;, with event: UIEvent?) {<br>        print(&quot;ViewB 被觸碰了&quot;)<br>        super.touchesBegan(touches, with: event)<br>    }<br>}</pre><pre>// ViewC<br>class ViewC: UIView {<br>   ......<br>    <br>    override func touchesBegan(_ touches: Set&lt;UITouch&gt;, with event: UIEvent?) {<br>        print(&quot;ViewC 被觸碰了&quot;)<br>        super.touchesBegan(touches, with: event)<br>    }<br>}</pre><p>如果觸碰 ViewC，結果如下：</p><pre>ViewC 被觸碰了<br>ViewB 被觸碰了<br>ViewA 被觸碰了</pre><p>可以觀察到，當 ViewC 先被觸發，接下來是上游的 ViewB，在接下來是 ViewA：一條由下往上的傳遞路徑。</p><h3>應用：</h3><h4>1. 跨元件的訊息傳遞</h4><p>可以利用 responder chain 的原理，讓訊息跨元件傳遞。</p><p>本次測試的元件關係如下：</p><blockquote>PassViewController 擁有 FirstPassView<br>FirstPassView 擁有 SecondPassView<br>SecondPassView 擁有 Button</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*D87j91QBoaYMMF2sK20ySA.png" /></figure><p>接著，我想要按下 button 後，可以讓上游的元件跳出 alertController，實作如下：</p><ol><li><strong>拓展 UIResponder 功能</strong></li></ol><p>next 屬性指向 responder chain 中的下一個響應者。因此當最上游的 button 呼叫 sentAction 時，就會呼叫下一個響應者呼叫 sentAction，因此這次的觸控事件就可以藉由 responder chain 傳遞下去。</p><pre>extension UIResponder {<br>    @objc func sentAction() {<br>        next?.sentAction()<br>    }<br>}</pre><p><strong>2. 在指定元件覆寫 sentAction</strong></p><p>在 Swift 中，extension 裡的方法預設無法被子類別覆寫。<br>但加上 <strong>@objc</strong> 標記後，該方法會暴露給 Objective-C runtime，<br>使得子類別可以覆寫這個方法，同時也讓 responder chain 的訊息傳遞機制能夠正常運作。</p><p>接著，我在元件裡覆寫 sentAction，讓他們產生 alert：</p><pre>// SecondPassView<br>class SecondPassView: UIView {  <br>    ...<br>    override init(frame: CGRect) {<br>        ...<br>        button.addTarget(self, action: #selector(tapBtn), for: .touchUpInside)<br>    }<br>    @objc func tapBtn() {<br>        sentAction()<br>    }<br>}<br><br>extension SecondPassView {<br>    override func sentAction() {<br>        let alert = UIAlertController(title: &quot;Event&quot;, message: &quot;SecondPassView 收到 Event&quot;, preferredStyle: .alert)<br>        let alertAction = UIAlertAction(title: &quot;確定&quot;, style: .default)<br>        alert.addAction(alertAction)<br>        if let rootController = findViewController() as? PassViewController {<br>            rootController.present(alert, animated: true)<br>        }<br>    }<br>}</pre><pre>// FirstPassView<br>extension FirstPassView {<br>    override func sentAction() {<br>        let alert = UIAlertController(title: &quot;Event&quot;, message: &quot;FirstPassView 收到 Event&quot;, preferredStyle: .alert)<br>        let alertAction = UIAlertAction(title: &quot;確定&quot;, style: .default)<br>        alert.addAction(alertAction)<br>        if let rootController = findViewController() as? PassViewController {<br>            rootController.present(alert, animated: true)<br>        }<br>    }<br>}</pre><pre>// PassViewController<br>extension PassViewController {<br>    override func sentAction() {<br>        let alert = UIAlertController(title: &quot;Event&quot;, message: &quot;PassViewController 收到 Event&quot;, preferredStyle: .alert)<br>        let alertAction = UIAlertAction(title: &quot;確定&quot;, style: .default)<br>        alert.addAction(alertAction)<br>        present(alert, animated: true)<br>    }<br>}</pre><p>點下按鈕後結果如下：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*q6EFNsHDcRXdLMnC4YdFYg.png" /></figure><p>三個元件都有實作 sentAction，但實際結果顯示，按鈕按下後，只有 <strong>SecondPassView 會跳出 alert。</strong></p><p>原因是按鈕呼叫 sentAction() 後，事件傳遞到 SecondPassView，由於我們覆寫了 SecondPassView 的 sentAction 但沒有呼叫 super.sentAction()，事件傳遞就此中斷，無法繼續向上傳遞給 FirstPassView 和 PassViewController。</p><p>如果想讓事件繼續傳遞到上層元件，有兩個解決方法：</p><ol><li>移除 SecondPassView 和 FirstPassView 的 sentAction 覆寫，讓事件直接傳遞到 PassViewController</li><li>2. 在 SecondPassView 和 FirstPassView 的 sentAction 中呼叫 super.sentAction()，確保事件繼續向上傳遞</li></ol><pre>extension FirstPassView {<br>    override func sentAction() {<br>        super.sentAction()<br>    }<br>}<br><br>extension SecondPassView {<br>    override func sentAction() {<br>        super.sentAction()<br>    }<br>}</pre><h3>Menu 應用：</h3><p>responder chain 的概念也可以使用在 Menu 上，以下是簡易的示範：</p><p>長按 Label，可叫出 Menu 選單，針對不同選項，可以呼叫不同元件執行動作。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XOaJ7KbSCziY0UlT6WJcnw.gif" /></figure><h4>實作：</h4><p><strong>設定 Label：</strong></p><p>建立一個 UIContextMenuInteraction 物件，這個物件會讓 view 支援長按出現上下文選單。這邊傳入 delegate: self，表示這個 view 要實作 UIContextMenuInteractionDelegate 協定來提供選單的內容。</p><p>最後再將剛剛建立的 interaction 加入到這個 view 中，表示這個 view 現在具備「觸發 context menu」的互動能力。</p><pre>override init(frame: CGRect) {<br>    super.init(frame: frame)<br>    isUserInteractionEnabled = true<br>    let interaction = UIContextMenuInteraction(delegate: self)<br>    addInteraction(interaction)<br>}</pre><p><strong>設定 method：</strong></p><p>在這個範例裡，有三個任務會被觸發：<strong>複製</strong>、<strong>打開網站</strong>、以及<strong>分享網址</strong>的功能。因此接下來設定觸發選項的 method。</p><pre><br>extension URLLabel: UIContextMenuInteractionDelegate {<br>    func contextMenuInteraction(_ interaction: UIContextMenuInteraction,<br>                                 configurationForMenuAtLocation location: CGPoint) -&gt; UIContextMenuConfiguration? {<br>        return UIContextMenuConfiguration(identifier: nil, previewProvider: nil) { _ in<br><br>            // 建立一個空選單，系統會自動去 responder chain 尋找能響應這些 selector 的物件<br>            let copy = UIAction(title: &quot;Copy&quot;, image: UIImage(systemName: &quot;doc.on.doc&quot;), handler: { _ in<br>                UIApplication.shared.sendAction(#selector(self.copyURL), to: nil, from: self, for: nil)<br>            })<br><br>            let open = UIAction(title: &quot;Open in Safari&quot;, image: UIImage(systemName: &quot;safari&quot;), handler: { _ in<br>                UIApplication.shared.sendAction(#selector(URLActionProvider.openInSafari), to: nil, from: self, for: nil)<br>            })<br><br>            let share = UIAction(title: &quot;Share&quot;, image: UIImage(systemName: &quot;square.and.arrow.up&quot;), handler: { _ in<br>                UIApplication.shared.sendAction(#selector(URLActionProvider.shareURL), to: nil, from: self, for: nil)<br>            })<br><br>            return UIMenu(title: &quot;&quot;, children: [copy, open, share])<br>        }<br>    }<br>}</pre><p><em>選單配置</em>：當使用者常按時，會觸發 delegate 呼叫這個contextMenuInteraction，要我們提供系統選單。</p><pre>func contextMenuInteraction(_ interaction: UIContextMenuInteraction,<br>                             configurationForMenuAtLocation location: CGPoint) -&gt; UIContextMenuConfiguration? </pre><p><em>選單配置方法</em>：這是當使用者長按這個 view 時，系統會詢問你：「請給我一個上下文選單的設定」。</p><pre>return UIContextMenuConfiguration(identifier: nil, previewProvider: nil) { _ in<br>   // 回傳選單選項<br>}</pre><p><em>回傳選單選項</em>：這邊提供一個 UIMenu，它會在UIContextMenuConfiguration 的 closure 中建立。</p><pre>// 建立一個空選單，系統會自動去 responder chain 尋找能響應這些 selector 的物件<br>let copy = UIAction(title: &quot;Copy&quot;, image: UIImage(systemName: &quot;doc.on.doc&quot;), handler: { _ in<br>    UIApplication.shared.sendAction(#selector(self.copyURL), to: nil, from: self, for: nil)<br>})<br><br>let open = UIAction(title: &quot;Open in Safari&quot;, image: UIImage(systemName: &quot;safari&quot;), handler: { _ in<br>    UIApplication.shared.sendAction(#selector(URLActionProvider.openInSafari), to: nil, from: self, for: nil)<br>})<br><br>let share = UIAction(title: &quot;Share&quot;, image: UIImage(systemName: &quot;square.and.arrow.up&quot;), handler: { _ in<br>    UIApplication.shared.sendAction(#selector(URLActionProvider.shareURL), to: nil, from: self, for: nil)<br>})<br><br>return UIMenu(title: &quot;&quot;, children: [copy, open, share])</pre><p>接著重點來了，當按下選項後，handler 執行的程式碼，正式啟動 responder chain 的關鍵。</p><pre>UIApplication.shared.sendAction(#selector(URLActionProvider.openInSafari), to: nil, from: self, for: nil</pre><p>當 to 為<strong>傳入物件</strong>時，sendAction 的 event 由該物件接收，並執行 #selector 傳入的 method。然而，當 to 為 <strong>nil</strong> 時，表示這個 sendAction 的 event 會由 <strong>responder chain 的開端</strong>，一路向上尋找有實作 URLActionProvider.openInSafari 的物件執行此功能。</p><p>而 URLActionProvider 的定義如下，並由 UIResponder 拓展這個 method，這段設計讓任何 UIResponder 子類（如 UIView、UIViewController、UIApplication 等）都具備預設的轉發能力，因此當目前物件無法處理這個 selector 時，就會自動轉給 next 這個 responder，直到找到會實作對應方法的物件為止。</p><p>而因為 sendAction(_:) 只能傳送給 Objective-C runtime 可識別的方法，所以 protocol 必須標示為 @objc 。</p><pre>@objc protocol URLActionProvider {<br>    func openInSafari()<br>    func shareURL()<br>}<br><br>extension UIResponder: URLActionProvider {<br>    func shareURL() {<br>        next?.shareURL()<br>    }<br>    func openInSafari() {<br>        next?.openInSafari()<br>    }<br>}</pre><p>最後就是<strong>指定 responder chain 中的響應者</strong>來具體執行對應功能：URLLabel 處理複製文字、MenuViewController 處理分享、UIApplication 處理打開 Safari。</p><pre>class URLLabel: UILabel {<br>    ......<br>    @objc func copyURL() {<br>        UIPasteboard.general.string = text<br>        print(&quot;📋 Copied: \(text ?? &quot;&quot;)&quot;)<br>    }<br>    ......<br>}<br><br><br>extension MenuViewController {<br>    override func shareURL() {<br>        guard let label = self.view.subviews.compactMap({ $0 as? URLLabel }).first,<br>              let text = label.text else { return }<br>        <br>        let activityVC = UIActivityViewController(activityItems: [text], applicationActivities: nil)<br>        self.present(activityVC, animated: true)<br>        print(&quot;📤 \(self) Share triggered: \(text)&quot;)<br>    }<br>    <br>    override func openInSafari() {<br>        print(&quot;MenuViewController: MenuViewController do not handle shareURL&quot;)<br>        super.openInSafari()<br>    }<br>}<br><br>extension UIApplication {<br>    override func openInSafari() {<br>        guard let rootVC = windows.first?.rootViewController as? MenuViewController,<br>              let label = rootVC.view.subviews.compactMap({ $0 as? URLLabel }).first,<br>              let text = label.text,<br>              let url = URL(string: text) else { return }<br>        UIApplication.shared.open(url)<br>        print(&quot;🌐 \(self) Opened in Safari: \(text)&quot;)<br>    }<br>    <br>    override func shareURL() {<br>        print(&quot;UIApplication: UIApplication do not handle shareURL&quot;)<br>        super.shareURL()<br>    }<br>}</pre><p>最後，再為這個範例的流程做個說明：</p><pre>舉例來說，當使用者點選「Open in Safari」：<br>1. URLLabel 觸發 context menu，執行 sendAction。<br>2. `to: nil` 表示從 URLLabel 開始向上找。<br>3. URLLabel 沒有實作 openInSafari，轉給 MenuViewController。<br>4. MenuViewController 有覆寫此方法，決定由自己處理或往上交給 `UIApplication`。<br>5. 最終 UIApplication 取得網址並打開 Safari。</pre><h3>備註</h3><p>可以藉由 next 來找這次能處理 event 的響應者有哪些：</p><pre>// 檢查 responder chain 結構<br>var responder: UIResponder? = self<br>print(&quot;=== Responder Chain ===&quot;)<br>while responder != nil {<br>    print(&quot;\(type(of: responder!))&quot;)<br>    responder = responder?.next<br>}<br>print(&quot;======================&quot;)</pre><h3>結語</h3><p>這樣子的設計對於內層元件要傳遞消息到上層時，<strong>不需要在每個上層的每個元件中建立額外的 closure 或 delegate</strong> 來傳遞事件，這讓事件傳遞更自然、簡潔。</p><p><strong>而事件傳遞也因為有單一方向與唯一目標</strong>，沿著 responder chain 一個個往上找，直到找到第一個能處理的物件為止，所以不會像觀察者模式那樣，出現多個元件同時收到訊號的情況，避免邏輯衝突。</p><p>以上就是這次閱讀許多文章後紀錄的心得，若有錯誤請指教，謝謝！</p><h3>Reference：</h3><ul><li><a href="https://developer.apple.com/documentation/uikit/using-responders-and-the-responder-chain-to-handle-events">Using responders and the responder chain to handle events | Apple Developer Documentation</a></li><li><a href="https://zhongwei0717.medium.com/%E4%B8%8D%E8%A6%81%E5%B7%B2%E8%AE%80%E4%B8%8D%E5%9B%9E-ios-%E7%9A%84-responder-chain-cc836d7c9e61">不要已讀不回！ iOS 的 Responder Chain</a></li><li><a href="https://www.appcoda.com.tw/responder-chain/">淺談回應鏈 (Responder Chain)　讓你認識這個靈活又實用的設計模式！</a></li></ul><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Fle7tzeqN908%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3Dle7tzeqN908&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2Fle7tzeqN908%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/16ac5b08d353f8563902fb0a28dfd010/href">https://medium.com/media/16ac5b08d353f8563902fb0a28dfd010/href</a></iframe><p><a href="https://juejin.cn/post/7065483072698843143">https://juejin.cn/post/7065483072698843143</a></p><p><a href="https://stackoverflow.com/questions/73295486/why-isfirstresponder-for-uitouchevent-is-returning-false-when-i-touch-a-uivie">https://stackoverflow.com/questions/73295486/why-isfirstresponder-for-uitouchevent-is-returning-false-when-i-touch-a-uivie</a></p><h3>GitHub：</h3><p><a href="https://github.com/ChingDD/ResponderChainDemo">GitHub - ChingDD/ResponderChainDemo</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ac5116d65800" width="1" height="1" alt=""><hr><p><a href="https://medium.com/peter-pan-swift-ios-class/37-%E5%88%9D%E7%AA%BA-responder-chain-ac5116d65800"># 37 初窺 Responder Chain</a> was originally published in <a href="https://medium.com/peter-pan-swift-ios-class">彼得潘的 Swift iOS / Flutter App 開發教室</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[#36 解決 Cursor 與 Xcode 檔案無法同步]]></title>
            <link>https://medium.com/peter-pan-swift-ios-class/36-%E8%A7%A3%E6%B1%BA-cursor-%E8%88%87-xcode-%E6%AA%94%E6%A1%88%E7%84%A1%E6%B3%95%E5%90%8C%E6%AD%A5-c120259ce0bc?source=rss-29f0f755c933------2</link>
            <guid isPermaLink="false">https://medium.com/p/c120259ce0bc</guid>
            <dc:creator><![CDATA[Jeff Lin]]></dc:creator>
            <pubDate>Sat, 05 Jul 2025 11:26:16 GMT</pubDate>
            <atom:updated>2025-07-06T15:49:54.582Z</atom:updated>
            <content:encoded><![CDATA[<p>前言：最近開始嘗試出一張嘴開發程式， Cursor 幫我新增了檔案到專案，然而，Xcode 的 project navigator 卻沒有出現該檔案！</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/924/1*SW5SVtIlcOJEmZGQD1AOGA.png" /></figure><p>我以為這是對免費仔的懲罰，但研究後發現不是這麼一回事，過程如下：</p><h3>問題發生步驟</h3><ol><li>Cursor -&gt; File -&gt; Open Folder</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GBIuklNmezTJUZbt6sy_og.png" /></figure><p>2. 選擇專案資料夾 -&gt; 打開</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yHaA6bQwWFPqeU54cADXuw.png" /></figure><p>3. 在 AI Agent 下 promp，請 AI 幫我新增一個檔案</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-R6wAQ6quFj_1zv1dAdLkg.png" /></figure><p>4. 接著到 Finder 資料夾查看，Cursor 確實幫我新增了 Hello.md 的檔案，然而此時打開 Xcode 看，卻沒有檔案！</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Nq_IvQOkC9nXS5Bg3jt1DQ.png" /><figcaption>左到右：Cursor, Finder, Xcode</figcaption></figure><h3>解決</h3><p>原因是因為，我的 Xcode 專案使用的資料夾是 Group，Cursor 在我的 Finder 新增檔案，是不會同步到 Xcode 的，要將專案的資料夾改成 Folder。</p><ol><li>將資料夾改成 Folder</li></ol><p>資料夾右鍵 -&gt; Convert to Folder</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/1*8EKEn6b96I9HLOe6O0VLOw.png" /></figure><p>2. 重新叫 AI 生成檔案</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I80FU2vyZyJcceK6dsvU-Q.png" /><figcaption>左到右：Cursor, Finder, Xcode</figcaption></figure><p>Cursor 新增的檔案與 Xcode 同步了!</p><p>👉 想知道 Folder 與 Groups 差別的捧油，可以參考我寫的這篇文章：</p><p><a href="https://koloa1989.medium.com/36-folder-vs-groups-6749d71eed68"># 35 Folder vs Groups</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c120259ce0bc" width="1" height="1" alt=""><hr><p><a href="https://medium.com/peter-pan-swift-ios-class/36-%E8%A7%A3%E6%B1%BA-cursor-%E8%88%87-xcode-%E6%AA%94%E6%A1%88%E7%84%A1%E6%B3%95%E5%90%8C%E6%AD%A5-c120259ce0bc">#36 解決 Cursor 與 Xcode 檔案無法同步</a> was originally published in <a href="https://medium.com/peter-pan-swift-ios-class">彼得潘的 Swift iOS / Flutter App 開發教室</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[# 35 Folder vs Groups]]></title>
            <link>https://medium.com/peter-pan-swift-ios-class/36-folder-vs-groups-6749d71eed68?source=rss-29f0f755c933------2</link>
            <guid isPermaLink="false">https://medium.com/p/6749d71eed68</guid>
            <dc:creator><![CDATA[Jeff Lin]]></dc:creator>
            <pubDate>Sat, 05 Jul 2025 11:21:41 GMT</pubDate>
            <atom:updated>2025-07-08T06:17:06.023Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M-JR2OfOOqFX8547P8kM-Q.png" /><figcaption>Folder vs Groups</figcaption></figure><p>前言：前一陣子請 Cursor 幫我寫程式時，Cursor 幫我新增檔案，卻沒有同步到 Xcode，後來深究發現是資料夾型態的關係，因此以下紀錄研究心得。</p><h3>目錄：</h3><pre><a href="#78ab">基本概念介紹</a><br><a href="#31b4">兩者的主要差異</a><br>- <a href="#e950">同步機制</a><br>- <a href="#20a3">資料夾的存取</a><br>- <a href="#a8fc">Git 版本控制影響</a><br><a href="#fdec">結語</a><br><a href="#e048">Reference</a></pre><h3>基本概念介紹：</h3><h4>Folder:</h4><blockquote>A folder is a file-system directory that you reference from your project. Xcode includes the contents of the folder in your project.</blockquote><ul><li>Folder 是檔案系統中的實際目錄</li><li>在 Xcode 建立 Folder 後，磁碟上會建立實際檔案目錄</li><li>Xcode 會直接參考這個目錄的內容，在 project navigator 上產生對應的藍色資料夾</li><li>Xcode 會持續同步磁碟上的專案目錄內容</li></ul><h4>Group:</h4><blockquote>A group is a collection of resources in your project. By default, Xcode maps each group to a folder in your project directory, but you can also create groups without an underlying file-system folder. You might use groups without folders if you want to manage files in your project without changing the underlying organization of the files on disk.</blockquote><ul><li>Group 是專案中資源的集合</li><li>預設情況下，在 Xcode 建立 Group 資料夾，Xcode 會把資料夾 map 成 Folder 形式，並映射到專案目錄中的資料夾，因此也可以從 Finder 找到<strong>對應的資料夾</strong></li><li>也可以建立不含實際資料夾的 Group（純標籤功能）</li></ul><h3>兩者的主要差異</h3><h4>同步機制</h4><blockquote>Folder 的特性：</blockquote><ol><li><strong>在 Xcode 中的操作會同步到實際檔案系(Finder 裡)</strong></li></ol><p>在 Xcode 裡對資料夾內的檔案做<strong>新增刪除移動</strong>，都會同步到 project 的檔案系統</p><p><strong>2. 在 Finder 中的操作會同步到 Xcode</strong></p><p>因為 Xcode 會自動與該磁碟上的資料夾同步，<strong>因此在 Finder 做刪除新增，都會同步到 Xcode 的 Project Navigator 上。</strong></p><p><strong>舉個例子：</strong></p><p>進入 Finder 裡的 ForderDemo 資料夾 → 新增一張圖片</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/237/1*YunGqMZlofbOXdjRl33QsA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/198/1*W63H8gSl1Fn-gpusG02YPQ.png" /><figcaption>Finder 新增檔案前</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/221/1*G4O68pv_qOW37lCa59Xxow.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/187/1*DFTTOJft3bpjtpaxnUEKdw.png" /><figcaption>Finder 新增檔案後</figcaption></figure><p>可以發現從 Finder 新增照片後，Xcode 同步並且也出現該張照片。</p><blockquote><strong><em>Group 的特性：</em></strong></blockquote><ol><li><strong>預設會在 Finder 建立實際資料夾</strong></li></ol><p>預設情況下，在 Project navigator 顯示的資料夾結構會與 disc 上相同。如果在 Project navigator 裡對這個檔案操作（新增刪除），都會同步到 disc 上的檔案系統。</p><p><strong>舉個例子：</strong></p><p>在 Group 資料夾點右鍵 → New Group → 講檔案拖曳該資料夾</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/238/1*kOa0fs5jkL0a9Xh34AELNQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/204/1*N7sFRy1QNYdXUqfi-7Yryg.png" /><figcaption>左：Project Navigator 右：Finder</figcaption></figure><p>在 Xcode 上新增檔案後，同步到 disc 上的資料夾。</p><p>2. <strong>可選擇建立「without folder」的純標籤形式</strong></p><p>但如果在 Project navigator 建立資料夾時，選擇 <strong>without folder</strong>， Project navigator 上依然會出現該建出來的 Group 資料夾，但是 disc 上卻<strong>不會有對應實際資料夾</strong>。</p><p><strong>舉個例子：</strong></p><p>在 Group 資料夾點右鍵 → 按住 Option → New Group without folder → 將檔案拖曳至 Project navigator 裡的 Group 資料夾。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/239/1*o8cyxmIO_wPiJVhO5OW64Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/170/1*pqedlKLg4PDXLN9fZt7lCw.png" /><figcaption>左：Project Navigator 右：Finder</figcaption></figure><p><strong>3. Reference File</strong></p><p>Group 提供一個功能，能夠 <strong>Reference</strong> 外部的檔案，<strong>步驟如下</strong>：</p><p>拖曳檔案至 Project Navigator → 將檔案放至 Group2 資料夾內 → 選擇 Reference files in place、 Target 勾選打開</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/287/1*2XMH037IMks3HC00PqTgtg.png" /></figure><p>如此一來，這個檔案會顯示在 Project Navigator 上，並且有一個小箭頭出現，而 Xcode 不會把檔案加到 Group 資料夾裡，而是直接 Reference 到專案外部的位置。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/235/1*sLRkUtlcAdAUHmiA4aRDHA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/256/1*_azheqmrXLKoHjjBYu7ZVQ.png" /><figcaption>左：Project Navigator 右：檔案位置顯示在桌面</figcaption></figure><p>接著在 Xcode 裡將該檔案任意地在不同 Group 內資料夾移動，都不會影響該檔案原本在 disc 上的位置。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/234/1*7ICsyqM4K-4OKRfuAX1A_w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/253/1*7MP0g8VilbRpN4tQjgz4iQ.png" /><figcaption>左：Project Navigator 右：檔案位置還是顯示在桌面</figcaption></figure><h4>資料夾的存取</h4><blockquote>Folder 的特性</blockquote><ol><li><strong>可以直接透過 Bundle 存取資料夾內容</strong></li></ol><p>如果要讀去專案裡某個資料夾的內容，一定得將資料放在 Folder 類型的資料夾裡。以下為範例：</p><p>Group 的資料夾放了 medium 的圖片，Folder 的資料夾放了 github 的圖片。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/284/1*nGrRwoeGJ_5ekModqgXnVw.png" /></figure><p>接著用以下程式碼去找到 Bundle 裡的資料夾，並讀取資料夾裡的內容後，把東西呈現到 imageView 上。</p><pre>class ViewController: UIViewController {<br><br>    enum FolderType: String {<br>        case Group = &quot;Group&quot;<br>        case Folder = &quot;Folder&quot;<br>    }<br>    <br>    @IBOutlet var imageView: UIImageView!<br>    <br>    override func viewDidLoad() {<br>        super.viewDidLoad()<br>        fetchDirContent()<br>    }<br><br>    @IBAction func clickGroupBtn(_ sender: Any) {<br>        getImage(type: .Group)<br>    }<br>    <br>    <br>    @IBAction func clickFolderBtn(_ sender: Any) {<br>        getImage(type: .Folder)<br>    }<br>    <br>    func fetchDirContent() {<br>        if let bundleURL = Bundle.main.resourceURL {<br>            do {<br>                let items = try FileManager.default.contentsOfDirectory(atPath: bundleURL.path)<br>                print(&quot;Bundle 資源內容：\(items)&quot;)<br>                items.forEach { print($0) }<br>            } catch {<br>                print(&quot;無法列出 bundle：\(error)&quot;)<br>            }<br>        }<br>    }<br>    <br>    func getImage(type: FolderType) {<br>        if let folderURL = Bundle.main.resourceURL?.appendingPathComponent(type.rawValue) {<br>            do {<br>                let fileURLs = try FileManager.default.contentsOfDirectory(at: folderURL, includingPropertiesForKeys: nil)<br>                if let url = fileURLs.first {<br>                    print(&quot;找到檔案：\(url.lastPathComponent)&quot;)<br>                    let urlStr = url.path<br>                    let image = UIImage(contentsOfFile: urlStr)<br>                    imageView.image = image<br>                }<br>            } catch {<br>                print(&quot;讀取資料夾失敗：\(error)&quot;)<br>                imageView.image = nil<br>            }<br>        } else {<br>            print(&quot;找不到資料夾&quot;)<br>            imageView.image = nil<br>        }<br>    }<br>}</pre><p>測試結果：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*BFYxAzO_Sih3MxFT2AJBkw.png" /><figcaption>點擊 Folder 後，github 的圖片如期呈現在 imageView 上。</figcaption></figure><blockquote>Group 的存取</blockquote><ol><li>編譯時資料夾結構會被移除</li></ol><p>沿用 Folder 範例 code，點擊 <strong>Group 按鈕</strong>後，出現的 Log，顯示無法找到該 Group 這個資源。</p><pre>讀取資料夾失敗：Error Domain=NSCocoaErrorDomain Code=260 <br>&quot;The file &quot;Group&quot; couldn&#39;t be opened because there is no such file.&quot;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*1F9IMvbc6YTc8d-vEhS6oQ.png" /><figcaption>點擊 Group 後，出現以下 Log：顯示系統無法找到資料夾</figcaption></figure><p>我想原因可能是因為，Group 代表的意義都是<strong>群組</strong>，<strong>只是集合資料的用途</strong>，因此 Group 類型的資料夾對 Xcode 來說<strong>不是真實存在的資料夾</strong>。在 compile 時，Group 的資料夾都會被移除，因此編譯後的 Bundle 內會找不到 Group 的資料夾。</p><p>2. 存在 Group 內的檔案會向上層移動</p><p>在專案裡建立三個 Group 資料夾，裡面各放三張圖片：test、github、medium</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/668/1*mnFXlXXRmWUFeGO8jIum4A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/394/1*DxRdfd-o1FQxwiohW9lILw.png" /></figure><p>在這裡，我們可以進一步在 ViewDidLoad 執行 <strong>fetchDirContent()</strong></p><pre>// 檢查跟目錄有哪些資源<br>func fetchDirContent() {<br>    if let bundleURL = Bundle.main.resourceURL {<br>        do {<br>            let items = try FileManager.default.contentsOfDirectory(atPath: bundleURL.path)<br>            print(&quot;Bundle 資源內容：\(items)&quot;)<br>            items.forEach { print($0) }<br>        } catch {<br>            print(&quot;無法列出 bundle：\(error)&quot;)<br>        }<br>    }<br>}</pre><p>觀察 root 有哪些檔案與資料夾，結果如下：</p><pre>Bundle 資源內容：[&quot;_CodeSignature&quot;, &quot;FolderDemo.debug.dylib&quot;, &quot;github.png&quot;, &quot;Base.lproj&quot;, &quot;__preview.dylib&quot;, &quot;medium.png&quot;, &quot;test.png&quot;, &quot;FolderDemo&quot;, &quot;Info.plist&quot;, &quot;PkgInfo&quot;]</pre><p>Group 的三個資料夾在 compile 時都被移除，所以 root 裡<strong>找不到</strong> GroupDemo1、GroupDemo2、GroupDemo3。</p><p>而那三張圖片因為資料夾被移除，向上移動一層，就到了根目錄，因此被檢查出來<strong> “github.png”、 “medium.png”、”test.png”</strong>。</p><p>反觀，因為 FolderDemo 是<strong>真實對應的資料夾</strong>，因此在編譯時不會被移除，因此一樣存在 root，而被這段程式碼找出來。</p><h4>Git 版本控制影響</h4><blockquote>Folder 的特性：<strong>對 project.pbxproj 影響較小：</strong></blockquote><p>這是沒有加入檔案前的樣子</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/364/1*oxp827tVFeHSMxZf9IB9fA.png" /></figure><p>接著加入一張圖片到 FolderDemo，可以發現，Project 沒有受到 git 追蹤，只有加入的檔案受到追蹤。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/584/1*Q-BqF_Vjj6i9EAcSjUNTLg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/670/1*U7YUujnem7ZuGbh5Bhc8tw.png" /><figcaption>左：加入時的選項 右：加入後的結果</figcaption></figure><p>Folder 類型對應的是實體存在於檔案系統中的資料夾，Xcode 會自動與該資料夾同步，<strong>在資料夾內對檔案做修改時，只會影響檔案本身，不會影響 project.pbxproj。</strong></p><blockquote>Group 的特性：會影響 project.pbxproj</blockquote><p>如果加入一張圖片到 GroupDemo，可以發現，除了<strong>加入的檔案</strong>以外，連 <strong>project.pbxproj</strong> 也受到 git 追蹤。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/672/1*CKZIOgushnoKXqIOyCMPZA.png" /></figure><p>原因可能是因為，Group 類型的資料夾在編譯時會被移除，所以 <strong>Groups 的檔案列表都會紀錄在 project.pbxproj</strong>，讓 Xcode 去追蹤資料來源。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4vT_J4NnWB7PczzaAkgZyQ.png" /></figure><p>因此可以想像，當 project.pbxproj 在不同 branch 同時受到改動，最後 merge 時產生衝突的話，可能會跟 storyboard 產生的衝突一樣難解。</p><h3>More than that</h3><p>需要注意的是，當<strong>資料夾型態為 Group</strong> 時，Xcode 不會從 Finder 中讀取實際的檔案與資料夾結構，因此<strong>如果在 Finder 上新增檔案，不會反映在 Xcode 上。</strong></p><p><strong>舉個例子：</strong>進入 Finder 裡的 Group 資料夾 → 新增一個文字檔</p><p><strong>【加入 Hello World 檔案前】</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/239/1*o8cyxmIO_wPiJVhO5OW64Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/170/1*pqedlKLg4PDXLN9fZt7lCw.png" /><figcaption>左：Project Navigator 右： Finder</figcaption></figure><p><strong>【</strong>加入 Hello World 檔案後<strong>】</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/239/1*o8cyxmIO_wPiJVhO5OW64Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/186/1*Ncd8YQUB6DJI5S7emU4K3w.png" /><figcaption>左：Project Navigator 右： Finder</figcaption></figure><p><strong>Finder 上所做的任何新增動作不會反應在 Xcode 上。</strong>但如果<strong>刪掉</strong>，Xcode 是真的會有反應，原因可能是因為，Xcode 會追蹤 project.pbxproj 中記錄的檔案列表，檔案列表中的檔案不存在，立即標示錯誤。</p><h3>結語：</h3><p>蠻多資料都提到，多人開發的話，會以 Folder 類型的資料夾去管理檔案，可以減少 project.pbxproj 發生 conflict 的機率。然而有些文章也提到使用 Folder 可能會對使用 cocoapods 造成影響，另外也有文章提到，要部署 CI/CD，使用有實體目錄的資料夾會比較好。</p><p>以上就是我看官方文件以及其他人寫的文章後的心得，歡迎討論，謝謝🙇‍♂️</p><h3>Reference：</h3><p>官方文件：</p><p><a href="https://developer.apple.com/documentation/xcode/managing-files-and-folders-in-your-xcode-project#Organize-project-files-in-the-navigator">Managing files and folders in your Xcode project | Apple Developer Documentation</a></p><p>與 CI/CD 有關</p><p><a href="https://troz.net/post/2024/xcode_folders_groups/">Xcode Folders &amp; Groups - TrozWare</a></p><p>其他閱讀資料</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Fz94vpBgj0HY%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3Dz94vpBgj0HY&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2Fz94vpBgj0HY%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/01d22d37cbbc4c9258eea203c03f8001/href">https://medium.com/media/01d22d37cbbc4c9258eea203c03f8001/href</a></iframe><p><a href="https://troz.net/post/2024/xcode_folders_groups/">Xcode Folders &amp; Groups - TrozWare</a></p><p><a href="https://stackoverflow.com/questions/47808746/create-groups-vs-create-folder-reference-in-xcode">https://stackoverflow.com/questions/47808746/create-groups-vs-create-folder-reference-in-xcode</a></p><p>​</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6749d71eed68" width="1" height="1" alt=""><hr><p><a href="https://medium.com/peter-pan-swift-ios-class/36-folder-vs-groups-6749d71eed68"># 35 Folder vs Groups</a> was originally published in <a href="https://medium.com/peter-pan-swift-ios-class">彼得潘的 Swift iOS / Flutter App 開發教室</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[# 34 Warning once only: UITableView was told to layout its visible cells and other contents without…]]></title>
            <link>https://koloa1989.medium.com/warning-once-only-uitableview-was-told-to-layout-its-visible-cells-and-other-contents-without-bb2ace1957ce?source=rss-29f0f755c933------2</link>
            <guid isPermaLink="false">https://medium.com/p/bb2ace1957ce</guid>
            <dc:creator><![CDATA[Jeff Lin]]></dc:creator>
            <pubDate>Tue, 28 Jan 2025 03:07:03 GMT</pubDate>
            <atom:updated>2025-01-28T03:10:28.126Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong># 34 Warning once only: UITableView was told to layout its visible cells and other contents without being in the view hierarchy</strong></h3><h4>更新 Layout 前記得算時辰</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Bv4yTvnZdEBlZTiU89cepg.png" /></figure><h4>前言：</h4><p>使用 tableView 時，因為在不正確的時機更新 layout，所以產生錯誤</p><h4>發生情境：</h4><p>程式碼使用 MVVM 架構，因此有使用 binding 來更新 UI。</p><p>首先，在 viewDidLoad 時執行 setupFriendTableView，將 tableView 加進 view：</p><pre>override func viewDidLoad() {<br>     setupFriendTableView()<br>    // Do any additional setup after loading the view.<br>}<br><br>private func setupFriendTableView() {<br>    view.addSubview(friendTableView)<br>    friendTableView.translatesAutoresizingMaskIntoConstraints = false<br>    friendTableViewTopConstraint = friendTableView.topAnchor.constraint(equalTo: view.topAnchor, constant: 1)<br>    NSLayoutConstraint.activate([<br>        friendTableViewTopConstraint!,<br>        friendTableView.leadingAnchor.constraint(equalTo: view.leadingAnchor),<br>        friendTableView.trailingAnchor.constraint(equalTo: view.trailingAnchor),<br>        friendTableView.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -1)<br>    ])<br>}</pre><p>接著，在 viewDidLoad 設定 binding，如下：</p><pre>override func viewDidLoad() {<br>    .....<br>    setupBinding()<br>    // Do any additional setup after loading the view.<br>}<br><br>private func setupBinding() {<br>    profileViewModel.isSearch.bind { [weak self] isSearch in<br>        guard let isSearch else { return }<br>        self?.updateSearchingState(isSearch: isSearch)<br>    }<br>}<br><br>private func updateSearchingState(isSearch: Bool) {<br>    cancelSearchBtn.isHidden = !isSearch<br>    addFriendBtn.isHidden = isSearch<br>    let layout = isSearch ? friendTableView.topAnchor.constraint(equalTo: self.view.topAnchor) : friendTableView.topAnchor.constraint(equalTo: topView.safeAreaLayoutGuide.bottomAnchor, constant: 1)<br>    updateFriendTableViewTopConstraint(layout: layout)<br>}<br><br>private func updateFriendTableViewTopConstraint(layout: NSLayoutConstraint) {        <br>    UIView.animate(withDuration: 0.1) { [weak self] in<br>        self?.friendTableViewTopConstraint?.isActive = false<br>        self?.friendTableViewTopConstraint = layout<br>        self?.friendTableViewTopConstraint?.isActive = true<br>        self?.view.layoutIfNeeded()<br>    }<br>}<br></pre><p>一旦 binding 後，馬上就會觸發 observer 執行功能。 因為 isSearch 有給初始值 false，guard let 檢查會通過，因此執行 updateSearchingState，最後會再執行<strong> layoutIfNeeded()</strong>。</p><p>此時將產生錯誤：</p><pre>Warning once only: UITableView was told to layout its visible cells and other contents without being in the view hierarchy (the table view or one of its superviews has not been added to a window). <br>This may cause bugs by forcing views inside the table view to load and perform layout without accurate information <br>(e.g. table view bounds, trait collection, layout margins, safe area insets, etc), <br>and will also cause unnecessary performance overhead due to extra layout passes. <br>Make a symbolic breakpoint at UITableViewAlertForLayoutOutsideViewHierarchy to catch this in the debugger and see what caused this to occur, so you can avoid this action altogether if possible, or defer it until the table view has been added to a window. Table view: &lt;UITableView: 0x10384b600; frame = (0 69.6667; 393 781.333); clipsToBounds = YES; tag = 1; gestureRecognizers = &lt;NSArray: 0x600000ca2dc0&gt;; animations = { bounds.size=&lt;CABasicAnimation: 0x6000002ce4a0&gt;; position=&lt;CABasicAnimation: 0x6000002cf3a0&gt;; }; backgroundColor = &lt;UIDynamicCatalogColor: 0x600002139630; name = backgroundColor2&gt;; layer = &lt;CALayer: 0x6000002c2600&gt;; contentOffset: {0, 0}; contentSize: {393, 369}; adjustedContentInset: {0, 0, 0, 0}; dataSource: &lt;Cathay_iOS.ProfileViewModel: 0x600000231dc0&gt;&gt;</pre><p>大意是在說，UITableView 被告知要對它的 content 進行 layout 時，UITableView 本身或它的 superView 還沒有被加進 window 裡。</p><p>這樣子的結果可能會導致不預期的 UI 結果。</p><h4>解決方法：</h4><ol><li>找出造成錯誤的程式碼：<br>當這個 Error 出現時，debug console 也是建議先用<strong>中斷點</strong>找出是哪行程式碼造成 layout 出錯，在我這個例子，是因為 <strong>layoutIfNeeded()</strong> 的關係。</li><li>近一步除錯：<br>debug console 説是因為我的 tableView 或它的 superView 沒被加到 window，所以表示我在 viewDidLoad 執行 <strong>layoutIfNeeded() </strong>是錯誤的時機點<br>上述可以用以下程式碼驗證：</li></ol><pre>extension ProfileViewController {<br>    func checkViewIsInViewHierarchy(lifeCycle: String) {<br>        print(&quot;\(lifeCycle) | view is in view hierarchy: \(self.view.isInViewHierarchy)&quot;)<br>    }<br>}<br><br>extension UIView {<br>    var isInViewHierarchy: Bool {<br>        return self.window != nil<br>    }<br>}</pre><p>在每個 life cycle 使用 <strong>checkViewIsInViewHierarchy</strong> 來確認 self.view 是否有在 window 裡，結果如下：</p><pre>viewDidLoad | view is in view hierarchy: false<br>viewWillAppear | view is in view hierarchy: false<br>viewDidLayoutSubviews | view is in view hierarchy: true<br>viewDidLayoutSubviews | view is in view hierarchy: true<br>viewDidAppear | view is in view hierarchy: true</pre><p>由結果可知，viewDidLoad 時 self.view 還未被加進 window，因此在此時呼叫 <strong>layoutIfNeeded() 會造成錯誤。</strong></p><p>3. 解決辦法：<br>根據 print 出來的結果，要呼叫 <strong>layoutIfNeeded() </strong>的話最好的時機點是在<strong> viewDidLayoutSubviews</strong> 以後，因為此時的 self.view 已經被加進 window 裡。</p><p>然而，我沒有想要把 binding 挪到 <strong>viewDidLayoutSubviews，因為</strong>binding<strong> 只需要做一次</strong>，因此我加了以下判斷，讓 tableView 在沒有被加進 window 裡前，不要執行 <strong>layoutIfNeeded()</strong>，如此就可以解決錯誤：</p><pre><br>override func viewDidLoad() {<br>     setupFriendTableView()<br>    // Do any additional setup after loading the view.<br>}<br><br>private func updateFriendTableViewTopConstraint(layout: NSLayoutConstraint) {<br>    // 若 friendTableView 沒在 window 裡，就不做動畫<br>    guard friendTableView.window != nil else { return }<br>    <br>    UIView.animate(withDuration: 0.1) { [weak self] in<br>        self?.friendTableViewTopConstraint?.isActive = false<br>        self?.friendTableViewTopConstraint = layout<br>        self?.friendTableViewTopConstraint?.isActive = true<br>        self?.view.layoutIfNeeded()<br>    }<br>}<br></pre><p><strong>Reference：</strong></p><p><a href="https://stackoverflow.com/questions/64568183/warning-once-only-uitableview-was-told-to-layout-its-visible-cells-and-other-co">Warning once only: UITableView was told to layout its visible cells and other contents without being in the view hierarchy?</a></p><p><a href="https://juejin.cn/post/6844904111536603143">https://juejin.cn/post/6844904111536603143</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bb2ace1957ce" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[2024 iPlayground 工作人員初體驗]]></title>
            <link>https://koloa1989.medium.com/2024-iplayground-%E5%B7%A5%E4%BD%9C%E4%BA%BA%E5%93%A1%E5%88%9D%E9%AB%94%E9%A9%97-8e8bd1a0a5c2?source=rss-29f0f755c933------2</link>
            <guid isPermaLink="false">https://medium.com/p/8e8bd1a0a5c2</guid>
            <dc:creator><![CDATA[Jeff Lin]]></dc:creator>
            <pubDate>Thu, 07 Nov 2024 16:38:29 GMT</pubDate>
            <atom:updated>2024-11-08T12:23:57.452Z</atom:updated>
            <content:encoded><![CDATA[<h3>報名初衷</h3><p>回想當初報名當工作人員，也是朋友推薦的，結果最後她沒被選到，反而是我幸運中獎 🎉ＸＤ</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/946/1*Q7GyYcbYDtfsdu3ZvKzbRg.png" /></figure><h3>活動前的籌備</h3><p>身為一個半 E 半 I 的人，要跟一群很厲害、半個不認識的人交流，也是十分緊張。幸好最後有個在彼得潘課程認識的朋友也有報名( Da Wei 就是你 )，我才稍稍鬆一口氣😌。</p><p>每週六晚上會固定開會約一小時，有時候總召 Hokila 會突然 cue 人，每次被 cue 到都會抖一下，讓我十分懷念以前被教授點到的日子😊</p><p>這次的活動裡，我是負責宣傳的工作，我跟我女友說這件事時，她說道：「平常不發限動的人竟然要當小編！」。我想想，好像是這麼一回事ＸＤ我回想起會當小編的原因，好像只是其他的工作沒搶到，只好選宣傳🤣。</p><p>然而在宣傳的過程卻學習到很多。像是研究其他研討會發文的形式與內容、與夥伴 Harry 討論發文策略、看以前 13 當宣傳時的發文內容、如何讓文章質量上升（減少廢話），以及第一次剪開場影片，所有的種種都是我沒有做過的事情，很新鮮，也很有趣。</p><p>這過程很感謝 Hokila 給我一些發文上的建議以及努力的方向，也很感謝 Harry 的 cover，讓票能順利都賣光光（不然就要特殊召喚親友團了😆）。</p><h3>活動當天</h3><p>活動的前置作業準備時，大家會先齊聚一堂，一見到其他工作人員，真的很有跟網友見面的感覺 🤣 。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-NlzA0Y52DpcqxfTgPmJeQ.jpeg" /></figure><p>過程中除了裝忙 (?)，也跟不同的工程師交流，了解不同公司的生態。很慶幸有跟 Terry, Michelle, Logan 聊天，讓我對外面的世界又多了幾分的認識 ✨。</p><p>在活動現場時，講者都還沒開講，我就已經興奮到變模糊了，因為活躍在螢幕前的傳奇人物都活生生地跑到眼前了，像是 13、Jane、僑德、涵宇、彼得潘 🤩 尤其跟 Jane 合照時好緊張 XD</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FZi5m4FlF-nxtWQOYEbVtw.png" /><figcaption>合影：打完桌球趕過來的彼得潘</figcaption></figure><p>看到會場坐滿人，心裡覺得很震撼：在這裡的每個人都是熱愛 iOS 開發的人。一個 iPlayground 社群的力量，可以凝聚這麼多喜歡相同事物的人，讓大家之間的聯繫變得更加緊密，真的是一件很厲害、也很感動的事情。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9z-yAn_gub1eTmPAfkwI_g.jpeg" /></figure><h3>後記</h3><p>這一次的活動，讓我能跟很多前輩面對面交流，真的是很難得的經驗。參與了研討會，讓我有深深的體悟：聆聽演講內容是其次（也是因為我根本記不起來🫠）。我後來覺得，更重要的，應該是與其他人的互動。聽著夥伴們分享職場上的事、 Hao 介紹 Apple 園區、Hokila 參加 WWDC 的經驗等，這些都是無價的（早知道就少聽演講多聊天了）。</p><p>很慶幸在 2024 年快結束時，踏出自己的小圈圈，看向更廣闊的世界。希望未來的自己都能這麼勇敢下去。</p><p>最後，很感謝每位辛苦付出的工作人員，因為有你們，活動才能順利落幕 ♥️ 同時也希望 iPlayground 能夠一直延續下去。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VI6Ry8odCGNwLsmFKH-lNg.jpeg" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8e8bd1a0a5c2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[#33 Closure 與 Capture]]></title>
            <link>https://koloa1989.medium.com/closure-%E8%88%87-capture-0aa461ca45d0?source=rss-29f0f755c933------2</link>
            <guid isPermaLink="false">https://medium.com/p/0aa461ca45d0</guid>
            <dc:creator><![CDATA[Jeff Lin]]></dc:creator>
            <pubDate>Sat, 07 Sep 2024 16:14:15 GMT</pubDate>
            <atom:updated>2024-09-07T16:27:48.603Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Fec6dQNeeWYwkUe48aLbBg.jpeg" /><figcaption>全部給我抓起來！</figcaption></figure><p>前言：在使用 Closure 時，若作用域裡有用到外圍的變數或常數，Closure會將其 Capture。Capture 這個行為會有怎樣的效果呢？最近都在看相關的資料，因此將其紀錄。</p><pre>目錄：<a href="#7e76"><br>什麼是 Closure？</a><br><a href="#cc6c">什麼是 Capture？</a><br><a href="#3e48">Implicit capturing</a><br><a href="#ab4d">Capture list</a><br><a href="#9d5f">取消強引用</a><br><a href="#900d">結論</a><br><a href="#b3b5">Reference</a></pre><h3>什麼是 Closure？</h3><h4>定義：</h4><p>Closure 是一個本身就具有功能的 block。屬於 primary type，表示可以被assigned、stored、pass around …等。</p><p>官方提供的原文如下：</p><pre>Closures are self-contained blocks of functionality that can be passed around and used in your code. <br>Closures in Swift are similar to closures, anonymous functions, lambdas, and blocks in other programming languages.</pre><p>Cookbook-Third-Edition 這本書的定義如下：</p><pre>Closures behave like other primary types. <br>They can be assigned, stored, passed around, and used as input and output to functions and other closures.</pre><h4>種類：</h4><p>根據 apple 官方的說明，Closure 主要有三種型態：</p><blockquote>Global functions</blockquote><p>定義在全域的 function，可以於任意地方使用。他有幾項特點：</p><ol><li>沒有 Capture 的能力</li><li>function 有名稱</li></ol><pre>// function test 定義在全域，可在任何地方使用<br>func test {<br>    print(&quot;123&quot;)<br>}<br><br>class A {<br>  func doSomething() {<br>      test()<br>  }<br>}</pre><blockquote>Nested functions</blockquote><p>function 裡面還有定義 function，定義在內部的 function 就會被視為 Closure。此種類型的 Closure 有以下特性：</p><ol><li>有 Capture 的能力</li><li>function 有名稱</li></ol><p>本例中，innerFunction 即為 Closure 。</p><pre>func createCounter() -&gt; (() -&gt; Int) {<br>    var count = 0<br>    func innerFunction() -&gt; Int {<br>        count += 1<br>        return count<br>    }<br>    return innerFunction<br>}<br><br>let counter = createCounter()<br>print(counter())  // 輸出 1<br>print(counter())  // 輸出 2</pre><blockquote>Closure expressions</blockquote><p>沒有名稱的 function。此種類型的 Closure 有以下特性：</p><ol><li>有 Capture 的能力</li><li>function 沒有名稱</li></ol><p>常數 closure 儲存的 就是一個沒有名稱的 function。</p><pre>let closure = {<br>    print(&quot;This is a anonymous function&quot;)<br>}</pre><p>所以 嚴格來說，其實不一定需要有 Capture 的功能才是 Closure，只要可以像 struct 或 class ( primary type ) 可以儲存、傳遞、賦值等，就可以被定義成 Closure。</p><p>說完 Closure 的定義以及種類後，接著說說 Capture 是什麼賴東東。</p><h3>什麼是 Capture？</h3><h4>定義 ：</h4><p>當 Closure 的作用域內使用到外部定義的常數或變數，就會有 Capture 的行為出現。</p><p>像是以下例子，count 是在閉包的作用域外定義的，所以當閉包會自動 capture 該變數的內容：</p><pre>var count = 0<br>let countClosure = {<br>    print(&quot;Count is \(count)&quot;)<br>}<br>countClosure() // 印出 Count is 0</pre><h4>為什麼需要 Capture：</h4><p>誠如定義，<strong>Closure 是個可以在任何時候使用的一種</strong>型別。由於其執行時間是<strong>不確定</strong>的，我們無法保證在 Closure 被調用時，其原先引用的常數或變數是否仍然存在於原始作用域中。因此，當定義 Closure 後，如果 Closure 使用了外部定義的常數或變數，它會執行 Capture 操作。這確保了當 Closure 被執行時，無論何時何地，它所需的所有外部資源都還存在著。</p><h4>Capture 機制：</h4><p>Capture 時，Closure 會對<strong>變數/常數</strong>建立<strong>引用。</strong>這種機制使得 Closure 不僅可以訪問這些變數/常數當前儲存的<strong>內容</strong>，還可以在其自身的作用域內<strong>修改</strong>這些變數的值（對於變數而言）。</p><p>官方提供的原文如下：</p><pre>A closure can capture constants and variables from the surrounding context in which it’s defined. <br>The closure can then refer to and modify the values of those constants and variables from within its body, even if the original scope that defined the constants and variables no longer exists.</pre><p>以下是使用 <strong>Nested Functions </strong>當範例。當 createCounter() 執行完後，變數 count 早就已經被清除。但是由於 innerFunction 持續捕獲count，因此innerFunction 被 output 出來儲存後，調用 counter，可以一直使用count。</p><p>而這個變數count是被引用狀態，因此<strong>同個 Closure 重複呼叫</strong>，<strong>會改動到同個 count</strong>。</p><pre>func createCounter() -&gt; (() -&gt; Int) {<br>    var count = 0<br>    func innerFunction() -&gt; Int {<br>        count += 1<br>        return count<br>    }<br>    return innerFunction<br>}<br><br>let counter = createCounter()<br>print(counter())  // 輸出 1<br>print(counter())  // 輸出 2</pre><h4>Closure 是 reference type：</h4><p><em>Capture 機制 </em>的段落裡使用到 Nested Functions 做範例。</p><p>那如果把 counter 存到其他變數呢？可以發現，存到另一個counter 後並執行，印出來的數字是 3，表示這是同一個 Closure，而這 Closure 持續引用同個變數的內容。</p><pre>func createCounter() -&gt; (() -&gt; Int) {<br>    var count = 0<br>    func innerFunction() -&gt; Int {<br>        count += 1<br>        return count<br>    }<br>    return innerFunction<br>}<br><br>let counter = createCounter()<br>let 另一個counter = counter<br>print(counter())        // 輸出 1<br>print(counter())        // 輸出 2<br>print(另一個counter())   // 輸出 3<br></pre><p>那理所當然，如果今天輸出另一個 Closure，則引用的變數不同，印出來的值自然不同。</p><pre>let counter = createCounter()<br>let counter2號 = createCounter()<br>print(counter())        // 輸出 1<br>print(counter())        // 輸出 2<br>print(counter2號())     // 輸出 1</pre><p>說完 Capture 的定義與機制後，接著要說明 capture 值型別與 capture 引用型別的差異。</p><h3><strong>Implicit capturing：</strong></h3><p>閉包會<strong>自動捕獲</strong>在外部作用域中定義的變數和常數，這個過程稱為<strong>Implicit capturing</strong>。這種捕獲會產生對這些變數或常數的引用。</p><p>變數儲存的內容又可分為 value type 與 reference type，以下紀錄兩者差異。</p><h4>Capture value type：</h4><p>count 是 Int 型別，屬於值型別 (value type)。當閉包 countClosure 捕獲 count 時，它捕獲的是 count 的變數本身，而不是當下的值。因此，即使在捕獲之後更改了 count 的值，閉包中使用的仍然是最新的變數值，這就是為什麼執行閉包時會打印出更新後的值。</p><pre>var count = 0<br><br>let countClosure = {<br>    print(&quot;Count is \(count)&quot;)<br>}<br><br>count = 10<br><br>countClosure()  // Output: Count is 10</pre><p>到這裡，都跟前幾個段落的示範一樣。那如果今天 Capture 的是 reference type 呢？</p><h4>Capture reference type：</h4><p>結果與捕獲 value type 的內容相同。對 myPencil 變數的引用，而非其值。當 myPencil 被設為 nil 時，閉包中引用的變數是 nil 值。因此，執行閉包時會印出 <strong>Pencil color is nil</strong> 的結果。</p><pre>class ColorPencil {<br>    var color: String<br>    init(color: String) {<br>        self.color = color<br>    }<br>    <br>    deinit {<br>        print(&quot;color pencil is broken&quot;)<br>    }<br>}<br><br>var myPencil: ColorPencil? = ColorPencil(color: &quot;Red&quot;)<br>let closure = {<br>    print(&quot;Pencil color is \(myPencil?.color)&quot;)<br>}<br><br>myPencil?.color = &quot;Blue&quot;<br>myPencil = nil   // color pencil is broken<br>closure()        // 印出 Pencil color is nil</pre><blockquote>閉包捕獲的是變數本身（即變數的引用），而非變數指向的實例（不會對實例造成新的強引用），也不是變數當前的值</blockquote><blockquote>這種行為允許閉包訪問到變數最新的值，即使這個值在閉包定義後發生了改變。</blockquote><p>剛剛的範例中，ColorPencil 的 ARC 為 1，因為 只有myPencil 這個變數建立強引用。若我再建立第二個強引用，則結果會如何呢？</p><p>在以下例子中，我宣告 myPencil2，並把 myPencil 存到裡面，建立對 ColorPencil 實例的第二個強引用，所以此時的 ARC 是 2。</p><p>最後將 myPencil 設成 nil，看 Console 印出來的結果，這次沒有看到 deinit 的訊息，原因是因為 myPencil2 還建立著對實例的強引用，所以 ARC 還沒歸 0 ，因此不會印出 deinit 的訊息。所以接著印出 myPencil2 的顏色後，可以看到結果是最後更改的藍色。</p><p>但仍然印出 <strong>Pencil color is nil</strong>，這再次證明，<strong>閉包捕獲的是變數本身（即變數的引用），而非變數指向的實例</strong>。</p><p>所以即使實例並未消失，但是<strong>引用的變數</strong>已經變成 nil，Closure 執行的結果就是 nil 。</p><pre>class ColorPencil {<br>    var color: String<br>    init(color: String) {<br>        self.color = color<br>    }<br>    <br>    deinit {<br>        print(&quot;color pencil is broken&quot;)<br>    }<br>}<br><br>var myPencil: ColorPencil? = ColorPencil(color: &quot;Red&quot;)<br>var myPencil2 = myPencil  // 增加實例的 ARC<br>let closure = {<br>    print(&quot;Pencil color is \(myPencil?.color)&quot;)<br>}<br><br><br>myPencil?.color = &quot;Blue&quot;<br>myPencil = nil<br>closure()      // 印出 Pencil color is nil<br><br>// ARC 還沒歸 0<br>// 印出 myPencil2 color:Optional(&quot;Blue&quot;)<br>print(&quot;myPencil2 color:\(myPencil2?.color)&quot;)  </pre><h3><strong>Capture list：</strong></h3><p>Capture list 是一種允許我們明確指定如何捕獲外部變數的機制，用於當我們需要控制捕獲行為時（即非隱式捕獲 Implicit capturing）。</p><blockquote>簡單來說，就是我們手控捕捉！</blockquote><p>使用方式:</p><pre>{ [捕獲列表] (參數) in<br>    ......<br>}</pre><p>以下一樣會觀察捕捉值型別與引用型別的值，會不會有差異。</p><h4>Capture value type：</h4><p>可以觀察到，countClosure2 的閉包會把捕捉的變數 Copy 一份存到自己定義的變數，這裡是存到 number 。若只是單純用 [count] in，這會創建一個同名但獨立的 count 常數在閉包內。。</p><blockquote>總而言之，使用 capture list 捕捉 value type，原本的值與 copy 來的值已經完全沒關係了。</blockquote><p>因此後來的 count 改成 10，對於 countClosure2 而言完全沒影響，<strong>因為他用的是自己的變數，不再是引用原先的變數</strong>。</p><pre>var count = 0<br>let countClosure = {<br>    print(&quot;Count is \(count)&quot;)<br>}<br><br>let countClosure2 = { [number = count] in<br>    print(&quot;Count is \(number)&quot;)<br>}<br><br>count = 10<br>countClosure()  // Output: Count is 10<br>countClosure2()  // Output: Count is 0</pre><p>而要注意的是，capture list 裡面宣告的變數是默認用 let 關鍵字，所以捕捉的內容是<strong>不能</strong>再做更改的！！</p><pre>var let countClosure2 = { [number = count] in<br>    // number = 2  // 報錯！！Cannot assign to value: &#39;number&#39; is an immutable capture<br>    print(&quot;Count is \(number)&quot;)<br>}</pre><h4>Capture reference type：</h4><p>closure2 的閉包會把捕捉的變數 Copy 一份存到閉包內部定義的變數內，但是因為複製的對象是<strong>引用型別</strong>，所以這裡複製的是<strong>實例的引用</strong>。因此呢～</p><blockquote>更改這個引用會影響原來的實例。</blockquote><p>closure 是隱式捕獲（Implicit capturing），所以它捕獲的是對變數 myPencil 的引用。</p><p>當我們第一次執行 closure() 時，會印出藍色，因為我們在捕獲後將 myPencil 的顏色設為藍色。</p><p>接著，執行 closure2() 時，由於 closure2 捕獲的是 myPencil 的引用，它會將顏色更改為黃色，因此印出黃色。</p><p>當再次執行 closure() 時，由於 closure2 已經更改了 myPencil 的顏色，所以 closure 引用的變數 myPencil 的內容，印出的顏色也會是黃色。</p><pre>class ColorPencil {<br>    var color: String<br>    init(color: String) {<br>        self.color = color<br>    }<br>    <br>    deinit {<br>        print(&quot;color pencil is broken&quot;)<br>    }<br>}<br><br>var myPencil: ColorPencil? = ColorPencil(color: &quot;Red&quot;)<br><br>let closure = {<br>    print(&quot;Pencil color is \(myPencil?.color)&quot;)<br>}<br><br>let closure2 = { [closurePencil = myPencil] in<br>    closurePencil?.color = &quot;Yellow&quot;<br>    print(&quot;Pencil color is \(closurePencil?.color)&quot;)<br>}<br><br>myPencil?.color = &quot;Blue&quot;<br>closure()       // Output: Pencil color is Optional(&quot;Blue&quot;)<br>closure2()      // Output: Pencil color is Optional(&quot;Yellow&quot;)<br>closure()      // Output: Pencil color is Optional(&quot;Yellow&quot;)</pre><h4>取消強引用：</h4><p>當使用 capture list 捕獲<strong>引用型別</strong>的變數時，閉包會產生一個新的變數，該變數保存<strong>原變數指向實例的位置</strong>，這會對實例產生新的<strong>強引用</strong>，從而增加 ARC 計數。</p><p>那如果不想要增加強引用，則可以使用 [weak 變數]，這樣捕獲的變數會是一個弱引用，不會影響實例的 ARC 計數。</p><p>以下例子，先定義一個 Pencil 的class</p><pre>class Pencil {<br>    init() {<br>        print(&quot;Pencil comes up&quot;)<br>    }<br>    deinit {<br>        print(&quot;Break the pencil&quot;)<br>    }<br>    func write() {<br>        print(&quot;Write Hello&quot;)<br>    }<br>}</pre><p>接著，我們宣告並執行一個 study() 函數。即使 study() 結束，Pencil 實例不會立即被釋放，這是因為閉包對 pencil 變數的隱式引用（implicit capturing），而<strong>不是</strong>閉包對Pencil 實例形成新的強引用。</p><p>所以可以想成：<strong>study( ) 跑完後，閉包還持續引用變數，導致變數和其指向的實例無法被釋放。</strong></p><p>直到閉包跑完，變數的引用才會解除，並且強引用的實例也會被釋放。</p><pre>func study() {<br>    var pencil: Pencil? = Pencil()<br>    Timer.scheduledTimer(withTimeInterval: 3, repeats: false, block: { _ in<br>        print(&quot;after 3 secs, going to write&quot;)<br>        if let pencil {<br>            pencil.write()<br>        } else {<br>            print(&quot;no pencil&quot;)<br>        }<br>    })<br>    print(&quot;Finish Studying&quot;)<br>}<br>study()<br><br>// 輸出結果：<br>Pencil comes up<br>Finish Studying<br>after 3 secs, going to write<br>Write Hello<br>Break the pencil</pre><p>如果我們不想要閉包引用變數，從而防止實例無法被釋放，我們可以使用 capture list。</p><p>這樣，閉包不會引用外部作用域的變數，而是創建一個新的變數，儲存該實例的引用，閉包直接使用新變數。</p><p>然而，即使這樣，實例仍然不會被釋放。因為雖然變數 pencil 不再被閉包引用而被釋放，但閉包內的<strong>新變數仍然強引用該實例</strong>。</p><p>為了避免這個問題，可以在 capture list 中使用 weak，這樣閉包內的變數對實例只會產生<strong>弱引用</strong>。</p><p>以下範例中，當 study() 執行結束時，實例立即被釋放，因為 pencil 變數不再被閉包引用，閉包內的變數對實例是弱引用，實例的 ARC 計數降為 0，直接被原地超渡 👼🏻。</p><pre>func study() {<br>    var pencil: Pencil? = Pencil()<br>    Timer.scheduledTimer(withTimeInterval: 3, repeats: false, block: { [weak pencil] _ in<br>        print(&quot;after 3 secs, going to write&quot;)<br>        if let pencil {<br>            pencil.write()<br>        } else {<br>            print(&quot;no pencil&quot;)<br>        }<br>    })<br>    print(&quot;Finish Studying&quot;)<br>}<br>study()<br><br>// 輸出結果：<br>Pencil comes up<br>Finish Studying<br>Break the pencil<br>after 3 secs, going to write<br>no pencil</pre><h3>結論：</h3><p>感覺以上的測試又臭又長ＸＤ這邊做個總結，以防以後我看不到重點🫠🫠🫠</p><blockquote>使用 Implicit capturing （不特別使用 capture list）</blockquote><ul><li>不管是捕獲值型別還是引用型別的變數，捕獲的都是變數的引用。</li><li>因此，無論是外部變數的修改，還是閉包內對捕獲變數的修改，都會影響變數的內容。</li></ul><blockquote>使用capture list 捕獲值型別的變數：</blockquote><ul><li>會複製一份變數的值到閉包內的新變數。</li><li>因此，外部變數的變動不會影響閉包內捕獲到的值。</li></ul><blockquote>使用capture list 捕獲引用型別的變數：</blockquote><ul><li>會複製實例的引用到閉包內的新變數。</li><li>因此，無論是外部變數還是閉包內對實例的修改，兩者都會影響實例的內容。</li></ul><blockquote>取消 capture list 對實例造成的強引用：</blockquote><ul><li>可以使用 weak 或 unowned 來避免閉包對實例產生強引用。</li></ul><p>結語：</p><p>一開始我以為 capture 會直接對所有實例產生強引用，但後來發現好像不是全部都這麼回事，特別是使用 Implicit capturing 捕獲引用型別變數時，並不會自動增加對實例的強引用。</p><p>以上，是我這次閱讀資料後的心得，但這是看完資料並加上自己的理解而記錄的，若有緣人看到並發現錯誤，希望可以指教~🙂‍↕️</p><p>Reference：</p><ul><li><a href="https://docs.swift.org/swift-book/documentation/the-swift-programming-language/closures/#Capturing-Values">Documentation</a></li><li><a href="https://www.swiftbysundell.com/articles/swifts-closure-capturing-mechanics/">Swift&#39;s closure capturing mechanics | Swift by Sundell</a></li></ul><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FlDKuSKrEeAk%3Flist%3DPLXM8k1EWy5ki_TSdt_Gxd3JRnnaucBiFW&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DlDKuSKrEeAk&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FlDKuSKrEeAk%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/7c044b8e4cdc7158e71ede2944d53605/href">https://medium.com/media/7c044b8e4cdc7158e71ede2944d53605/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0aa461ca45d0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[#32 Background Tasks]]></title>
            <link>https://koloa1989.medium.com/32-background-tasks-0098a229b1d9?source=rss-29f0f755c933------2</link>
            <guid isPermaLink="false">https://medium.com/p/0098a229b1d9</guid>
            <dc:creator><![CDATA[Jeff Lin]]></dc:creator>
            <pubDate>Wed, 21 Aug 2024 07:12:07 GMT</pubDate>
            <atom:updated>2024-12-29T16:24:02.911Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lEE3C1sVIvD6vW8qer174w.jpeg" /></figure><p>前言：</p><p>本來想要找有沒有方法可以在App是關閉的情況下，喚醒App然後做事，接著就查到了Background Task，花了時間研究後，發現這個方法完全不可行XD，但還是記錄一下這個刻骨銘心的研究過程🫠。</p><pre>目錄：<br><a href="#d431">BackgroundTasks framework介紹</a><br><a href="#c0ef">選擇何種Task</a><br><a href="#ce38">重要物件解釋</a><br><a href="#1461">Implement<br></a><a href="#0497">實際測試</a></pre><h3>BackgroundTasks framework：</h3><p>使用 BackgroundTasks 框架可以用來確保應用程式內容為最新，並在應用程式處於<strong>背景</strong>時執行需要數分鐘才能完成的任務。較長時間的任務可以選擇性地要求外部電源和網路連接。</p><p>當應用程式啟動時，會為任務註冊啟動處理程式。系統會在背景中啟動您的應用程式並執行這些任務。</p><p><a href="https://developer.apple.com/documentation/BackgroundTasks">Background Tasks | Apple Developer Documentation</a></p><h3>選擇策略：</h3><p>為了達到效能最佳化，Apple建議使用者根據不同的使用情境，來訂定適合的background task。</p><p><a href="https://developer.apple.com/documentation/backgroundtasks/choosing-background-strategies-for-your-app#overview">Choosing Background Strategies for Your App | Apple Developer Documentation</a></p><blockquote>Continue Foreground Work in the Background <br>(在背景執行前景正在執行的任務，例如把訊息傳送出去或把檔案下載完)</blockquote><ul><li>用 beginBackgroundTask(withName:expirationHandler:)，系統會給予app在<strong>有限的時間</strong>內繼續完成任務。 記得要在 expirationHandler 參數內用<strong>case</strong> 來表示時間用盡的情況，任務沒有完成的話要取消還是延遲，以確保應用程式能夠順利返回到前台或關閉，避免因為長時間的後台運行導致應用程式被系統強制終止。</li><li>endBackgroundTask(_:) 要在task完成後呼叫，應用程式才能夠正常地進入後台暫停狀態，否則應用程式可能會被系統強制關閉。</li><li>如果是需要花時間的程序，像是下載或上傳，則可以參考以下文章：</li></ul><p><a href="https://developer.apple.com/documentation/foundation/url_loading_system/downloading_files_in_the_background">Downloading files in the background | Apple Developer Documentation</a></p><blockquote>Defer Intensive Work (推遲密集任務)：</blockquote><ul><li>為了維持電池壽命與效能，一些比較heavy的工作像是機器訓練或database的維護等，可以放在payload較低的時候做，例如晚上。</li><li>使用BGProcessingTask 來及行此類型的任務，系統會挑選最適合的時間去執行。</li><li>如果應用程式涉及健康研究，這些研究可能有一些耗時的任務需要在背景中完成。對於這類型的背景任務，應該使用 BGHealthResearchTask 來進行排程。</li><li>總結來說，這段話建議將密集的工作安排在設備低活動量的時段，並提供了如何使用相應的背景任務類型（BGProcessingTask 和 BGHealthResearchTask）來實現這一目的。</li></ul><blockquote>Update Your App’s Content (更新app內容)：</blockquote><ul><li>如果app只需要短時間去更新app的內容，像是從server抓資料更新畫面，或是定期更新app狀態，可以使用 BGAppRefreshTask，接著透過請求 BGAppRefreshTaskRequest 來進行排程。</li><li>如果你的應用程式涉及用戶參與的健康研究，則可以用 BGHealthResearchTaskRequest 來在背景中啟動並處理相關數據。</li><li>系統會決定啟動你的背景任務的最佳時間，並提供最多<strong>30秒</strong>的背景運行時間。在這段時間內完成你的工作並呼叫 setTaskCompleted(success:)，否則系統會終止你的應用程式。</li></ul><blockquote>Wake Your App with a Background Push：</blockquote><ul><li>如果app的內容都是以server提供的內容為主，且server更新頻率並不高，更新app時間也不一定，那就可以使用<strong>background notifications</strong>來通知app有新的內容可以更新。</li><li>background notification是一種remote notification，他不會出現alert, sound, 或 badge 。這類的應用用在像是把對話mute掉的message app或信件app。</li><li>set content-available 為<strong>1</strong>，就不會出現alert, sound, 或 badge 。系統會自己決定何時去更新app的內容。</li><li>設置 apns-priority 為 <strong>5</strong> 和 apns-push-type 為 <strong>background</strong>，這些設置確保你的應用程序能夠被系統喚醒並在後台下載內容。</li><li>當系統通過application(_:didReceiveRemoteNotification:fetchCompletionHandler:)來接受remote notification後，系統會給予<strong>30秒</strong>來處理task。一但完成task，要呼叫fetchCompletionHandler以節省電量。</li><li>如果一個小時內有<strong>超過三次</strong>的background push，系統會自動限制數量。</li></ul><blockquote>Request Background Time and Notify the User：</blockquote><ul><li>如果app需要在background執行，並跳出Notification通知使用者，則可以使用<strong>Notification Extension（UNNotificationServiceExtension）。</strong>(例如mail下載完後要通知使用者)</li><li>繼承 UNNotificationServiceExtension 類，並將這個系統擴展與你的應用程式打包在一起</li><li>當收到推送通知時，你的服務擴展會被喚醒，通過 didReceive(_:withContentHandler:) 獲取背景運行時間。</li><li>在有限時間內，必須呼叫content handler，並在裡頭處理想要呈現user的content。</li></ul><p>以上是關於針對不同情況，background task可以如何選擇的內容。</p><p>而這次的測試專案，是單純使用userDefault的資料而已，因此使用的策略是偏向<strong>Update Your App’s Content。</strong></p><h3>重要物件解釋：</h3><p><strong>決定Update Your App’s Content後</strong>，以下為介紹會用到的重要物件。</p><h4><strong>BGTaskScheduler：</strong></h4><p>這是一個規劃何時要執行background task的元件，需要使用這個元件來註冊你想要執行的task是什麼。</p><p>在註冊task的時候應該要在app launch sequence結束之前，所以應該放在appDelegate裡面註冊。</p><pre>(原文)<br> Register all of the tasks before the end of the app launch sequence. <br> For more information, see About the app launch sequence.</pre><ul><li><a href="https://developer.apple.com/documentation/backgroundtasks/bgtaskscheduler">BGTaskScheduler | Apple Developer Documentation</a></li><li><a href="https://developer.apple.com/documentation/uikit/app_and_environment/scenes/preparing_your_ui_to_run_in_the_background/using_background_tasks_to_update_your_app#3193993">Using background tasks to update your app | Apple Developer Documentation</a></li></ul><h4><strong>BGAppRefreshTask：</strong></h4><p>適用於<strong>短時間內能完成的任務</strong>，這些任務通常期望能夠快速獲得結果。例如，下載股票行情就是一個典型的短時間任務。這類任務通常在短時間內執行並完成。此物件具有以下特性：</p><blockquote><strong><em>設定處理任務的能力：</em></strong></blockquote><p>要此用這個task前，必須要在target設定UIBackgroundMode為<strong>Background fetch</strong>。</p><blockquote><strong><em>處理任務的執行條件：</em></strong></blockquote><p>當 BGAppRefreshTask 已經在背景中執行時，即使用戶開始使用手機，這個任務也不會被系統終止。換句話說，BGAppRefreshTask 可以在用戶使用設備的同時繼續運行，而不會因為用戶的操作（如解鎖設備、打開應用程式等）而被中斷。</p><blockquote><strong><em>Task辨識：</em></strong></blockquote><p>給予在info plist設定的ID，來當作這個task的識別碼</p><p><a href="https://developer.apple.com/documentation/backgroundtasks/bgapprefreshtask">BGAppRefreshTask | Apple Developer Documentation</a></p><h4>BGProcessingTask：</h4><p>雖然不會用到這個Task，但是這物件在其他情況下很常會被使用，所以特別記錄下來，也可以與我們會用到的BGAppRefreshTask比較。</p><p>需要花費<strong>大量時間執行的任務</strong>，像是下載大型文件、同步數據、或應用程式維護時，應該使用 BGProcessingTask。這些任務可以持續數分鐘，但系統<strong>可能會中斷這些任務</strong>。</p><blockquote><strong>過期處理程序</strong>：</blockquote><p>由於系統可能會中斷正在執行的處理任務，你應該通過設置 expirationHandler 來添加一個過期處理程序。這個處理程序可以用來在任務被中斷時執行必要的清理工作。</p><blockquote><strong>設定處理任務的能力</strong>：</blockquote><p>要此用這個task前，必須要在target設定UIBackgroundMode為<strong>Background processing</strong>。</p><blockquote><strong>處理任務的執行條件</strong>：</blockquote><p>處理任務只有在設備<strong>閒置</strong>時才會運行。一旦用戶開始使用設備，系統會終止所有正在運行的背景處理任務。相比之下，BGAppRefreshTask可以在用戶使用設備的同時繼續執行，不會被系統強制中斷。</p><blockquote><strong>Task辨識：</strong></blockquote><p>給予在info plist設定的ID，來當作這個task的識別碼</p><p><a href="https://developer.apple.com/documentation/backgroundtasks/bgprocessingtask">BGProcessingTask | Apple Developer Documentation</a></p><h4>BGAppRefreshTaskRequest：</h4><p>用此物件來實際提交一個短時間refresh的背景任務，以喚醒App。此物件具有以下重點：</p><blockquote><strong>ID</strong>：</blockquote><p>request 包含一個唯一的標識符，它用來與你在 AppDelegate 中註冊的任務對應。</p><blockquote><strong>Request類型</strong>：</blockquote><p>這類Request明確定義要執行的Task是a short refresh task。</p><blockquote><strong>預定執行時間 (EarliestBeginDate)</strong>：</blockquote><p>你可以設置 request.earliestBeginDate 來指定任務最早可以被執行的時間。系統會根據它的判斷在合適的時間執行這個任務。</p><blockquote><strong>優先級</strong>：</blockquote><p>雖然apple沒有API讓我們控制優先級，但是BGProcessingTaskRequest提交的Task能獲得比BGAppRefreshTaskRequest更多的系統資源。</p><p><a href="https://developer.apple.com/documentation/backgroundtasks/bgapprefreshtaskrequest">BGAppRefreshTaskRequest | Apple Developer Documentation</a></p><h3>Implement：</h3><p>溫馨提醒❤：</p><blockquote>實作只能在實機上跑！</blockquote><h4>前置作業：</h4><ol><li>在capability裡加入<strong>background mode</strong></li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ausQsOXyjVkpIYnAchJxVQ.png" /></figure><p>2. 在info plist加入Permitted background task scheduler identifiers選項，並設定ID</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D5YsB-Fm0_cyotE0MeF5sQ.png" /></figure><h4>註冊Task：</h4><p>這個註冊過程是告訴系統應用可能會在未來的某個時間點需要執行某種類型的背景任務。註冊通常包括設定一個<strong>ID</strong>和一個<strong>處理程序</strong>來在任務執行時調用。</p><p>根據前面的敘述，註冊Task應該在“app launch sequence結束之前”，根據官方提供的圖對照，要寫在appDelegate裡。</p><p><a href="https://developer.apple.com/documentation/uikit/app_and_environment/responding_to_the_launch_of_your_app/about_the_app_launch_sequence#3894431">About the app launch sequence | Apple Developer Documentation</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/484/1*5yTvsdKgwVZ9bkCKgRNvFw.png" /></figure><blockquote><strong>步驟：</strong></blockquote><ol><li>先使用Bundle.main.infoDictionary將我在info plist設定的ID讀出來，供後續程式碼使用。</li><li>使用BGTaskScheduler的函式register(forTaskWithIdentifier:using:launchHandler:)註冊Task，並代入先前在info plist設定的ID。</li><li>register的閉包內要調用想要執行的程式碼，最後一定要呼叫BGAppRefreshTask的函式setTaskCompleted(success:)，系統才知道任務完成，不然就會直接殺掉你的任務。</li></ol><pre>class AppDelegate: UIResponder, UIApplicationDelegate {<br><br>    let id = (Bundle.main.infoDictionary?[&quot;BGTaskSchedulerPermittedIdentifiers&quot;] as? [String])?.first<br>    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -&gt; Bool {<br>        // Override point for customization after application launch.<br>        // regist handler for task<br>        BGTaskScheduler.shared.register(forTaskWithIdentifier: id ?? &quot;&quot;, using: nil) { task in<br>            guard let task  = task as? BGAppRefreshTask else { return }<br>            self.handleTask(task: task) {<br>              .....<br>            }<br>            print(&quot;Regist Success&quot;)<br>        }<br>        return true<br>    }<br>    <br>  ....<br>  <br>  ....<br>  <br>    // MARK: Custom Function<br>    func handleTask(task: BGAppRefreshTask, completion: @escaping () -&gt; Void) {<br>        // count<br>        let count = UserDefaults.standard.integer(forKey: &quot;bgNumber&quot;)<br>        UserDefaults.standard.setValue(count+1, forKey: &quot;bgNumber&quot;)<br>        // date<br>        let date = Date()<br>        let formatter = DateFormatter()<br>        formatter.dateFormat = &quot;yyyy/MM/dd HH:mm:ss&quot;<br>        let dateStr = formatter.string(from: date)<br>        var dateStrArray = UserDefaults.standard.stringArray(forKey: dateStr) ?? []<br>        dateStrArray.append(dateStr)<br>        UserDefaults.standard.setValue(dateStrArray, forKey: &quot;dateStr&quot;)<br>        // task complete<br>        task.setTaskCompleted(success: true)<br>        completion()<br>    }<br>}</pre><h4>提交註冊的Task的請求：</h4><p>提交Task前須先建立一個BGAppRefreshTaskRequest的物件，並用這個物件來實際提交這個背景任務。</p><p>這個請求告訴系統對於這個任務的<strong>細節設定</strong>。像是要在何時開始執行任務，屬於什麼類型的任務。</p><blockquote>步驟：</blockquote><ol><li>在appDelegate裡使用BGTaskScheduler.shared.getPendingTaskRequests來確認目前有沒有pending的task，沒有等待執行的task時，才提交新的task，並在task完成後，會再重新提交一次。</li><li>BGTaskScheduler的函式submit(_:)提交並執行Task。在submit(_:)裡帶入參數BGAppRefreshTaskRequest，表示告訴系統這是一個應用刷新任務。</li><li>若有需要，可以使用request.earliestBeginDate來告訴系統這個task要在多久後執行，但<strong><em>執行時間仍由系統決定</em></strong>。</li></ol><pre>class AppDelegate: UIResponder, UIApplicationDelegate {<br><br>//    let id = (Bundle.main.object(forInfoDictionaryKey: &quot;Permitted background task scheduler identifiers&quot;) as? [String])?.first<br>    let id = (Bundle.main.infoDictionary?[&quot;BGTaskSchedulerPermittedIdentifiers&quot;] as? [String])?.first<br>    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -&gt; Bool {<br>        // Override point for customization after application launch.<br>        // regist handler for task<br>        guard let task  = task as? BGAppRefreshTask else { return }<br>            self.handleTask(task: task) {<br>                //任務完成後，自動提交下一次的task<br>                self.schedual()<br>            }<br>        .....<br>        // schedual task<br>        schedual()<br>        return true<br>    }<br><br>    fileprivate func schedual() {<br>//        BGTaskScheduler.shared.cancelAllTaskRequests()<br>        BGTaskScheduler.shared.getPendingTaskRequests { requests in<br>            print(&quot;pending requests counts: \(requests.count)&quot;)<br>            if requests.isEmpty {<br>                do {<br>                    let request = BGAppRefreshTaskRequest(identifier: self.id ?? &quot;&quot;)<br>        //            request.earliestBeginDate = Date().addingTimeInterval(86400*3)<br>                    try BGTaskScheduler.shared.submit(request)<br>                    print(&quot;Submit Success&quot;)<br>                } catch {<br>                    print(&quot;Submit Error&quot;)<br>                }<br>            }<br>        }<br>    }<br>}</pre><p>若有提交成功，則下一次開啟app時，debugger會印出pending中的task數量。</p><h4>驗證：</h4><p>我覺得Background Task的很重要的特點是：「我會做，但不告訴你我什麼時候做」。</p><p><strong>因此要怎麼驗證自己寫的code真的能夠執行呢？</strong></p><p>很貼心的，apple有提供API給我們去強制執行Background Task，以確認code可以正確地執行。</p><blockquote>步驟：</blockquote><ol><li>在成功執行完submit(_:)的下一行程式碼設一個中斷點</li><li>執行App，等待程式跑到中斷點的地方</li><li>在debugger區域，有條綠色的輸入欄，輸入以下程式碼：</li></ol><p>e -l objc — (void)[[BGTaskScheduler sharedScheduler] _simulateLaunchForTaskWithIdentifier:@”TASK_IDENTIFIER”]</p><p>其中TASK_IDENTIFIER 換成我們真實設定的ID，接著按下Enter</p><p>4. 等待debugger出現新的訊息後，按下resume即完成</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*67PHOZ-IgmIfCIpxq65bhw.png" /><figcaption>示範</figcaption></figure><p><a href="https://developer.apple.com/documentation/backgroundtasks/starting-and-terminating-tasks-during-development">Starting and Terminating Tasks During Development | Apple Developer Documentation</a></p><h4>實際測試：</h4><p>當 App 在背景運作時，會記錄當下的時間，並把呈現在 Label 上的數字 + 1，結束 Task 後，會自動註冊下一次的 Request。花兩天的時間觀察，結果如下：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F8mbDg_qBttASqo_iiArNA.gif" /></figure><p>可以觀察到，App更新的時間沒有一個規律，比台北的天氣還陰晴不定。</p><p>後記：</p><p>看了各種影片與官方文件跟留言串，收穫滿滿，尤其最大的收穫，就是知道這方法行不通ＸＤ</p><p>以下是大神說行不通的原因，主要就是App的State 的關係。</p><p><a href="https://stackoverflow.com/questions/61928130/background-tasks-on-ios-13-bgtaskscheduler">Background tasks on IOS 13 (BGTaskScheduler)</a></p><p>但這個framework感覺很重要，還是很慶幸有提前學習這塊🤭</p><p>同場加映：</p><p>WWDC影片：</p><p><a href="https://developer.apple.com/videos/play/wwdc2019/707">Advances in App Background Execution - WWDC19 - Videos - Apple Developer</a></p><p>UIBackgroundMode的選擇：</p><ul><li><a href="https://developer.apple.com/documentation/bundleresources/information_property_list/uibackgroundmodes">UIBackgroundModes | Apple Developer Documentation</a></li><li><a href="https://developer.apple.com/documentation/xcode/configuring-background-execution-modes">Configuring background execution modes | Apple Developer Documentation</a></li></ul><p>Reference：</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FLb7OShyNSdM%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DLb7OShyNSdM&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FLb7OShyNSdM%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/3a9461fdac73081acdb52e2e0d37836c/href">https://medium.com/media/3a9461fdac73081acdb52e2e0d37836c/href</a></iframe><ul><li><a href="https://medium.com/mobil-dev/background-task-with-bgtaskscheduler-1d49e22b1519">Background Task with BGTaskScheduler</a></li><li><a href="https://misomiso43.medium.com/background-fetch-38cca0e91f11">Background Fetch</a></li><li><a href="https://medium.com/@dbabic_38867/background-tasks-on-ios-c27366723b6d">Background Tasks on iOS</a></li></ul><p>GitHub：</p><p><a href="https://github.com/ChingDD/BGTaskScheduler_Demo">GitHub - ChingDD/BGTaskScheduler_Demo</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0098a229b1d9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[#31 App間傳送資訊-Multipeer Connectivity framework]]></title>
            <link>https://koloa1989.medium.com/31-app%E9%96%93%E5%82%B3%E9%80%81%E8%B3%87%E8%A8%8A-multipeer-connectivity-framework-66a308d81ce4?source=rss-29f0f755c933------2</link>
            <guid isPermaLink="false">https://medium.com/p/66a308d81ce4</guid>
            <dc:creator><![CDATA[Jeff Lin]]></dc:creator>
            <pubDate>Tue, 16 Jul 2024 02:06:31 GMT</pubDate>
            <atom:updated>2024-07-16T02:06:31.586Z</atom:updated>
            <content:encoded><![CDATA[<p>前言：去年寫了一個冰箱的App，後來有被建議說紀錄的物品可以跟家庭分享會更好，後來就查到這個簡單傳送資料的方法，以下是這個framework的紀錄：</p><h3>Multipeer Connectivity framework:</h3><p>這是一個利用infrastructure Wi-Fi networks, peer-to-peer Wi-Fi, and Bluetooth personal area networks 進行資料傳輸的一個工具。（但實際上把藍牙跟wifi通通關掉，還是可以連線）</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FamYDdm2lssM%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DamYDdm2lssM&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/3ce124601f564190e57524d2a568582e/href">https://medium.com/media/3ce124601f564190e57524d2a568582e/href</a></iframe><p>官方文件說明：<a href="https://developer.apple.com/documentation/multipeerconnectivity">https://developer.apple.com/documentation/multipeerconnectivity</a></p><h3>開始前（加入permissions）：</h3><p>在使用此framework前，必須要在info plist輸入NSLocalNetworkUsageDescription 與NSBonjourServices。NSBonjourServices的格式如下：<em>_[myservicetype]._[transporttype]</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*j_cQhUG7IGxT_BkDpg5XNg.png" /></figure><h3>重要物件說明：</h3><h4><strong>MCPeerID</strong>：</h4><p>這個ID是用來顯示目前設備的名稱，通常可以用UIDevice.current.name，但也可以打任何你想要的字串。</p><h4><strong>MCSession</strong>：</h4><p>session物件支持互相連線的device間進行傳輸的行為</p><pre>var peerSession = MCSession(peer: peerId, securityIdentity: nil, encryptionPreference: .none)</pre><ul><li>peer：Device要顯示的名稱</li><li>securityIdentity：是否需要進行驗證</li><li>encryptionPreference：是否需要加密</li></ul><h4><strong>MCBrowserViewController / MCNearbyServiceBrowser</strong>：</h4><p>為Host，他會負責搜尋有沒有誰想要加入Host開的Session。</p><ol><li>使用MCBrowserViewController建立觀察者：</li></ol><pre>let peerBrowserVC = MCBrowserViewController(serviceType: serviceType, session: peerSession)</pre><ul><li>serviceType：為獨一無二的字串，可以隨意，若與其他App相同，則也會觀察到其他App的device出現在邀請的選單上<br>關於serviceType的規定：</li></ul><pre>- Must be 1–15 characters long<br>- Can contain only ASCII lowercase letters, numbers, and hyphens<br>- Must contain at least one ASCII letter<br>- Must not begin or end with a hyphen<br>- Must not contain hyphens adjacent to other hyphens.</pre><ul><li>session：Host / Browser建立的Session</li></ul><p>2. 使用MCNearbyServiceBrowser建立觀察者：</p><pre>let peerBrowser = MCNearbyServiceBrowser(peer: peerId, serviceType: serviceType)</pre><ul><li>serviceType：同MCBrowserViewController裡的描述</li><li>peer：自己的設備要顯示的名稱</li></ul><h4><strong>MCNearbyServiceAdvertiser</strong>：</h4><p>我認為像是Guest，他會發送advertisement，告訴周圍的人有他目前想加入特定的session，看有沒有人願意收留他(?</p><pre>MCNearbyServiceAdvertiser(peer: peerId, discoveryInfo: nil, serviceType: serviceType)</pre><ul><li>peerId：Device要顯示的名稱</li><li>discoveryInfo：發送的請求裡夾帶的訊息，為字串，可以拿來當作版本或使用者的資料。關於discoveryInfo的格式如下：</li></ul><pre>- This data is advertised using a Bonjour TXT record, encoded according to [RFC 6763](http://tools.ietf.org/html/rfc6763) (section 6). As a result:<br>- The key-value pair must be no longer than 255 bytes (total) when encoded in UTF-8 format with an equals sign (`=`) between the key and the value.<br>- Keys cannot contain an equals sign.</pre><ul><li>serviceType：同MCBrowserViewController / MCNearbyServiceBrowser裡的敘述。</li></ul><h3>Implement：</h3><h4>1. 建立用得到的變數：</h4><pre>// 這個 peer session的service 可以任意取，但要獨一無二<br>let serviceType = &quot;item-peer&quot;<br><br>// 這台設備呈現出來的名字<br>let peerId = MCPeerID(displayName: UIDevice.current.name)<br><br>//建立Advertiser來播報需求，好讓Browser可以搜尋到Advertiser<br>var peerAdvertiser: MCNearbyServiceAdvertiser?<br><br>// 用來支援資料傳輸的session.<br>var peerSession: MCSession?<br><br>// Browser object 用來搜尋周圍有沒有送出訊息的Advertiser，以對他送出邀請並進行連線<br>var peerBrowser: MCNearbyServiceBrowser?<br>var peerBrowserAssistant: MCAdvertiserAssistant?</pre><h4>2. 在viewDidLoad進行初始化：</h4><pre>peerSession = MCSession(peer: peerId, securityIdentity: nil, encryptionPreference: .none)<br>peerSession?.delegate = self</pre><h4>3. 建立Advertiser：</h4><p>當advertisement的物件被做出來後，要使用startAdvertisingPeer，請求才會被發送出去。</p><p>controller必須要當Advertiser的delegate，去實作func advertiser(_ advertiser: didReceiveInvitationFromPeer peerID:withContext context: invitationHandler:) 。當browser搜尋到該advertiser的請求並對他發送invitation後，若advertiser收到Host的invitation，便會啟動這段程式碼。</p><p>參數context：表示browser發出邀請時，若有夾帶資料，則可以用context將資料讀出來。</p><p>參數invitationHandler：用<strong>true</strong>或<strong>false</strong>來決定advertiser是否要接受browser發出來的邀請。結尾一定要使用invitationHandle，這段程式碼才會結束。</p><pre>@objc func sendRequest(action: UIAlertAction) {<br>    let discoveryInfo = [<br>        &quot;appVersion&quot;: &quot;1.0.0&quot;,<br>        &quot;userName&quot;: &quot;Jeff Lin&quot;<br>    ]<br>    peerAdvertiser = MCNearbyServiceAdvertiser(peer: peerId, discoveryInfo: discoveryInfo, serviceType: serviceType)<br>    peerAdvertiser?.delegate = self<br>    peerAdvertiser?.startAdvertisingPeer()<br>    let ac = UIAlertController(title: nil, message: &quot;已發出請求&quot;, preferredStyle: .alert)<br>    let okAction = UIAlertAction(title: &quot;確認&quot;, style: .default)<br>    ac.addAction(okAction)<br>    present(ac, animated: true)<br>}<br><br><br>extension ViewController: MCNearbyServiceAdvertiserDelegate {<br>    // 當advertiser收到browser的邀請後想做些什麼事<br>    func advertiser(_ advertiser: MCNearbyServiceAdvertiser,<br>                    didReceiveInvitationFromPeer peerID: MCPeerID,<br>                    withContext context: Data?,<br>                    invitationHandler: @escaping (Bool, MCSession?) -&gt; Void) {<br>        print(&quot;did Receive Invitation From Peer:\(peerID.displayName)&quot;)<br>        var ac = UIAlertController(title: &quot;Request&quot;, message: &quot;\(peerID.displayName) wants to join&quot;, preferredStyle: .alert)<br>        //若advertiser有收到Browser傳來的invitation裡的資訊，就將它呈現在在alertController上<br>        if let msg = String(data: context ?? Data(), encoding: .utf8) {<br>            ac = UIAlertController(title: &quot;Request&quot;, message: msg, preferredStyle: .alert)<br>        }<br>        let okAction = UIAlertAction(title: &quot;Accept&quot;, style: .default) { _ in<br>            invitationHandler(true, self.peerSession)<br>        }<br>        let cancelAction = UIAlertAction(title: &quot;Decline&quot;, style: .cancel) { _ in<br>            invitationHandler(false, nil)<br>        }<br>        ac.addAction(okAction)<br>        ac.addAction(cancelAction)<br>        present(ac, animated: true)<br>    }<br>}</pre><h4>4. 建立Browser：</h4><p><strong>方法一：</strong></p><p>使用<strong>MCNearbyServiceBrowser</strong>。controller要成為browser的delegate，並實作func browser(_ browser:, foundPeer peerID:, withDiscoveryInfo info:)。</p><p>當browser搜尋到advertiser後，會執行這段function。可以使用peerID.displayName來辨識出找到的advertiser是誰。withDiscoveryInfo則是advertiser發出請求時，他所夾帶的資料，以我的例子，我的advertiser發出請求時會攜帶[ “appVersion”: “1.0.0”, “userName”: “Jeff Lin” ]，當browser收到請求時，則可以從參數withDiscoveryInfo裡會抓出[ “appVersion”: “1.0.0”, “userName”: “Jeff Lin” ] 。</p><p>收尋到發送請求的advertiser後，會直接發出invitation，因此advertiser會直接執行func advertiser(_ advertiser:, didReceiveInvitationFromPeer peerID:, withContext context:, invitationHandler: )。</p><pre>// 方法一<br>// Advertiserd方<br>@objc func sendRequest(action: UIAlertAction) {<br>    let discoveryInfo = [<br>        &quot;appVersion&quot;: &quot;1.0.0&quot;,<br>        &quot;userName&quot;: &quot;Jeff Lin&quot;<br>    ]<br>    peerAdvertiser = MCNearbyServiceAdvertiser(peer: peerId, discoveryInfo: discoveryInfo, serviceType: serviceType)<br>    peerAdvertiser?.delegate = self<br>    peerAdvertiser?.startAdvertisingPeer()<br>    let ac = UIAlertController(title: nil, message: &quot;已發出請求&quot;, preferredStyle: .alert)<br>    let okAction = UIAlertAction(title: &quot;確認&quot;, style: .default)<br>    ac.addAction(okAction)<br>    present(ac, animated: true)<br>}<br><br>// Browser方<br>@objc func seekUser(action: UIAlertAction) {<br>    peerBrowser = MCNearbyServiceBrowser(peer: peerId, serviceType: serviceType)<br>    peerBrowser?.delegate = self<br>    peerBrowser?.startBrowsingForPeers()<br>}<br><br>extension ViewController: MCNearbyServiceBrowserDelegate {<br>    func browser(_ browser: MCNearbyServiceBrowser, foundPeer peerID: MCPeerID, withDiscoveryInfo info: [String : String]?) {<br>        print(&quot;Found peer: \(peerID.displayName)&quot;)<br>        guard let peerSession else { return }<br>        let invitationStr = &quot;\(peerId.displayName) would like to join the session&quot;<br>        let data = invitationStr.data(using: .utf8)<br>        browser.invitePeer(peerID, to: peerSession, withContext: data, timeout: 60)<br>    }<br>    <br>    func browser(_ browser: MCNearbyServiceBrowser, lostPeer peerID: MCPeerID) {<br>        print(&quot;Lost peer: \(peerID.displayName)&quot;)<br>    }<br>}</pre><p>方法二：</p><p>使用<strong>MCBrowserViewController</strong>。controller要成為MCBrowserViewController的delegate，並實作func browserViewControllerDidFinish(_ browserViewController: )與func browserViewControllerWasCancelled(_ browserViewController: ) 。這兩個程式碼可以決定按取消或完成後的要做的事情。</p><p>收尋到發送請求的advertiser後，會跳出advertiser的名稱，要點擊名稱後才會對advertiser發送邀請，接著才會執行func advertiser(_ advertiser: MCNearbyServiceAdvertiser, didReceiveInvitationFromPeer peerID:, withContext context: , invitationHandler: )。</p><pre>//方法二<br>@objc func seekUser(action: UIAlertAction) {<br>    guard let peerSession else { return }<br>    let peerBrowserVC = MCBrowserViewController(serviceType: serviceType, session: peerSession)<br>    peerBrowserVC.delegate = self<br>    present(peerBrowserVC, animated: true)<br>}<br><br>extension ViewController: MCBrowserViewControllerDelegate {<br>    func browserViewControllerDidFinish(_ browserViewController: MCBrowserViewController) {<br>        print(&quot;browser ViewController Did Finish&quot;)<br>        browserViewController.dismiss(animated: true)<br>    }<br>    <br>    func browserViewControllerWasCancelled(_ browserViewController: MCBrowserViewController) {<br>        print(&quot;browser ViewController Was Cancelled&quot;)<br>        browserViewController.dismiss(animated: true)<br>    }<br>}</pre><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F4Q2FjljsJIc&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D4Q2FjljsJIc&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/64faa302c1fc5871a624dd3c81a7ffb5/href">https://medium.com/media/64faa302c1fc5871a624dd3c81a7ffb5/href</a></iframe><h4>5. 離開Session：</h4><p>在這個framework裡，當app進入背景後，連線就會中斷，但回到前景時，advertiser與browser就會重新運作，因此會自動連線。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bfpatRsIodDEilZvEzWAWw.gif" /></figure><p>那如何永遠離開session呢？要調用stopAdvertisingPeer()與stopBrowsingForPeers()的函式，如下：</p><pre>peerAdvertiser?.stopAdvertisingPeer()<br>peerBrowser?.stopBrowsingForPeers()</pre><p>調用這兩個函式時，已連線的設備仍然會維持連線，但是當回到背景斷線後，再回到前景，則不會再自動連線。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3u11NUNtxZtAAcLTrxdj3g.gif" /></figure><h4>6. 傳送資料：</h4><p>當要傳送資料時，使用func send( _ data: toPeers peerIDs: with mode:) throws 。</p><ul><li><strong>data</strong>： 是你想要傳給其他peer的資料。</li><li><strong>peerIDs</strong>： 為你要傳的對象的peerID，這裡我會有個全域變數把已經加入的peer給儲存起來，方便這裡傳送data時使用。</li><li><strong>mode</strong>：主要是資料傳輸的模式，說明如下：</li></ul><pre>MCSessionSendDataMode有兩個選項：<br><br>.reliable:<br>這種模式確保數據可靠地傳輸到所有連接的設備。<br>系統會自動處理錯誤檢測和重傳，以確保數據的完整性。<br>適用於需要保證數據完整性的情況，如文件傳輸或重要信息交換。<br><br>.unreliable:<br>會馬上傳輸資料<br>這種模式不保證數據的可靠傳輸。<br>數據可能會丟失或無序到達。<br>適用於實時性要求高、可以容忍少量數據丟失的場景，如遊戲狀態更新或流媒體。</pre><p>根據上述的說明，可以根據數據完整性和傳輸速度之間權衡。</p><pre>// 儲存正在連線的peer<br>var connectedPeers: [MCPeerID]? = nil {<br>    didSet {<br>        DispatchQueue.main.async {<br>            guard let connectedPeers = self.connectedPeers else {<br>                self.connectedDeviceLabel.text = &quot;尚未連接&quot;<br>                print(&quot;connected Peers：\(self.connectedPeers)&quot;)<br>                return<br>            }<br>            self.connectedDeviceLabel.text = connectedPeers.map { $0.displayName }.joined(separator: &quot; &quot;)<br>            print(&quot;connected Peers：\(self.connectedPeers)&quot;)<br>        }<br>    }<br>}<br><br><br>@IBAction func tapShareBtn(_ sender: Any) {<br>    guard let connectedPeers else { return }<br>    let msg = msgTextField.text ?? &quot;No Input Msg&quot;<br>    if let data = msg.data(using: .utf8) {<br>        do {<br>            try peerSession?.send(data, toPeers: connectedPeers, with: .reliable)<br>        } catch {<br>            print(error)<br>        }<br>    }<br>}</pre><p>當peer收到data時，會觸發MCSessionDelegate裡的<strong>func</strong> session(_ session:, didReceive data:, fromPeer peerID:) 。可以在這個function裡擷取data進行想要的操作。</p><pre>// 收到訊息<br>func session(_ session: MCSession, didReceive data: Data, fromPeer peerID: MCPeerID) {<br>    DispatchQueue.main.async { [weak self] in<br>        if let string = String(data: data, encoding: .utf8) {<br>            self?.msgLabel.text = string<br>        } else {<br>            self?.msgLabel.text = &quot;No recieve msg&quot;<br>        }<br>    }<br>}</pre><h4>7. 當連線成員有改變：</h4><p>當連線的狀態發生改變時，會觸發MCSessionDelegate裡的<strong>func</strong> session(_ session:, peer peerID:, didChange state: )，我們可以在這裡根據不同狀態，做我們想做的事。</p><pre>// 當連線狀態有發生改變<br>func session(_ session: MCSession, peer peerID: MCPeerID, didChange state: MCSessionState) {<br>    print(&quot;連線狀態有發生改變:\(session.connectedPeers)&quot;)<br>    switch state {<br>    case .connected:<br>        print(&quot;Connected：\(peerID.displayName)&quot;)<br>    case .connecting:<br>        print(&quot;Connecting：\(peerID.displayName)&quot;)<br>    case .notConnected:<br>        print(&quot;Not Connected：\(peerID.displayName)&quot;)<br>    @unknown default:<br>        print(&quot;Unknown state：\(peerID.displayName)&quot;)<br>    }<br>    DispatchQueue.main.async {<br>        self.connectedPeers = session.connectedPeers<br>    }<br>}</pre><p>後記：看來我的冰箱App可以往闔家歡樂的路上邁進了。</p><p>以上敘述若有錯懇請指教！謝謝！</p><p>Reference：</p><p><a href="https://medium.com/@cleanrun/communicate-between-multiple-ios-devices-using-the-multipeer-connectivity-framework-468018af1839">Communicate between multiple iOS devices using the Multipeer Connectivity framework</a></p><p><a href="https://www.hackingwithswift.com/100/83">https://www.hackingwithswift.com/100/83</a></p><p>GitHub：</p><p><a href="https://github.com/ChingDD/MultipeerConnectivityDemo">GitHub - ChingDD/MultipeerConnectivityDemo</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=66a308d81ce4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[#30 利用Xcode在App Store Connect產生bundle ID]]></title>
            <link>https://koloa1989.medium.com/30-%E5%88%A9%E7%94%A8xcode%E5%9C%A8app-store-connect%E7%94%A2%E7%94%9Fbundle-id-4187ce7c8d31?source=rss-29f0f755c933------2</link>
            <guid isPermaLink="false">https://medium.com/p/4187ce7c8d31</guid>
            <dc:creator><![CDATA[Jeff Lin]]></dc:creator>
            <pubDate>Sun, 10 Mar 2024 07:48:52 GMT</pubDate>
            <atom:updated>2024-03-10T07:48:52.440Z</atom:updated>
            <content:encoded><![CDATA[<p>前言：繼上回#29，想要上傳App到app store connect時，要先在app store connect上產生一個App紀錄，之後在Xcode archive app後才能上傳到app store connect。</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/29-app-record-with-bundle-identifier-xxx-not-found-on-app-store-connect-cfadca6d71ae">#29 App record with bundle identifier “XXX” not found on App Store Connect</a></p><p>欲上傳的App的bundle ID如下：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GR9vdVw2zrq3lV6kLzPwSw.png" /></figure><p>但建立App紀錄時我遇到一個問題，就是<strong>清單上沒有我要的bundle ID!!!</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/950/1*V2POvVMjBH-HO5YvvFN82Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VLhkA1Fb7jzN7S8Ojy83Pg.png" /><figcaption><strong>清單上沒有QRcodeDemoTest2的bundel ID</strong></figcaption></figure><p>這個選單上沒有符合我app的bundle ID，因此我無法建立對應的App紀錄，該怎麼辦呢？我使用的方法如下：</p><blockquote>1. 開啟In-App Purchase：</blockquote><p>點選專案 -&gt; Target -&gt;Signing&amp;Capabilities -&gt; 選擇In-App Purchase</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g8yaPF3DFSAAs9PEAtmcFw.png" /></figure><p>看到藍色框框的內容表示新增成功</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1rANQv-dG_47OOAcEDghoQ.png" /></figure><blockquote>2. 前往App store connect檢查</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0R2jB9zSCdmlvhIZYTIwow.png" /></figure><p>此時清單上就出現<strong>QRcodeDemoTest2</strong>，如此便可以新增bundle id為QRcodeDemoTest2的App紀錄，以供bundle id為QRcodeDemoTest2的App可以上傳到這個紀錄裡。</p><p>Reference:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FcXxh5HHtflw%3Fstart%3D141%26feature%3Doembed%26start%3D141&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DcXxh5HHtflw&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FcXxh5HHtflw%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/5f10c8b50938e035d7362bfe3ddb61f6/href">https://medium.com/media/5f10c8b50938e035d7362bfe3ddb61f6/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4187ce7c8d31" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[#29 App record with bundle identifier “XXX” not found on App Store Connect]]></title>
            <link>https://medium.com/peter-pan-swift-ios-class/29-app-record-with-bundle-identifier-xxx-not-found-on-app-store-connect-cfadca6d71ae?source=rss-29f0f755c933------2</link>
            <guid isPermaLink="false">https://medium.com/p/cfadca6d71ae</guid>
            <dc:creator><![CDATA[Jeff Lin]]></dc:creator>
            <pubDate>Wed, 31 Jan 2024 17:20:20 GMT</pubDate>
            <atom:updated>2024-03-08T15:08:01.373Z</atom:updated>
            <content:encoded><![CDATA[<p>前言：依稀記得去年七月左右，把App上傳到TestFlight時，直接從Xcode archive後按下Distribute App，當 Xcode 發現 App Store Connect 沒有對應的 App 時，它將要求我們輸入 App 的基本資料，接著幫我們在 App Store Connect 建立 App紀錄後直接上傳，簡直是一路大順暢！</p><p>參考資料如下：</p><ul><li><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/%E5%B0%87-app-%E4%B8%8A%E5%82%B3%E5%88%B0-app-store-connect-2891ea8a758e">將 App 上傳到 App Store Connect</a></li><li><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/%E5%B0%87-ios-app-%E9%80%81%E5%AF%A9%E4%B8%8A%E6%9E%B6%E5%88%B0-app-store-2be449824ae2">將 iOS App 送審上架到 App Store</a></li></ul><p>然而最近要把App上傳到TestFlight時，卻出現以下錯誤：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4iGVUNK2c0yCwrXW55K_Wg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/946/1*euODcQmnpdO-QU_7Q8whkw.png" /></figure><p>不知道是中間有歷經改版的關係，還是我之前有做過但沒注意，但總之訊息告訴我：</p><blockquote>App store connect上沒有相對應的App紀錄給我上傳</blockquote><p>所以以下是紀錄如何在TestFlight建立App紀錄</p><pre><a href="#fe9c">1. 到App store connect後進入&quot;我的App&quot;，然後點選&quot;新的App&quot;<br></a><a href="#e0c3">2. 填寫資料填完，即可建立該App紀錄<br></a><a href="#5f17">3. 建立App紀錄失敗<br></a><a href="#0821">4. 上傳App到TestFlightg錯誤1-App沒設定icon<br></a><a href="#df36">5. 上傳App到TestFlightg錯誤2-icon沒透明</a></pre><blockquote>到App store connect後進入”我的App”，然後點選“新的App”</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/450/1*iLUqst3_id9ufXG7I_TJSA.png" /></figure><blockquote>填寫資料填完，即可建立該App紀錄</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*gw4ich7i_-6CH3aeUrQVnw.png" /></figure><p>名稱：該名稱會顯示在 App Store上，不能和別人一樣，也不能超過 30 個字。</p><p>主要語言: App 的主要語言。</p><p>套件識別碼：即為bundle ID。須與Xcode上的專案的bundle ID一致且獨一無二，否則App會無法上傳。</p><p>點選後可以找尋對應要上傳App的bundle ID</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9UXZrH28Kpc3fLeho4_-OQ.png" /></figure><p>SKU：App 獨一無二的 ID，不會顯示在 App Store 上。可以是任意字串，只要確保同帳號上架的App，其SKU沒有重複即可。</p><blockquote>建立紀錄失敗-未遵守最新協議</blockquote><p>我按下建立時，出現以下Error：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kH5NsPIqHzIQH1lQ3Kx9tA.png" /></figure><p>這種有講跟沒講一樣的錯誤，讓我看著螢幕發呆一下，然後很聽話地稍後再試，結果還是一樣，後來在我的App store connect首頁發現這個警示：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3DXb2rkoBYBUBp7iDyetTQ.png" /></figure><p>原來是因為有新的協議出來，我不同意就不給我上傳，因此當點進上面的藍字，全部同意後，就可以成功建立App紀錄拉～</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/808/1*Xo4XiqJIUmhR6gn3ZO9eqg.png" /></figure><blockquote>上傳App到TestFlight的錯誤</blockquote><p>當紀錄已經建立好，重複archive的步驟，理論上就可以把app上傳到App Store Connect裡的App紀錄儲存，然而此時我遇上兩個錯誤：</p><p><strong>第一個錯誤</strong>：<strong>有icon</strong>才能上傳，因此我新增了icon</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pL-V0vK59Ie9x8hkfy0pVQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m5J-ZFNNLPmeoWS3Pv_33Q.png" /></figure><p>結果重新archive一次，出現第二個錯誤：<strong>icon背景不能透明</strong>。因此<strong>打開圖片-&gt;檔案-&gt;輸出-&gt;把alpha取消</strong>，即可得到非透明背景的icon。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Iz4LyIZL7jNKbRV2fjmNuA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IAnUWtJ-vedaYLqqbOpN5w.png" /></figure><p>更新icon後重新archive，上傳即可成功！</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H-MY2b9tOHWMVXmiXiVg4g.png" /></figure><p>Reference：</p><ul><li><a href="https://www.appcoda.com.tw/ios-app-submission/">一步一腳印的 iOS App 上架和更新流程</a></li><li><a href="https://developer.apple.com/tw/help/app-store-connect/create-an-app-record/add-a-new-app/">加入新的 App</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cfadca6d71ae" width="1" height="1" alt=""><hr><p><a href="https://medium.com/peter-pan-swift-ios-class/29-app-record-with-bundle-identifier-xxx-not-found-on-app-store-connect-cfadca6d71ae">#29 App record with bundle identifier “XXX” not found on App Store Connect</a> was originally published in <a href="https://medium.com/peter-pan-swift-ios-class">彼得潘的 Swift iOS / Flutter App 開發教室</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>