<?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 Tommy on Medium]]></title>
        <description><![CDATA[Stories by Tommy on Medium]]></description>
        <link>https://medium.com/@tommy5566123?source=rss-dcc5ce982008------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*RP-KaVsw1_oiOKZdCHmFqg.jpeg</url>
            <title>Stories by Tommy on Medium</title>
            <link>https://medium.com/@tommy5566123?source=rss-dcc5ce982008------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 01:01:52 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@tommy5566123/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[iOS| #29 | NSOperation 筆記]]></title>
            <link>https://medium.com/@tommy5566123/ios-29-nsoperation-%E7%AD%86%E8%A8%98-67c7b12d64bd?source=rss-dcc5ce982008------2</link>
            <guid isPermaLink="false">https://medium.com/p/67c7b12d64bd</guid>
            <category><![CDATA[swift-programming]]></category>
            <dc:creator><![CDATA[Tommy]]></dc:creator>
            <pubDate>Tue, 26 Apr 2022 10:08:10 GMT</pubDate>
            <atom:updated>2022-04-26T10:08:10.080Z</atom:updated>
            <content:encoded><![CDATA[<h4>在iOS| #28提到了DispatchQueue、DispatchGroup、DispatchSemaphore的使用。這次要說明的NSOperation是比GCD更高階的元件。不僅可以達成上述物件的功能，甚至還可以做的更細膩。</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*tO3Fpcm4U0boUPTr" /><figcaption>Photo by <a href="https://unsplash.com/@thoughtcatalog?utm_source=medium&amp;utm_medium=referral">Thought Catalog</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><blockquote>NSOperation在處理任務的方式預設為非同步，若想要同步處理的話也是可以達成，但需要做一些相對的動作。</blockquote><h4>關於同步與非同步處理相關的概念已在 iOS| #28 說明過，在此不再贅述。若想了解也可以參考以下連結：</h4><ul><li><a href="https://medium.com/@tommy5566123/ios-28-gcd-%E7%AD%86%E8%A8%98-7593b4cb3b6c">iOS| #28 | GCD 筆記 part1. Dispatch Queue</a></li><li><a href="https://medium.com/@tommy5566123/ios-29-gcd-%E7%AD%86%E8%A8%98-part2-dispatchgroup-bf47107e9dd5">iOS| #28 | GCD 筆記 part2. DispatchGroup</a></li><li><a href="https://medium.com/@tommy5566123/ios-28-gcd-%E7%AD%86%E8%A8%98-part3-dispatchsemaphore-ff774942ba8c">iOS| #28 | GCD 筆記 part3. DispatchSemaphore</a></li></ul><blockquote>程式範例</blockquote><ol><li><strong>首先建立一個project，實作func operationQueueTest()。</strong></li><li><strong>在viewDidLoad()呼叫此func 。</strong></li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/972/1*XpYvwWyQOrv3jEazpG-tWQ.png" /></figure><p><strong>3. 生成OperationQueue，之後測試方便使用。</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/892/1*obvdAmacJd5etOkz4SeDIw.png" /></figure><blockquote>接下來會用程式範例在func <strong>operationQueueTest</strong>()中 print出一些東西來觀察利用NSOperation執行任務時的狀況</blockquote><ul><li><strong>多個任務（非同步）同時處理，等待全數執行完成時再執行後續程式</strong></li></ul><p>某些時候我們可能要處理多項任務（無限制完成順序），等多項前置任務都完成時，最後再觸發一項任務。</p><p>例如：吃早餐之前，要先添加牛奶、麥片。但順序是沒有差的，吃進肚子裡都一樣。</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/029f843a6f8ef05d6f1dcd95911a2da6/href">https://medium.com/media/029f843a6f8ef05d6f1dcd95911a2da6/href</a></iframe><p>利用BlockOperation生成operation1、operation2，並且在block中寫要執行的任務。</p><pre><strong>let</strong> operation1 = BlockOperation {</pre><pre>  print(&quot;加麥片&quot;)</pre><pre>}</pre><pre><strong>let</strong> operation2 = BlockOperation {</pre><pre>  print(&quot;加牛奶&quot;)</pre><pre>}</pre><p>使用addOperations把任務交給queue執行<br>waitUntilFinished：控制是否要等任務執行完畢再做後續事情。</p><pre>queue.addOperations([operation1,operation2], waitUntilFinished: <strong>true</strong>)</pre><p><em>結果如下：</em></p><p>由於是非同步執行的關係，所以任務會同時開始進行，無法保證哪個任務會先執行完畢。</p><p>但由於參數waitUntilFinished為true，所以可以確定 print(“吃早餐”) 一定會等待operation1、operation2都完成才會被執行。</p><pre><strong>加牛奶</strong></pre><pre><strong>加麥片</strong></pre><pre><strong>吃早餐</strong></pre><ul><li><strong>多個任務（同步）依序處理，等待前項任務完成才可以執行下個任務</strong></li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2d6cb818757d4ad0ee2024a25c34329b/href">https://medium.com/media/2d6cb818757d4ad0ee2024a25c34329b/href</a></iframe><p>使用addDependency將operation2依屬至operation1，operation2將會等operation1執行完成才會被觸發。（operation3邏輯類似，不再贅述）</p><pre>operation2.addDependency(operation1)</pre><pre>operation3.addDependency(operation2)</pre><p><em>結果如下：</em></p><pre><strong>開門</strong></pre><pre><strong>洗手</strong></pre><pre><strong>吃飯</strong></pre><pre><strong>飯後甜點</strong></pre><blockquote>補充：<br>等待任務全數執行完畢再執行print(“飯後甜點”)還有別種寫法</blockquote><p>由於Dependency的特性會使該任務等待dependencies的operation執行完畢後才會觸發自己本身的任務，然而我們可以利用這種特性達成此功能。</p><p>以下我們分成兩種情境來說明：</p><ol><li><strong>多項任務同步執行，待前項任務行完以後再執行後續任務</strong></li></ol><pre><strong>var</strong> queue = OperationQueue()</pre><pre><strong>let</strong> operation1 = BlockOperation { print(&quot;開門&quot;) }</pre><pre><strong>let</strong> operation2 = BlockOperation { print(&quot;洗手&quot;) }</pre><pre><strong>let</strong> operation3 = BlockOperation { print(&quot;吃飯&quot;) }</pre><pre><strong>let</strong> operation4 = BlockOperation { print(&quot;飯後甜點&quot;) }</pre><pre>operation2.addDependency(operation1)</pre><pre>operation3.addDependency(operation2)</pre><pre>operation4.addDependency(operation3)</pre><pre>queue.addOperations([operation1,operation2,operation3,operation4], waitUntilFinished: <strong>true</strong>)</pre><p>此段程式與前面的例子差異在於新增一個operation4，將print(“飯後甜點”)的任務交給他來執行。並且新增addDependency的關聯，這樣當所有任務<strong>「依序」</strong>執行完畢以後才會做最後的任務operation4。</p><p><em>執行結果：</em></p><h4>執行順序一定都會相同</h4><pre><strong>開門</strong></pre><pre><strong>洗手</strong></pre><pre><strong>吃飯</strong></pre><pre><strong>飯後甜點</strong></pre><p><strong>2. 多項任務非同步執行，待所有任務行完以後再執行最後一項任務</strong></p><pre><strong>var</strong> queue = OperationQueue()</pre><pre><strong>let</strong> operation1 = BlockOperation { print(&quot;刷牙&quot;) }</pre><pre><strong>let</strong> operation2 = BlockOperation { print(&quot;洗澡&quot;) }</pre><pre><strong>let</strong> operation3 = BlockOperation { print(&quot;睡覺&quot;) }</pre><pre>operation3.addDependency(operation1)</pre><pre>operation3.addDependency(operation2)</pre><pre>queue.addOperations([operation1,operation2,operation3], waitUntilFinished: <strong>true</strong>)</pre><p>此段程式我們將operation1、operation2做非同步處理，因此這兩個任務的完成順序並不會每次都一樣。然後將以上兩個任務加入至operation3的Dependency關聯中。這樣就可以達成非同步處理operation1、operation2，最後執行operation3的需求。</p><p><em>執行結果：</em></p><h4><strong>「洗澡」</strong>、「<strong>刷牙」</strong>完成順序不一。「<strong>睡覺」</strong>一定會等前兩項任務完成才會執行</h4><pre><strong>洗澡</strong></pre><pre><strong>刷牙</strong></pre><pre><strong>睡覺</strong></pre><pre>// or</pre><pre><strong>刷牙</strong></pre><pre><strong>洗澡</strong></pre><pre><strong>睡覺</strong></pre><blockquote><strong>相較於</strong>Dispatch<strong>Semaphore、DispatchGroup，OperationQueue在cancel的部分可以做的更細膩。假如同時有多個任務都要利用OperationQueue執行：當有一個任務失敗時，其他任務就要全部取消。這樣的需求使用OperationQueue很容易就可以達成。</strong></blockquote><ul><li><strong>執行多個任務，只要有一個任務失敗就跳出</strong></li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9e615bc5e0795e3166cbf44ddcdb7fb1/href">https://medium.com/media/9e615bc5e0795e3166cbf44ddcdb7fb1/href</a></iframe><p><em>執行結果：</em></p><p>以上第31行我們利用for迴圈將operation1加入到operation2、operation3、operation4的Dependency中，等待operation1完成後再以非同步的方式執行operation2、operation3、operation4。</p><p>由於在operation1中第9行有做檢查年齡的動作，依照此例會走到 age &lt; 18的判斷式中。在呼叫cancelAllOperations()以後operation2、operation3、operation4都會被取消，所以都不會被執行。</p><pre><strong>未成年</strong></pre><p>反之若滿18歲則會正常執行：</p><pre><strong>已成年</strong></pre><pre><strong>泡網咖</strong></pre><pre><strong>買菸</strong></pre><pre><strong>買酒</strong></pre><p>在這邊需要注意在operation執行的當下使用cancelAllOperations()並不會將已經執行到一半的任務被取消，如上述例子我們在operation1呼叫queue.cancelAllOperations()時還是會執行print(“未成年”)，並且要使用return跳出，防止後續的程式碼被執行。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UqQ6Y3OkoWNfb6kbrF1SYg.png" /></figure><ul><li>管理非同步可運作的執行緒數量</li></ul><p>以下案例最多只容許兩個任務非同步處理（queue.maxConcurrentOperationCount = 2）</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7a105bc647642746d1a808d6981045e1/href">https://medium.com/media/7a105bc647642746d1a808d6981045e1/href</a></iframe><p>我們利用BreakPoint可以觀察到在queue中最多只會有兩個thread同時做事</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IIF1QvOoTzKf9qhaI8gQtw.png" /></figure><blockquote>結語</blockquote><blockquote>關於NSOperation其實還有更複雜的使用方式，在本文中提到的都只是很單純的案例。日後研究更透徹會再找時間寫文章。</blockquote><p><em>參考資料：</em></p><ul><li><a href="https://developer.apple.com/documentation/foundation/operationqueue">OperationQueue | Apple Developer Documentation</a></li><li><a href="https://www.appcoda.com.tw/ios-concurrency/">iOS 並行程式設計: 初探 NSOperation 和 Dispatch Queues</a></li></ul><p>若內容有誤煩請指教，感謝收看。</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=67c7b12d64bd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[iOS| #28 | GCD 筆記 part3. DispatchSemaphore]]></title>
            <link>https://medium.com/@tommy5566123/ios-28-gcd-%E7%AD%86%E8%A8%98-part3-dispatchsemaphore-ff774942ba8c?source=rss-dcc5ce982008------2</link>
            <guid isPermaLink="false">https://medium.com/p/ff774942ba8c</guid>
            <category><![CDATA[swift-programming]]></category>
            <dc:creator><![CDATA[Tommy]]></dc:creator>
            <pubDate>Mon, 25 Apr 2022 05:37:49 GMT</pubDate>
            <atom:updated>2022-04-25T05:42:20.355Z</atom:updated>
            <content:encoded><![CDATA[<h4>在<a href="https://medium.com/@tommy5566123/ios-29-gcd-%E7%AD%86%E8%A8%98-part2-dispatchgroup-bf47107e9dd5">iOS| #28 part2.</a>提到了DispatchGroup的使用，這次會說明另一個相似的物件，叫做DispatchSemaphore。</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_XpEQLQ5PdgNxW2i" /><figcaption>Photo by <a href="https://unsplash.com/@markusspiske?utm_source=medium&amp;utm_medium=referral">Markus Spiske</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><blockquote>DispatchSemaphore的功能與DispatchGroup相當類似，但Semaphore可以利用參數value控制資源的運用（例如：同時只能執行2個任務）。</blockquote><blockquote>名詞解釋</blockquote><p>在正式講解前有一些DispatchSemaphore的method可能要先熟悉一下</p><ul><li><strong>signal</strong><br>Semaphore計數增加</li><li><strong>wait</strong><br>Semaphore計數減少</li></ul><blockquote>程式範例</blockquote><p><a href="https://developer.apple.com/documentation/dispatch/dispatchsemaphore/1452955-init">官方文件</a>說明主要會有兩種做法：</p><ol><li>預設value為0，當執行任務時會呼叫wait，使其value -1（變成負數）。這時候執行緒會block住，直到呼叫signal，使其value +1（變回零），這時候才會繼續執行後續的任務。</li><li>預設value為任一正整數，目的是為了管理同時可以運作的執行緒數量。</li></ol><h4>以下就讓我們看看範例：</h4><ol><li><strong>首先建立一個project，實作func dispatchSemaphoreTest()。</strong></li><li><strong>在viewDidLoad()呼叫此func 。</strong></li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A4UpLDzfwk-gmzS6YLrO4Q.png" /></figure><p><strong>3. 生成DispatchSemaphore、DispatchQueue之後測試方便使用。</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5-Sib3ODyIdYf-7mbmqRzA.png" /></figure><blockquote>接下來會用程式範例在func <strong>dispatchSemaphoreTest</strong>()中 print出一些東西來觀察利用DispatchSemaphore執行任務時的狀況</blockquote><ul><li><strong>預設value為0<br></strong>任務會按照順序完成，與<a href="https://medium.com/@tommy5566123/ios-29-gcd-%E7%AD%86%E8%A8%98-part2-dispatchgroup-bf47107e9dd5">iOS| #28 part2.</a>提到的DispatchGroup使用wait的結果一樣</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/420faf26e741f51b475114a0dead8d41/href">https://medium.com/media/420faf26e741f51b475114a0dead8d41/href</a></iframe><p><em>結果如下：</em></p><pre><strong>開門</strong></pre><pre><strong>洗手</strong></pre><pre><strong>吃飯</strong></pre><ul><li><strong>預設value為5<br></strong>同時最多只能執行5個任務。依照Semaphore的特性，value為負的話執行緒會被block住，直到value≥0。</li></ul><p>這邊的範例稍微多了幾個步驟：</p><ol><li><strong>宣告屬性count負責記錄現在有幾項任務</strong></li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qvBmRVR6GxwzSN_-TEb5_Q.png" /></figure><p><strong>2. 實作func countValue()</strong><br>當做完五項任務時會print出訊息，並將計數器歸零</p><pre>//控制counter</pre><pre><strong>func</strong> countValue(){</pre><pre>  count += 1</pre><pre><strong>  if</strong> count == 5 {</pre><pre>   print(&quot;已完成五項任務&quot;)</pre><pre>   count = 0</pre><pre>  }</pre><pre>}</pre><p><strong>3. 實作func dispatchSemaphoreTest()範例內容</strong></p><p>補充：在func dispatchSemaphoreTest()中會使用asyncAfter &amp; sleep(1)是為了讓gif結果看起來更明顯，因為任務非常簡單，要避免程式一下子就做完所有事。</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1ae1eb5f7aa60e8957c3ebf7c48e74eb/href">https://medium.com/media/1ae1eb5f7aa60e8957c3ebf7c48e74eb/href</a></iframe><p><em>結果如下：</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gT9EyV5MVS8_hfQ6RZIkcw.gif" /></figure><blockquote>補充：<br>在使用上會有一些要注意的地方，經過測試後將這些情境列在下方</blockquote><ul><li><strong>使用呼叫wait()使value為負數的話，會讓程式碼停在wait()這邊，在此以後的其他任務會暫時不會被執行。</strong></li></ul><p>透過以下的執行結果可以觀察程式碼34行的print(“完成”)並沒有馬上被執行。因為使用Semaphore的緣故等到三秒後執行完signal()使value≥0才會繼續執行。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v5DCgyypd20Y8mkEfRicyg.gif" /></figure><ul><li><strong>若value為負數的話，一直沒有呼叫signal()。執行緒會永遠block住，無法執行任何動作。</strong></li></ul><p><em>系列文章：</em></p><ul><li><a href="https://medium.com/@tommy5566123/ios-28-gcd-%E7%AD%86%E8%A8%98-7593b4cb3b6c">iOS| #28 | GCD 筆記 part1. Dispatch Queue</a></li><li><a href="https://medium.com/@tommy5566123/ios-29-gcd-%E7%AD%86%E8%A8%98-part2-dispatchgroup-bf47107e9dd5">iOS| #28 | GCD 筆記 part2. DispatchGroup</a></li><li><a href="https://medium.com/@tommy5566123/ios-28-gcd-%E7%AD%86%E8%A8%98-part3-dispatchsemaphore-ff774942ba8c">iOS| #28 | GCD 筆記 part3. DispatchSemaphore</a></li></ul><p>參考資料：</p><ul><li><a href="https://developer.apple.com/documentation/dispatch/dispatchsemaphore">DispatchSemaphore | Apple Developer Documentation</a></li><li><a href="https://medium.com/%E7%A8%8B%E5%BC%8F%E6%84%9B%E5%A5%BD%E8%80%85/ios-gcd-dispatchgroup-dispatchsemaphore%E4%BB%8B%E7%B4%B9-ab4182c61dc5">iOS-GCD-DispatchGroup, DispatchSemaphore介紹</a></li></ul><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F6rJN_ECd1XM%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D6rJN_ECd1XM&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F6rJN_ECd1XM%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/1692a035b534c669ec4132ffa4be9b1d/href">https://medium.com/media/1692a035b534c669ec4132ffa4be9b1d/href</a></iframe><p>若內容有誤煩請指教，感謝收看。</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ff774942ba8c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[iOS| #28 | GCD 筆記 part2. DispatchGroup]]></title>
            <link>https://medium.com/@tommy5566123/ios-29-gcd-%E7%AD%86%E8%A8%98-part2-dispatchgroup-bf47107e9dd5?source=rss-dcc5ce982008------2</link>
            <guid isPermaLink="false">https://medium.com/p/bf47107e9dd5</guid>
            <category><![CDATA[swift-programming]]></category>
            <dc:creator><![CDATA[Tommy]]></dc:creator>
            <pubDate>Fri, 22 Apr 2022 06:32:57 GMT</pubDate>
            <atom:updated>2022-04-25T05:41:58.314Z</atom:updated>
            <content:encoded><![CDATA[<h4>在<a href="https://medium.com/@tommy5566123/ios-28-gcd-%E7%AD%86%E8%A8%98-7593b4cb3b6c">iOS| #28</a>提到了DispatchQueue的使用，這次會說明如何使用DispatchGroup搭配DispatchQueue應用。</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*3E1tm8gFFswVsTwR" /><figcaption>Photo by <a href="https://unsplash.com/@mocaandrew?utm_source=medium&amp;utm_medium=referral">Andrew Moca</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><blockquote>名詞解釋</blockquote><p>在正式講解前有一些DispatchGroup的method可能要先熟悉一下</p><ol><li><strong>notify<br></strong>當DispatchGroup中所有task都完成時，可以呼叫此函式做相對應的動作</li><li><strong>wait</strong><br>要等待前面的task完成才開始做下一動，可以呼叫此函式</li><li><strong>enter</strong><br>使用此函式代表DispatchGroup要產生新的block執行任務</li><li><strong>leave</strong><br>使用此函式代表先前生成的block任務已完成</li></ol><blockquote>程式範例</blockquote><ol><li><strong>首先建立一個project，實作func dispatchGroupTest()。</strong></li><li><strong>在viewDidLoad()呼叫此func 。</strong></li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1010/1*SsKXmmQhh6-pffmAACMtKg.png" /></figure><p><strong>3. 生成DispatchGroup、DispatchQueue之後測試方便使用。</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aoZoP0zdoMGfe17M9Ya_jQ.png" /></figure><blockquote><em>接下來會用程式範例在func </em>dispatchGroupTest<em>()中 print出一些東西來觀察利用</em>DispatchGroup<em>執行任務時的狀況</em></blockquote><ul><li><strong>多個任務同時處理，全數執行完成時觸發新的任務</strong></li></ul><h4>某些時候我們可能要處理多項任務（無限制完成順序），等多項前置任務都完成時，最後再觸發一項任務。</h4><p>例如：<strong>吃早餐</strong>之前，要先添加<strong>牛奶、麥片</strong>。但順序是沒有差的，吃進肚子裡都一樣。</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/910d27408cd9463ff056b58952432658/href">https://medium.com/media/910d27408cd9463ff056b58952432658/href</a></iframe><p><em>結果如下：</em></p><p>從以下結果可以看得出來，前兩個任務：<strong>加麥片、加牛奶</strong>是平行處理的，所以重複執行時完成順序可能會不同。</p><p><strong>第一次執行</strong></p><pre><strong>加牛奶</strong></pre><pre><strong>加麥片</strong></pre><pre><strong>吃早餐</strong></pre><p><strong>第二次執行</strong></p><pre><strong>加麥片</strong></pre><pre><strong>加牛奶</strong></pre><pre><strong>吃早餐</strong></pre><ul><li><strong>多個任務按照順序完成，全數執行完成時觸發新的任務</strong></li></ul><h4>某些時候我們可能要處理多項任務，並且我們希望任務按照順序完成。等多項前置任務都完成時，最後再觸發一項任務。</h4><p>例如：現在疫情當道，衛生習慣要稍微注意。所以當我們回到家要先<strong>開門、洗手、吃飯</strong>。我們希望這些任務照順序完成，前面任務都完成以後再執行<strong>吃飯後甜點</strong>的任務。</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8de1c181370f067dccc603b6fa87f51f/href">https://medium.com/media/8de1c181370f067dccc603b6fa87f51f/href</a></iframe><p><em>結果如下：</em></p><p>透過wait()的method，我們可以等待前一項任務完成再做後面的任務。<br>因此這邊print的結果一定都會照著我們期望的順序顯示。</p><pre><strong>開門</strong></pre><pre><strong>洗手</strong></pre><pre><strong>吃飯</strong></pre><pre><strong>吃飯後甜點</strong></pre><blockquote>補充：<br>在使用上會有一些要注意的地方，經過測試後將這些情境列在下方</blockquote><ul><li><strong>使用wait()等待前項任務完成，會讓程式碼停在wait()這邊，在此以後的其他任務會暫時不會被執行。</strong></li></ul><p>新增程式碼，等待五秒後再執行leave()。</p><pre>queue.asyncAfter(deadline: .now() + 5) {</pre><pre> //告訴group已經做完事了</pre><pre> dispatchGroup.leave()</pre><pre>}</pre><p>透過以下的執行結果可以觀察程式碼40行的print(“開完門了”)並沒有馬上被執行。因為使用<strong>wait()</strong>的緣故等到五秒後執行完<strong>leave()</strong>才會繼續往程式碼40行以後執行。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8Ymh5hrAnNC09T_cPT6hjQ.gif" /></figure><ul><li><strong>enter()數量大於leave()</strong></li></ul><ol><li>無使用wait()的情況：<br>notify()的任務永遠不會被執行</li><li>有使用wait()的情況：<br>程式會因為wait()而卡住，後面的事情都不會做</li></ol><ul><li><strong>leave()數量大於enter()</strong></li></ul><p>會閃退</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*swOH-TOdQRQGDtv1JOKr2A.png" /></figure><p><em>系列文章：</em></p><ul><li><a href="https://medium.com/@tommy5566123/ios-28-gcd-%E7%AD%86%E8%A8%98-7593b4cb3b6c">iOS| #28 | GCD 筆記 part1. Dispatch Queue</a></li><li><a href="https://medium.com/@tommy5566123/ios-29-gcd-%E7%AD%86%E8%A8%98-part2-dispatchgroup-bf47107e9dd5">iOS| #28 | GCD 筆記 part2. DispatchGroup</a></li><li><a href="https://medium.com/@tommy5566123/ios-28-gcd-%E7%AD%86%E8%A8%98-part3-dispatchsemaphore-ff774942ba8c">iOS| #28 | GCD 筆記 part3. DispatchSemaphore</a></li></ul><p><em>參考資料：</em></p><p><a href="https://developer.apple.com/documentation/dispatch/dispatchgroup">DispatchGroup | Apple Developer Documentation</a></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F4zsNgBhDs0M%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D4zsNgBhDs0M&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F4zsNgBhDs0M%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/7617620821bfc8f3caf5d2804bf763cb/href">https://medium.com/media/7617620821bfc8f3caf5d2804bf763cb/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F6rJN_ECd1XM%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D6rJN_ECd1XM&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F6rJN_ECd1XM%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/1692a035b534c669ec4132ffa4be9b1d/href">https://medium.com/media/1692a035b534c669ec4132ffa4be9b1d/href</a></iframe><p>若內容有誤煩請指教，感謝收看。</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bf47107e9dd5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[iOS| #28 | GCD 筆記 part1. Dispatch Queue]]></title>
            <link>https://medium.com/@tommy5566123/ios-28-gcd-%E7%AD%86%E8%A8%98-7593b4cb3b6c?source=rss-dcc5ce982008------2</link>
            <guid isPermaLink="false">https://medium.com/p/7593b4cb3b6c</guid>
            <category><![CDATA[swift-programming]]></category>
            <dc:creator><![CDATA[Tommy]]></dc:creator>
            <pubDate>Mon, 18 Apr 2022 16:19:05 GMT</pubDate>
            <atom:updated>2022-04-25T08:09:23.004Z</atom:updated>
            <content:encoded><![CDATA[<h4>在開發程式的過程中，我們不會只有一個任務要執行。任務可以是抓取資料、更新畫面、上傳資料等等。而我們當然會希望不要因為其他的任務而影響到UI介面顯示被卡住。<br>因此Apple提供了GCD（多執行序的功能）讓我們使用。</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*SvwEUBX4dQe84jmg" /><figcaption>Photo by <a href="https://unsplash.com/@melanie_sophie?utm_source=medium&amp;utm_medium=referral">Melanie Pongratz</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><blockquote>名詞解釋</blockquote><ol><li><strong>GCD（Grand Central Dispatch）</strong><br>為多執行序的應用，可以縮短任務達成時間、避免佔用主執行序導致UI畫面被卡住，影響使用者體驗</li><li><strong>Queue</strong><br>稱為佇列，是一種資料結構的型態，有著先進先出的特性。<br>例如：排隊買車票，當前面的人購票完成才換下一個。</li><li><strong>Serial</strong><br> queue的屬性之一，屬性為serial的queue會依序執行任務，並且會等前面的任務執行完成再執行下個任務。</li><li><strong>Concurrent<br></strong>queue的屬性之一，屬性為concurrent的queue會按照順序“開始”執行任務。但在處理多項任務時是同時進行的，因此不會等前面的任務執行完畢再做下一個，每項工作的完成時間是不確定的。</li><li><strong>sync（同步）<br></strong>在queue中要執行的程式碼區塊(block)，使用sync執行的話會依序執行block內的程式，且不會開啟新的執行序。</li><li><strong>async（非同步）<br></strong>在queue中要執行的程式碼區塊(block)，使用async執行的話會依序執行block內的程式，且會開啟新的執行序。</li></ol><blockquote>程式範例</blockquote><ol><li><strong>首先建立一個project，實作func queueTest()。</strong></li><li><strong>在viewDidLoad()呼叫此func 。</strong></li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1022/1*mKL98exf3M0txXJOfYbf7w.png" /></figure><p><strong>3. 生成queue，日後會再來使用。</strong><br>注意：attribute沒給預設會是serial的，若要使用concurrent可以利用參數attribute來設置。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qWJD1dtANC-4g2OtVpbHJg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rlfGj9YyGDadHsVrUEzIVA.png" /></figure><p><strong>4. 在main queue印出一些東西，日後會拿來跟queue比較執行任務的順序。</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WW0ZVUEVRVdqL6bWTsgVYA.png" /></figure><blockquote>接下來會用程式範例在func queueTest()中 print出一些東西搭配BreakPoint來觀察不同的Queue＆block組合執行任務時Thread的狀況</blockquote><ul><li><strong>建立 Serial Queue 與 sync block</strong></li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/121fe545f860f4bdb6028f8795f633b6/href">https://medium.com/media/121fe545f860f4bdb6028f8795f633b6/href</a></iframe><p><em>結果如下：</em></p><p>按照任務順序完成，會等前面的任務執行完成再執行下個任務。</p><pre><strong>first block queue:❤️ 1</strong></pre><pre><strong>first block queue:❤️ 2</strong></pre><pre><strong>first block queue:❤️ 3</strong></pre><pre><strong>first block queue:❤️ 4</strong></pre><pre><strong>first block queue:❤️ 5</strong></pre><pre><strong>first block queue:❤️ 6</strong></pre><pre><strong>first block queue:❤️ 7</strong></pre><pre><strong>first block queue:❤️ 8</strong></pre><pre><strong>first block queue:❤️ 9</strong></pre><pre><strong>first block queue:❤️ 10</strong></pre><pre><strong>first block queue - 2 :❤️ 1</strong></pre><pre><strong>first block queue - 2 :❤️ 2</strong></pre><pre><strong>first block queue - 2 :❤️ 3</strong></pre><pre><strong>first block queue - 2 :❤️ 4</strong></pre><pre><strong>first block queue - 2 :❤️ 5</strong></pre><pre><strong>first block queue - 2 :❤️ 6</strong></pre><pre><strong>first block queue - 2 :❤️ 7</strong></pre><pre><strong>first block queue - 2 :❤️ 8</strong></pre><pre><strong>first block queue - 2 :❤️ 9</strong></pre><pre><strong>first block queue - 2 :❤️ 10</strong></pre><pre><strong>second block queue:❤️ 1</strong></pre><pre><strong>second block queue:❤️ 2</strong></pre><pre><strong>second block queue:❤️ 3</strong></pre><pre><strong>second block queue:❤️ 4</strong></pre><pre><strong>second block queue:❤️ 5</strong></pre><pre><strong>second block queue:❤️ 6</strong></pre><pre><strong>second block queue:❤️ 7</strong></pre><pre><strong>second block queue:❤️ 8</strong></pre><pre><strong>second block queue:❤️ 9</strong></pre><pre><strong>second block queue:❤️ 10</strong></pre><pre><strong>main queue:💙 100</strong></pre><pre><strong>main queue:💙 101</strong></pre><pre><strong>main queue:💙 102</strong></pre><pre><strong>main queue:💙 103</strong></pre><pre><strong>main queue:💙 104</strong></pre><pre><strong>main queue:💙 105</strong></pre><pre><strong>main queue:💙 106</strong></pre><pre><strong>main queue:💙 107</strong></pre><pre><strong>main queue:💙 108</strong></pre><pre><strong>main queue:💙 109</strong></pre><pre><strong>main queue:💙 110</strong></pre><p><em>利用BreakPoint觀察thread的情形：</em></p><p>可以看得出來不會產生新的thread，且使用Serial Queue 搭配 sync block其實就等於在main thread執行任務（如下圖同樣都在thread 1）。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kJmy-ZQzx27Wzh7-Zpc7ig.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IXpYwATE767B5vRTClPS_w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zxqS-OgL65uvAKy3gFwhKA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rTi3wXJq3e9UM2Mg3UVFUQ.png" /></figure><ul><li><strong>建立 Serial Queue 與 async block</strong></li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4faac18764e0507cc0390871688b6a29/href">https://medium.com/media/4faac18764e0507cc0390871688b6a29/href</a></iframe><p><em>結果如下：</em></p><p>按照任務順序完成，會等前面的任務執行完成再執行下個任務。<br>但因為使用async的緣故會產生新的thread，將任務送出去以後，系統會根據thread的qos（quality of service）自動分配資源給優先度較高的任務（此例來看是main thread較高）。</p><pre><strong>main queue:💙 100</strong></pre><pre><strong>first block queue:❤️ 1</strong></pre><pre><strong>main queue:💙 101</strong></pre><pre><strong>first block queue:❤️ 2</strong></pre><pre><strong>first block queue:❤️ 3</strong></pre><pre><strong>first block queue:❤️ 4</strong></pre><pre><strong>first block queue:❤️ 5</strong></pre><pre><strong>first block queue:❤️ 6</strong></pre><pre><strong>first block queue:❤️ 7</strong></pre><pre><strong>first block queue:❤️ 8</strong></pre><pre><strong>first block queue:❤️ 9</strong></pre><pre><strong>first block queue:❤️ 10</strong></pre><pre><strong>main queue:💙 102</strong></pre><pre><strong>main queue:💙 103</strong></pre><pre><strong>first block queue - 2 :❤️ 1</strong></pre><pre><strong>main queue:💙 104</strong></pre><pre><strong>first block queue - 2 :❤️ 2</strong></pre><pre><strong>main queue:💙 105</strong></pre><pre><strong>main queue:💙 106</strong></pre><pre><strong>main queue:💙 107</strong></pre><pre><strong>main queue:💙 108</strong></pre><pre><strong>main queue:💙 109</strong></pre><pre><strong>main queue:💙 110</strong></pre><pre><strong>first block queue - 2 :❤️ 3</strong></pre><pre><strong>first block queue - 2 :❤️ 4</strong></pre><pre><strong>first block queue - 2 :❤️ 5</strong></pre><pre><strong>first block queue - 2 :❤️ 6</strong></pre><pre><strong>first block queue - 2 :❤️ 7</strong></pre><pre><strong>first block queue - 2 :❤️ 8</strong></pre><pre><strong>first block queue - 2 :❤️ 9</strong></pre><pre><strong>first block queue - 2 :❤️ 10</strong></pre><pre><strong>second block queue:❤️ 1</strong></pre><pre><strong>second block queue:❤️ 2</strong></pre><pre><strong>second block queue:❤️ 3</strong></pre><pre><strong>second block queue:❤️ 4</strong></pre><pre><strong>second block queue:❤️ 5</strong></pre><pre><strong>second block queue:❤️ 6</strong></pre><pre><strong>second block queue:❤️ 7</strong></pre><pre><strong>second block queue:❤️ 8</strong></pre><pre><strong>second block queue:❤️ 9</strong></pre><pre><strong>second block queue:❤️ 10</strong></pre><p><em>利用BreakPoint觀察thread的情形：</em></p><p>可以看得出來會產生新的thread（但只有一個）如下圖中的Thread7，且與main thread平行處理任務。但系統會自動分配比較多資源給main thread使其優先完成。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8JCuyjg4y_-S1vGJHDSnhA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZmnwRxhpoDTFsYtxVrSdAQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*otgz6eulYeToRKdLwfDvyQ.png" /></figure><ul><li><strong>建立 Concurrent Queue 與 sync block</strong></li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/319c150df426e400a2a9b2865d93fb51/href">https://medium.com/media/319c150df426e400a2a9b2865d93fb51/href</a></iframe><p><em>結果如下：</em></p><p>與Serial Queue 搭配sync block的結果相同。<br>按照任務順序完成，會等前面的任務執行完成再執行下個任務。</p><pre><strong>first block queue:❤️ 1</strong></pre><pre><strong>first block queue:❤️ 2</strong></pre><pre><strong>first block queue:❤️ 3</strong></pre><pre><strong>first block queue:❤️ 4</strong></pre><pre><strong>first block queue:❤️ 5</strong></pre><pre><strong>first block queue:❤️ 6</strong></pre><pre><strong>first block queue:❤️ 7</strong></pre><pre><strong>first block queue:❤️ 8</strong></pre><pre><strong>first block queue:❤️ 9</strong></pre><pre><strong>first block queue:❤️ 10</strong></pre><pre><strong>first block queue - 2 :❤️ 1</strong></pre><pre><strong>first block queue - 2 :❤️ 2</strong></pre><pre><strong>first block queue - 2 :❤️ 3</strong></pre><pre><strong>first block queue - 2 :❤️ 4</strong></pre><pre><strong>first block queue - 2 :❤️ 5</strong></pre><pre><strong>first block queue - 2 :❤️ 6</strong></pre><pre><strong>first block queue - 2 :❤️ 7</strong></pre><pre><strong>first block queue - 2 :❤️ 8</strong></pre><pre><strong>first block queue - 2 :❤️ 9</strong></pre><pre><strong>first block queue - 2 :❤️ 10</strong></pre><pre><strong>second block queue:❤️ 1</strong></pre><pre><strong>second block queue:❤️ 2</strong></pre><pre><strong>second block queue:❤️ 3</strong></pre><pre><strong>second block queue:❤️ 4</strong></pre><pre><strong>second block queue:❤️ 5</strong></pre><pre><strong>second block queue:❤️ 6</strong></pre><pre><strong>second block queue:❤️ 7</strong></pre><pre><strong>second block queue:❤️ 8</strong></pre><pre><strong>second block queue:❤️ 9</strong></pre><pre><strong>second block queue:❤️ 10</strong></pre><pre><strong>main queue:💙 100</strong></pre><pre><strong>main queue:💙 101</strong></pre><pre><strong>main queue:💙 102</strong></pre><pre><strong>main queue:💙 103</strong></pre><pre><strong>main queue:💙 104</strong></pre><pre><strong>main queue:💙 105</strong></pre><pre><strong>main queue:💙 106</strong></pre><pre><strong>main queue:💙 107</strong></pre><pre><strong>main queue:💙 108</strong></pre><pre><strong>main queue:💙 109</strong></pre><pre><strong>main queue:💙 110</strong></pre><p><em>利用BreakPoint觀察thread的情形：</em></p><p>可以看得出來不會產生新的thread，且使用Concurrent Queue 搭配 sync block其實就等於在main thread執行任務（如下圖同樣都在thread 1）。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Pssc4bqdXrpAUMgf4eyDYQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KYOK0Vdk8hHgdt-PdVrJHw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VkiDJt7SvpJsWxE-LB6oQg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a-MpnuZxwBbEewja2yuvsg.png" /></figure><ul><li><strong>建立 Concurrent Queue 與 async block（執行效率最高的做法）</strong></li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3f0643a536c46c7910c6d9cdc0fef1d5/href">https://medium.com/media/3f0643a536c46c7910c6d9cdc0fef1d5/href</a></iframe><p><em>結果如下：</em></p><p>按照任務順序 <strong>“開始”</strong> 執行，且不會等前面的任務執行完成再執行下個任務，所有任務是 <strong>“同時”</strong> 進行的。<br>但因為使用async的緣故會產生新的thread，將任務送出去以後，系統會根據thread的qos（quality of service）自動分配資源給優先度較高的任務（此例來看是main thread較高）。</p><pre><strong>main queue:💙 100</strong></pre><pre><strong>main queue:💙 101</strong></pre><pre><strong>main queue:💙 102</strong></pre><pre><strong>main queue:💙 103</strong></pre><pre><strong>second block queue:❤️ 1</strong></pre><pre><strong>second block queue:❤️ 2</strong></pre><pre><strong>first block queue:❤️ 1</strong></pre><pre><strong>main queue:💙 104</strong></pre><pre><strong>second block queue:❤️ 3</strong></pre><pre><strong>second block queue:❤️ 4</strong></pre><pre><strong>second block queue:❤️ 5</strong></pre><pre><strong>second block queue:❤️ 6</strong></pre><pre><strong>first block queue:❤️ 2</strong></pre><pre><strong>first block queue:❤️ 3</strong></pre><pre><strong>second block queue:❤️ 7</strong></pre><pre><strong>first block queue:❤️ 4</strong></pre><pre><strong>main queue:💙 105</strong></pre><pre><strong>second block queue:❤️ 8</strong></pre><pre><strong>second block queue:❤️ 9</strong></pre><pre><strong>second block queue:❤️ 10</strong></pre><pre><strong>first block queue:❤️ 5</strong></pre><pre><strong>main queue:💙 106</strong></pre><pre><strong>first block queue:❤️ 6</strong></pre><pre><strong>main queue:💙 107</strong></pre><pre><strong>main queue:💙 108</strong></pre><pre><strong>first block queue:❤️ 7</strong></pre><pre><strong>main queue:💙 109</strong></pre><pre><strong>main queue:💙 110</strong></pre><pre><strong>first block queue:❤️ 8</strong></pre><pre><strong>first block queue:❤️ 9</strong></pre><pre><strong>first block queue:❤️ 10</strong></pre><pre><strong>first block queue - 2 :❤️ 1</strong></pre><pre><strong>first block queue - 2 :❤️ 2</strong></pre><pre><strong>first block queue - 2 :❤️ 3</strong></pre><pre><strong>first block queue - 2 :❤️ 4</strong></pre><pre><strong>first block queue - 2 :❤️ 5</strong></pre><pre><strong>first block queue - 2 :❤️ 6</strong></pre><pre><strong>first block queue - 2 :❤️ 7</strong></pre><pre><strong>first block queue - 2 :❤️ 8</strong></pre><pre><strong>first block queue - 2 :❤️ 9</strong></pre><pre><strong>first block queue - 2 :❤️ 10</strong></pre><blockquote>補充：由於是平行處理（非同步）的緣故，所以每次執行的結果print出來的順序會有些許不同。</blockquote><p><em>第二次執行結果如下：</em></p><pre><strong>second block queue:❤️ 1</strong></pre><pre><strong>first block queue:❤️ 1</strong></pre><pre><strong>main queue:💙 100</strong></pre><pre><strong>main queue:💙 101</strong></pre><pre><strong>second block queue:❤️ 2</strong></pre><pre><strong>main queue:💙 102</strong></pre><pre><strong>second block queue:❤️ 3</strong></pre><pre><strong>first block queue:❤️ 2</strong></pre><pre><strong>second block queue:❤️ 4</strong></pre><pre><strong>main queue:💙 103</strong></pre><pre><strong>second block queue:❤️ 5</strong></pre><pre><strong>main queue:💙 104</strong></pre><pre><strong>main queue:💙 105</strong></pre><pre><strong>first block queue:❤️ 3</strong></pre><pre><strong>main queue:💙 106</strong></pre><pre><strong>second block queue:❤️ 6</strong></pre><pre><strong>second block queue:❤️ 7</strong></pre><pre><strong>second block queue:❤️ 8</strong></pre><pre><strong>second block queue:❤️ 9</strong></pre><pre><strong>first block queue:❤️ 4</strong></pre><pre><strong>second block queue:❤️ 10</strong></pre><pre><strong>main queue:💙 107</strong></pre><pre><strong>main queue:💙 108</strong></pre><pre><strong>main queue:💙 109</strong></pre><pre><strong>main queue:💙 110</strong></pre><pre><strong>first block queue:❤️ 5</strong></pre><pre><strong>first block queue:❤️ 6</strong></pre><pre><strong>first block queue:❤️ 7</strong></pre><pre><strong>first block queue:❤️ 8</strong></pre><pre><strong>first block queue:❤️ 9</strong></pre><pre><strong>first block queue:❤️ 10</strong></pre><pre><strong>first block queue - 2 :❤️ 1</strong></pre><pre><strong>first block queue - 2 :❤️ 2</strong></pre><pre><strong>first block queue - 2 :❤️ 3</strong></pre><pre><strong>first block queue - 2 :❤️ 4</strong></pre><pre><strong>first block queue - 2 :❤️ 5</strong></pre><pre><strong>first block queue - 2 :❤️ 6</strong></pre><pre><strong>first block queue - 2 :❤️ 7</strong></pre><pre><strong>first block queue - 2 :❤️ 8</strong></pre><pre><strong>first block queue - 2 :❤️ 9</strong></pre><pre><strong>first block queue - 2 :❤️ 10</strong></pre><p><em>利用BreakPoint觀察thread的情形：</em></p><p>可以看得出來會產生新的thread（且會有多個）如下圖中的Thread4、Thread8，且與main thread平行處理任務。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r2rfNBYHDVIAQXnG3ekB5g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DsMA134H3nxPvacQe8jnbA.png" /></figure><blockquote>補充：在巢狀的async block中的任務不一定會被分配到同一個thread中。</blockquote><p>被分配到同個Thread中（Thread2）</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Tjg9nJDJE_v8qJJnuq95SQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Vrg6CnGcD2rli_IfLpXPMQ.png" /></figure><p>被分配到不同個Thread中（Thread7、Thread2）</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3q-LT0cJkBCLDP5ZpmUXPA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QcqwXx20MjyPiVs2scuOow.png" /></figure><p><em>系列文章：</em></p><ul><li><a href="https://medium.com/@tommy5566123/ios-28-gcd-%E7%AD%86%E8%A8%98-7593b4cb3b6c">iOS| #28 | GCD 筆記 part1. Dispatch Queue</a></li><li><a href="https://medium.com/@tommy5566123/ios-29-gcd-%E7%AD%86%E8%A8%98-part2-dispatchgroup-bf47107e9dd5">iOS| #28 | GCD 筆記 part2. DispatchGroup</a></li><li><a href="https://medium.com/@tommy5566123/ios-28-gcd-%E7%AD%86%E8%A8%98-part3-dispatchsemaphore-ff774942ba8c">iOS| #28 | GCD 筆記 part3. DispatchSemaphore</a></li></ul><p><em>參考資料：</em></p><ul><li><a href="https://franksios.medium.com/ios-gcd%E5%A4%9A%E5%9F%B7%E8%A1%8C%E7%B7%92%E7%9A%84%E8%AA%AA%E6%98%8E%E8%88%87%E6%87%89%E7%94%A8-c69a68d01da1">GCD 多執行緒的說明與應用</a></li><li><a href="https://www.appcoda.com.tw/grand-central-dispatch/">Swift 3學習指南：重新認識GCD應用</a></li></ul><p>若內容有誤煩請指教，感謝收看。</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7593b4cb3b6c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[iOS| #27 | Retain Cycle 筆記]]></title>
            <link>https://medium.com/@tommy5566123/ios-27-retain-cycle-%E7%AD%86%E8%A8%98-8c69dfe37dcc?source=rss-dcc5ce982008------2</link>
            <guid isPermaLink="false">https://medium.com/p/8c69dfe37dcc</guid>
            <category><![CDATA[swift-programming]]></category>
            <dc:creator><![CDATA[Tommy]]></dc:creator>
            <pubDate>Mon, 21 Mar 2022 17:21:26 GMT</pubDate>
            <atom:updated>2022-03-21T17:21:56.945Z</atom:updated>
            <content:encoded><![CDATA[<h4>在開發專案的過程中，會大量的運用到Class，在生成物件時就會在裝置中佔據記憶體。在某些時候我們清除Class時記憶體空間卻沒有free出來，那很有可能是因為Retain Cycle的緣故，久而久之超過記憶體上限以後App就會閃退。</h4><blockquote>名詞解釋</blockquote><ol><li><strong>ARC( Automatic Reference Counting )</strong><br>為Xcode的功能，當reference產生/斷開時會自動在背後將計數器+1/-1</li><li><strong>Strong Reference </strong><br>屬性在建立時若沒有指定為weak或是unowned，預設為Strong。Reference 產生時 count會增加。</li><li><strong>Weak Reference </strong><br>屬性在建立時若指定為weak，Reference 產生時 count不會增加。</li><li><strong>Unowned<br></strong>同Weak，但是要確保該屬性在生成以後直到他死掉為止不會再變成nil。</li></ol><blockquote>案例實作</blockquote><ol><li>新增一個UIButton，點擊該Button會push到背景為紅色的頁面。</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/324/1*I2cQ8ALuHqQh4meoQC8MBg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_sMUCDfZXcccMCfNmfFAQQ.png" /></figure><p>2. 實作Class RedViewController，並且在viewDidLoad中把背景顏色改為紅色（測試時比較好分辨）</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*IoATuogdBs38X1i5A5J-3g.png" /></figure><p>3. 在Class RedViewController中實作deinit，在該物件死掉時會觸發此程式</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1018/1*49HTCJEwQNZnbufWECXSDQ.png" /></figure><p>現在我們來執行程式。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/571/1*be1PU9regLK6KvDIrTxRNg.gif" /></figure><p>可以藉由以上影片看到在回到上一頁時，RedViewController死亡，deinit被觸發印出RedViewController deinit。</p><h4>現在我們要來製造一個Retain Cycle。</h4><p>實作Class Service</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jv1Hu50HdFXuUnWmW6zddg.png" /></figure><p>在RedViewController宣告屬性service</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_l7BqPyZzvsYz26o1CizGQ.png" /></figure><p>在RedViewController的viewDidLoad中指派屬性service的redViewController為self</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/976/1*oTeeidj5UqwNi8vYfIgDqA.png" /></figure><p>Reference 關係如下：<br>在這邊會產生Retain Cycle的情形</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AANmoKpGgOxldZOHwjTlGQ.png" /></figure><p>再次執行程式。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/428/1*Mk4Op_IpqZpU5RFqP0noFQ.gif" /></figure><p>可以看到由於Retain Cycle的緣故，RedViewController的deinit沒有被觸發，代表還存在著Reference，該物件沒有真的死亡。</p><h4>透過Debug Memory Graph來找出沒有被殺死的物件</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/616/1*24aInBvHLhh3wMjmYA6Zyw.png" /></figure><p>可以看到透過上面在simulator的操作，回到上一頁以後，RedViewController與Service就應該要死掉了，但是在這邊他們還活著。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/578/1*bMzcYfaMxSViZ-kE-SBCPA.png" /></figure><h4>解決辦法</h4><p>將Service的屬性redViewController設為weak（或是unowned）</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vmHnHu_lNHcmEl1FSZeHug.png" /></figure><p>執行程式，現在可以看到RedViewController的deinit正常執行，代表回到上一頁RedViewController就死亡，Retain Cycle被打破。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/428/1*pdbqB2tACDB1OKIwTpVHUA.gif" /></figure><p>物件已死亡，在Memory Graph Hierarchy找不到物件RedViewController與Service</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I1engFICBs5K4npfyyTZ3g.png" /></figure><p><em>參考資料：</em></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Fsp8qEMY9X6Q%3Fstart%3D629%26feature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3Dsp8qEMY9X6Q&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2Fsp8qEMY9X6Q%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/7d9417c853e2153bef258b910412db09/href">https://medium.com/media/7d9417c853e2153bef258b910412db09/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Fb2AgibUg47k%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3Db2AgibUg47k&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2Fb2AgibUg47k%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/80f89fc7327c7216b13ff6765947d55d/href">https://medium.com/media/80f89fc7327c7216b13ff6765947d55d/href</a></iframe><p>若內容有誤煩請指教，感謝收看。</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8c69dfe37dcc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[iOS| #26 | 使用TableView與Core Data實作ToDo App — 新增功能]]></title>
            <link>https://medium.com/peter-pan-swift-ios-class/ios-26-%E4%BD%BF%E7%94%A8tableview%E8%88%87core-data%E5%AF%A6%E4%BD%9Ctodo-app-%E6%96%B0%E5%A2%9E%E5%8A%9F%E8%83%BD-7c2a5e5934d?source=rss-dcc5ce982008------2</link>
            <guid isPermaLink="false">https://medium.com/p/7c2a5e5934d</guid>
            <category><![CDATA[swift-programming]]></category>
            <dc:creator><![CDATA[Tommy]]></dc:creator>
            <pubDate>Thu, 17 Mar 2022 09:48:37 GMT</pubDate>
            <atom:updated>2022-03-18T11:37:42.404Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8jAeS47Iu0EQfiTLhPobJg.png" /></figure><h3>iOS| #26 | 使用TableView與Core Data實作ToDo App — 新增功能</h3><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/ios-23-%E4%BD%BF%E7%94%A8tableview%E8%88%87core-data%E5%AF%A6%E4%BD%9Ctodo-app-729a7b549bca?source=your_stories_page----------------------------------------">iOS| #23 | 使用TableView與Core Data實作ToDo App</a>，這一次新增了兩項功能，以下就讓我們娓娓道來。</p><h4>原先是實作func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)，透過點擊tableViewCell來打勾。但因為沒有處理到button的點擊event，所以點擊button時會沒有反應。</h4><h4>這一次的更新我們會把完成事項的功能做在UIButton上面，點擊tableViewCell則會進入detail頁面（僅供讀取無法編輯）。</h4><blockquote>功能解說＆程式解說</blockquote><ul><li><strong>點擊Check Button可以完成事項</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/1*sVP4GCPtoyAATq9VO6ST2w.gif" /></figure><p><strong>在override func tableView(_ tableView: , cellForRowAt indexPath: ) -&gt; UITableViewCell根據indexPath.ro給予toDoButton.tag編號作為判斷第幾筆資料</strong></p><pre>cell.toDoButton.tag = indexPath.row</pre><p><strong>新增toDoButton.tag的處理事項</strong></p><pre>cell.toDoButton.addTarget(<strong>self</strong>, action: <strong>#selector</strong>(selectTodoButton), for: .touchUpInside)</pre><p><strong>實作func selectTodoButton(sender: )，從程式override func tableView(_ tableView: , cellForRowAt indexPath: ) -&gt; UITableViewCell複製過來修改。其餘詳細解說可以參考</strong><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/ios-23-%E4%BD%BF%E7%94%A8tableview%E8%88%87core-data%E5%AF%A6%E4%BD%9Ctodo-app-729a7b549bca?source=your_stories_page----------------------------------------"><strong>iOS| #23 | 使用TableView與Core Data實作ToDo App</strong></a><strong>。</strong></p><p><strong>主要差異點在於原本是使用indexPath.row取得資料，現在改為使用sender.tag取得todoData。</strong></p><pre><strong>@objc</strong> <strong>func</strong> selectTodoButton(sender: UIButton){</pre><pre><strong>  let</strong> todoData = todoDataList![sender.tag]</pre><pre>  todoData.done.toggle()</pre><pre><strong>  do</strong> {</pre><pre><strong>    try</strong> ListCoreData.shared.updateData(todoData: todoData)</pre><pre>  } <strong>catch</strong> <strong>let</strong> error {</pre><pre>    showAlert(message: error.localizedDescription)</pre><pre><strong>  return</strong></pre><pre>}</pre><pre>  tableView.reloadData()</pre><pre>}</pre><ul><li><strong>新增讀取Detail頁面功能</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/1*Kj_WEjNYjRho5g6mdozP8Q.gif" /></figure><p><strong>為了控制點擊cell讀取Detail不能修改，所以在enum DataStatus新增選項read</strong></p><pre><strong>enum</strong> DataStatus {</pre><pre><strong>  case</strong> insert , update , read</pre><pre>}</pre><p><strong>在ListTableViewController新增屬性status，用來控制跳到Detail頁面的狀態。（預設為新增）</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GN86DFWaVomtqOkFIkskxQ.png" /></figure><p><strong>在Edit的按鈕控制屬性status為update</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mxdzb1JMowO5zK5y6Llkqw.png" /></figure><p><strong>在點擊cell時控制屬性status為read</strong></p><pre>status = .read</pre><p><strong>取得當筆todoData</strong></p><pre><strong>let</strong> todoData = todoDataList![indexPath.row]</pre><p><strong>呼叫performSegue去下一頁</strong></p><pre><strong>self</strong>.performSegue(withIdentifier: &quot;clickSwipeEditToEditController&quot;, sender: todoData)</pre><p><strong>status原本是寫死update，由於現在read與update都會call同一個@IBSegueAction，所以直接將屬性status傳到下一頁</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vUaSa8sHm7WIYekXfb2jDA.png" /></figure><p><em>系列文章：</em></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%E6%95%99%E5%AE%A4/ios-23-%E4%BD%BF%E7%94%A8tableview%E8%88%87core-data%E5%AF%A6%E4%BD%9Ctodo-app-729a7b549bca">iOS| #23 | 使用TableView與Core Data實作ToDo App</a></li><li><a href="https://medium.com/@tommy5566123/ios-26-%E4%BD%BF%E7%94%A8tableview%E8%88%87core-data%E5%AF%A6%E4%BD%9Ctodo-app-%E6%96%B0%E5%A2%9E%E5%8A%9F%E8%83%BD-7c2a5e5934d">iOS| #26 | 使用TableView與Core Data實作ToDo App — 新增功能</a></li></ul><p><em>GitHub：</em></p><p><a href="https://github.com/tommy6457/ToDoApp">GitHub - tommy6457/ToDoApp</a></p><p>若內容有誤煩請指教，感謝收看。</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7c2a5e5934d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/peter-pan-swift-ios-class/ios-26-%E4%BD%BF%E7%94%A8tableview%E8%88%87core-data%E5%AF%A6%E4%BD%9Ctodo-app-%E6%96%B0%E5%A2%9E%E5%8A%9F%E8%83%BD-7c2a5e5934d">iOS| #26 | 使用TableView與Core Data實作ToDo App — 新增功能</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[iOS| #25 | 約翰紅茶訂餐App 2.0–Part.3 送出訂單與修改訂單]]></title>
            <link>https://medium.com/peter-pan-swift-ios-class/ios-25-%E7%B4%84%E7%BF%B0%E7%B4%85%E8%8C%B6%E8%A8%82%E9%A4%90app-2-0-part-3-%E9%80%81%E5%87%BA%E8%A8%82%E5%96%AE%E8%88%87%E4%BF%AE%E6%94%B9%E8%A8%82%E5%96%AE-65314e315cc4?source=rss-dcc5ce982008------2</link>
            <guid isPermaLink="false">https://medium.com/p/65314e315cc4</guid>
            <category><![CDATA[swift-programming]]></category>
            <dc:creator><![CDATA[Tommy]]></dc:creator>
            <pubDate>Wed, 16 Mar 2022 07:36:53 GMT</pubDate>
            <atom:updated>2022-03-17T04:03:13.056Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*szDRCaW7Th7W4DFKXSIgtw.png" /></figure><p>不久前已經實作過訂飲料App初版，那麼這次要利用目前所學的技能將其升級為2.0，並且加上數個功能使其成為一個更完整的產品。</p><h4>繼上篇講解到購物車的功能，本篇文章主要會說明從購物車頁面送出訂單與在訂單頁面修改訂單的UI畫面與功能實現。</h4><blockquote>由於此系列文篇幅會較長，會拆分成多篇文章紀錄實作的過程與功能講解</blockquote><blockquote>技術應用</blockquote><ul><li>Programming UIKit</li><li>AutoLayout</li><li>TableView</li><li>Airtable REST API — CRUD</li></ul><blockquote>UI畫面</blockquote><ul><li>Cart Page</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/910/1*i6xvozBn2MkQnhSjok6kcQ.png" /></figure><ul><li>Order Page</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Px-1wmKaoxSx4m--GiW-cQ.png" /></figure><blockquote>功能解說＆程式解說</blockquote><ul><li><strong>Alert 搭配 DatePicker與TextField<br>在購物車頁面點擊Send會跳出Alert讓使用者選擇取餐時間</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/518/1*07n3Tzia5tdsgyTuoEQfIQ.png" /></figure><p><strong>宣告屬性alertController</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bFudPZqGZls5L1J7lsxGDg.png" /></figure><p><strong>在viewDidLoad設定呼叫method setAlertController，初始化alertController的action與textField</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3n98xCTnuBit9Nq1PM-8IQ.png" /></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7274e7135c38895480ee95a35d30db9f/href">https://medium.com/media/7274e7135c38895480ee95a35d30db9f/href</a></iframe><p>生出UIDatePicker</p><pre><strong>let</strong> datePicker = UIDatePicker()</pre><p>設定樣式</p><pre>datePicker.preferredDatePickerStyle = .wheels</pre><p>使用addTarget新增事件處理的程式，在valueChanged時會自動呼叫method datePickerValueChanged</p><pre>datePicker.addTarget(<strong>self</strong>, action: <strong>#selector</strong>(datePickerValueChanged), for: .valueChanged)</pre><h4>以下說明datePickerValueChanged程式：</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/53de1cde386ef109077f982b104dbb8e/href">https://medium.com/media/53de1cde386ef109077f982b104dbb8e/href</a></iframe><p>取得alert的相關屬性textField與action “ OK ”（按照規格會有兩個action，但addAction這邊是由自己控制，且確定 “ OK ”一定會在第一個，所以使用first取得）</p><pre><strong>if</strong> <strong>let</strong> textField = alertController.textFields?[0] ,</pre><pre><strong>   let</strong> action = alertController.actions.first{ </pre><pre><strong>   取得屬性後要做的事</strong></pre><pre>}</pre><p>同步datePicker的時間至textField.text上</p><pre>textField.text = NetWorkController.shared.getOrderHeaderDateTime(date: sender.date)</pre><p>此時間文字格式統一由NetWorkController的method getOrderHeaderDateTime處理</p><pre>//格式化為 OrderHeader-date 的字串</pre><pre><strong>func</strong> getOrderHeaderDateTime(date: Date) -&gt; String {</pre><pre><strong>  let</strong> formatter = DateFormatter()</pre><pre>  formatter.dateFormat = &quot;(yyyy-MM-dd,HH:mm)&quot;</pre><pre><strong>  return</strong> formatter.string(from: date)</pre><pre>}</pre><p>時間只能選擇未來一小時的，若選擇小於一小時的時間則無法點擊action “ OK ”</p><pre>//只能點未來一小時的</pre><pre><strong>if</strong> sender.date &gt; Date().addingTimeInterval(60 * 60){</pre><pre>  action.isEnabled = <strong>true</strong></pre><pre>}<strong>else</strong>{</pre><pre>  action.isEnabled = <strong>false</strong></pre><pre>}</pre><p>效果如下：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/296/1*OM1182IIt3CV2LhvYDrlPg.gif" /></figure><h4>接下來回到setAlertController程式：</h4><p>在alertController中加入textField，在closure中寫程式設定textField的屬性</p><pre>//alertController加TextField</pre><pre>alertController.addTextField { textField <strong>in</strong></pre><pre>  textField.inputView = datePicker</pre><pre>  textField.addTarget(<strong>self</strong>, action: <strong>#selector</strong>(<strong>self</strong>.textfieldEditingChanged), for: .editingChanged)</pre><pre>}</pre><p>將inputView設為剛剛生成的datePicker讓使用者可以自由選擇時間</p><pre>textField.inputView = datePicker</pre><p>使用addTarget新增事件處理的程式，在editingChanged時會自動呼叫method textfieldEditingChanged</p><pre>textField.addTarget(<strong>self</strong>, action: <strong>#selector</strong>(<strong>self</strong>.textfieldEditingChanged), for: .editingChanged)</pre><h4>以下說明textfieldEditingChanged程式：</h4><p>我們只希望使用者使用datePicker修改時間，為了防止使用者在textField自己輸入文字，於是在這邊固定使用alertController的inputView(datePicker)屬性date作為textField的值</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1c298bc5678d3e1f38da596167a0bf3f/href">https://medium.com/media/1c298bc5678d3e1f38da596167a0bf3f/href</a></iframe><h4>接下來回到setAlertController程式：</h4><p>生成UIAlertAction，當點擊action“OK”會送出訂單。（saveDataToAirTable()會在後面<strong>送出訂單</strong>部分說明）</p><pre><strong>let</strong> action_Ok = UIAlertAction(title: &quot;OK&quot;, style: .default) { action <strong>in</strong></pre><pre>//keep取貨時間</pre><pre>g_headerInfo.date = NetWorkController.shared.getOrderHeaderDateTime(date: datePicker.date)</pre><pre>//儲存資料到AirTable</pre><pre><strong>self</strong>.saveDataToAirTable()</pre><pre>}</pre><p>生成UIAlertAction，當點擊action“Cancel”會離開alert，返回購物車頁面。</p><pre><strong>let</strong> action_Cancel = UIAlertAction(title: &quot;Cancel&quot;, style: .cancel, handler: <strong>nil</strong>)</pre><p>新增action至alert</p><pre>alertController.addAction(action_Ok)</pre><pre>alertController.addAction(action_Cancel)</pre><p>固定color</p><pre>alertController.view.tintColor = .systemBlue</pre><ul><li><strong>送出訂單<br>在購物車頁面點選Alert的action button“OK”時會呼叫method saveDataToAirTable()送出訂單</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/540/1*CyHF7JDLGp7dKQqT72VFaw.png" /></figure><p><strong>以下會說明saveDataToAirTable()內程式</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/69181b4b35607d0e2e4c07e4dd698b8f/href">https://medium.com/media/69181b4b35607d0e2e4c07e4dd698b8f/href</a></iframe><p>先初始化orderHeader</p><pre>orderHeader = OrderHeader(records: [OrderHeader.Records]())</pre><p>組訂單編號，在這邊先產生日期。（規格為：年月日＋六碼流水號。）</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/944/1*p7kKxEgTJbND0RYCaMeFpQ.png" /></figure><pre><strong>var</strong> orderNumber = NetWorkController.shared.getOrderHeaderDate(date: Date())</pre><p>用fetchOrderHeader下where條件從airtable — OrderHeader取得今天已產生的編號</p><pre>NetWorkController.shared.fetchOrderHeader(urlString: NetWorkController.getOrderHeaderURL, where: (field: &quot;orderNumber&quot;, value: orderNumber)) { result <strong>in</strong></pre><pre><strong>switch</strong> result{</pre><pre><strong>  case</strong>.failure(<strong>let</strong> error):</pre><pre>    <strong>組錯誤訊息，並showAlert</strong></pre><pre><strong>    return</strong></pre><pre><strong>  case</strong>.success(<strong>var</strong> result):</pre><pre>    <strong>排序已抓到的資料（by訂單號碼倒序），並且組出流水號</strong></pre><pre>  }</pre><pre>}</pre><p>組錯誤訊息，並showAlert</p><pre><strong>var</strong> errorMessage = &quot;&quot;</pre><pre><strong>switch</strong> error{</pre><pre><strong>  case</strong> .invalidData:</pre><pre>    errorMessage = &quot;invalidData&quot;</pre><pre><strong>  case</strong> .invalidJsonFormat:</pre><pre>    errorMessage = &quot;invalidJsonFormat&quot;</pre><pre><strong>  case</strong> .invalidResponse:</pre><pre>    errorMessage = &quot;invalidResponse&quot;</pre><pre><strong>  case</strong> .invalidurl:</pre><pre>    errorMessage = &quot;invalidurl&quot;</pre><pre><strong>  case</strong> .requestFailed:</pre><pre>    errorMessage = &quot;requestFailed&quot;</pre><pre>}</pre><pre>DispatchQueue.main.async {</pre><pre>  NetWorkController.shared.showAlert(title: &quot;警告&quot;, message: &quot;訂單建立失敗&quot; + errorMessage) { alert <strong>in</strong></pre><pre><strong>    self</strong>.present(alert, animated: <strong>true</strong>)</pre><pre>  }</pre><pre>}</pre><p>排序已抓到的資料（by訂單號碼倒序），並且組出流水號</p><pre>//倒序</pre><pre>result.records.sort { records1, records2 <strong>in</strong></pre><pre><strong>  return</strong> records2.fields.orderNumber &lt; records1.fields.orderNumber</pre><pre>}</pre><pre>//判斷result是否為空陣列</pre><pre><strong>if</strong> !result.records.isEmpty{</pre><pre><strong>  let</strong> num = result.records.first!.fields.orderNumber</pre><pre><strong>  let</strong> startIndex = num.index(num.startIndex, offsetBy: 8)</pre><pre>//endIndex是最後一個字的下一個</pre><pre><strong>  let</strong> string = num[startIndex..&lt;num.endIndex]</pre><pre><strong>  var</strong> number = Int(string)!</pre><pre>//號碼+1</pre><pre>  number += 1</pre><pre>//轉文字合併字串</pre><pre>orderNumber += NetWorkController.shared.getFrontZero(count: 6, value: number)</pre><pre>}<strong>else</strong>{</pre><pre>  orderNumber += &quot;000001&quot;</pre><pre>}</pre><p>比較值得一提的為函式sort與字串處理，以下會依序說明。</p><p><strong>函式sort解說：</strong><br>records1:前面的參數<br>records2：後面的參數<br>講白話一點，就是後面的數字要小於前面的數字，也就是降冪排列。</p><pre>result.records.sort { records1, records2 <strong>in</strong></pre><pre><strong>return</strong> records2.fields.orderNumber &lt; records1.fields.orderNumber</pre><pre>}</pre><p><strong>字串處理解說：</strong></p><p>取得剛才排序後的第一筆orderNumber</p><pre><strong>let</strong> num = result.records.first!.fields.orderNumber</pre><p>取得orderNumber的流水碼startIndex（在這邊使用函式index並且從num.startIndex數到第八位）。例：20220315000001，依照此邏輯的話startIndex會落在六碼流水號的第一位“0”。</p><pre><strong>let</strong> startIndex = num.index(num.startIndex, offsetBy: 8)</pre><p>根據index取得完整流水碼。<br>在這邊使用range從startIndex至num.endIndex要使用小於是因為實際上endIndex會比實際的最後一位再多一位</p><pre><strong>let</strong> string = num[startIndex..&lt;num.endIndex]</pre><p>轉換成整數</p><pre><strong>var</strong> number = Int(string)!</pre><p>流水碼 + 1</p><pre>number += 1</pre><p>組成完整orderNumber</p><pre>orderNumber += NetWorkController.shared.getFrontZero(count: 6, value: number)</pre><p>在這邊利用NetWorkController的method getFrontZero(count: , value: )將整數補上前置零。<br>count：位數<br>value：要補上前置零的值</p><pre>//補前置零</pre><pre><strong>func</strong> getFrontZero(count: Int, value: Int) -&gt; String{</pre><pre><strong>  let</strong> formatter = NumberFormatter()</pre><pre>  formatter.minimumIntegerDigits = count</pre><pre><strong>  let</strong> stringNum = NSNumber(value: value)</pre><pre><strong>  return</strong> formatter.string(from: stringNum)!</pre><pre>}</pre><p>確認表頭資料是否都有值</p><pre><strong>if</strong> <strong>let</strong> date = g_headerInfo.date,</pre><pre><strong>let</strong> phone = g_headerInfo.phone,</pre><pre><strong>let</strong> userName = g_headerInfo.userName,</pre><pre><strong>let</strong> consigneeName = g_headerInfo.consigneeName{ </pre><pre><strong>  確定有值以後生成表頭資料，並且上傳資料 </strong></pre><pre>}</pre><p>確定有值以後生成表頭資料</p><pre><strong>let</strong> field = OrderHeader.Records.Fields(orderNumber: orderNumber, userName: userName, date: date, phone: phone, consigneeName: consigneeName, status: Status.send.statusText, totalPrice: <strong>self</strong>.total)</pre><pre><strong>let</strong> records = OrderHeader.Records(fields: field)</pre><pre><strong>self</strong>.orderHeader.records.append(records)</pre><p>準備上傳資料，先叫出loading畫面</p><pre>DispatchQueue.main.async {</pre><pre><strong>  self</strong>.navigationController?.pushViewController(<strong>self</strong>.loadingVC, animated: <strong>false</strong>)</pre><pre>}</pre><p>使用NetWorkController的method postOrderHeader、postOrderItem上傳資料，成功或失敗都會出相關alert訊息。詳細程式解說請參考<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/ios-25-%E7%B4%84%E7%BF%B0%E7%B4%85%E8%8C%B6%E8%A8%82%E9%A4%90app-2-0-part-1-%E4%B8%B2%E6%8E%A5airtable-api-e5a7e2b9e8d6?source=your_stories_page----------------------------------------">iOS| #25 | 約翰紅茶訂餐App 2.0–Part.1 串接Airtable API</a>。</p><ul><li><strong>查詢歷史訂單<br>在輸入完使用者名稱後點擊icon可以查看歷史訂單</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/342/1*n0Ff4NqK8iGkt5KzLBLykw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/1*VG9UVVKq1iRS0RSbQVQkLA.png" /></figure><h4>這邊將從歷史訂單的頁面（OrderViewController）開始講起</h4><p>因為一進來頁面就準備要抓資料了，首先在viewDidLoad生出Loading的ViewController，並且push過去。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-TAnx8IsoiOwvineQiCEgw.png" /></figure><p>抓取訂單資料</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sf4PlzXF-iW4f3a3iIMncw.png" /></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f0c051f34a0c43f720bbc1057c0835b4/href">https://medium.com/media/f0c051f34a0c43f720bbc1057c0835b4/href</a></iframe><p>根據result type分為success與failure兩種情況，成功就會更新tableView資料，失敗出alert訊息。</p><pre><strong>switch</strong> result {</pre><pre><strong>case</strong> .success(<strong>let</strong> orderHeader):</pre><pre>  <strong>抓到資料，更新tableView</strong></pre><pre><strong>case</strong> .failure:</pre><pre><strong>  抓資料失敗，出Alert訊息</strong></pre><pre>}</pre><h4>Call API相關程式解說請參考<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/ios-25-%E7%B4%84%E7%BF%B0%E7%B4%85%E8%8C%B6%E8%A8%82%E9%A4%90app-2-0-part-1-%E4%B8%B2%E6%8E%A5airtable-api-e5a7e2b9e8d6?source=your_stories_page----------------------------------------">iOS| #25 | 約翰紅茶訂餐App 2.0–Part.1 串接Airtable API</a>。</h4><ul><li><strong>修改訂單＆取消訂單</strong></li></ul><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FDF70CZZOAHo%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DDF70CZZOAHo&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FDF70CZZOAHo%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/b2fd5d48803300972099d406bf807179/href">https://medium.com/media/b2fd5d48803300972099d406bf807179/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F2R0gUKCTp-w%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D2R0gUKCTp-w&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F2R0gUKCTp-w%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/bf23306f940085fad980dc0c3bd5b236/href">https://medium.com/media/bf23306f940085fad980dc0c3bd5b236/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5ca624e2084941b511b6af33ed8617ef/href">https://medium.com/media/5ca624e2084941b511b6af33ed8617ef/href</a></iframe><p>修改訂單與取消訂單都是放在trailing（右手邊的地方），所以要實作<strong>func</strong> <strong>tableView(_ tableView: , trailingSwipeActionsConfigurationForRowAt indexPath: ) -&gt; UISwipeActionsConfiguration?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kRoPif3EwWT-iO6uZb1rYQ.png" /></figure><p>檢查已經完成、取消的訂單不能更改</p><pre>//完成訂單不能更改</pre><pre><strong>if</strong> record.fields.status == Status.complete.statusText { <strong>return</strong> <strong>nil</strong> }</pre><pre>//取消訂單不能更改</pre><pre><strong>if</strong> record.fields.status == Status.cancel.statusText { <strong>return</strong> <strong>nil</strong> }</pre><p>生出取消訂單的button，並且點擊以後做相對應的動作。（Call API相關程式不再贅述）</p><pre><strong>let</strong> cancel = UIContextualAction(style: .normal, title: &quot;取消&quot;) { action, view, bool <strong>in</strong></pre><pre>  <strong>更新Airtable</strong></pre><pre>}</pre><p>生出更改訂單的button，並且點擊以後做相對應的動作。（Call API相關程式不再贅述）</p><pre><strong>let</strong> edit = UIContextualAction(style: .normal, title: &quot;更改&quot;) { action, view, bool <strong>in</strong></pre><pre><strong>  使用UIAlertController搭配TextField讓使用者可以修改資料</strong></pre><pre><strong>let</strong> okAction = UIAlertAction(title: &quot;OK&quot;, style: .default) { action <br><strong>in</strong></pre><pre>  <strong>檢查alertController中的textField是否有值</strong></pre><pre><strong>  更新Airtable</strong></pre><pre>}<br></pre><pre><strong>let</strong> cancelAction = UIAlertAction(title: &quot;Cancel&quot;, style: .cancel)</pre><p>在這邊值得一提的是再度使用了UIAlertController搭配TextField的技術</p><pre><strong>let</strong> alert = UIAlertController(title: &quot;修改訂單資訊&quot;, message: &quot;僅以下資訊提供調整&quot;, preferredStyle: .alert)</pre><pre>alert.addTextField { textField <strong>in</strong></pre><pre>  textField.placeholder = &quot;取貨人名稱&quot;</pre><pre>}</pre><pre>alert.addTextField { textField <strong>in</strong></pre><pre>  textField.placeholder = &quot;聯絡電話&quot;</pre><pre>  textField.keyboardType = .phonePad</pre><pre>}</pre><p>點擊Alert的 OK action，檢查alertController中的textField是否有值</p><pre>//兩個都是空的</pre><pre><strong>if</strong> <strong>let</strong> consigneeName = alert.textFields?[0].text,</pre><pre>consigneeName.isEmpty,</pre><pre><strong>let</strong> phone = alert.textFields?[1].text,</pre><pre>phone.isEmpty{</pre><pre>  NetWorkController.shared.showAlert(title: &quot;警告&quot;, message: &quot;無修改內容&quot;) { alert <strong>in</strong></pre><pre><strong>    self</strong>.present(alert, animated: <strong>true</strong>, completion: <strong>nil</strong>)</pre><pre>  }</pre><pre><strong>  return</strong></pre><pre>}</pre><p>若有值則更新Airtable。（Call API相關程式不再贅述）</p><pre>//填值</pre><pre><strong>if</strong> <strong>let</strong> consigneeName = alert.textFields?[0].text,</pre><pre>!consigneeName.isEmpty{</pre><pre>  record.fields.consigneeName = consigneeName</pre><pre>}</pre><pre><strong>if</strong> <strong>let</strong> phone = alert.textFields?[1].text,</pre><pre>!phone.isEmpty{</pre><pre>  record.fields.phone = phone</pre><pre>}</pre><h4>Call API相關程式解說請參考<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/ios-25-%E7%B4%84%E7%BF%B0%E7%B4%85%E8%8C%B6%E8%A8%82%E9%A4%90app-2-0-part-1-%E4%B8%B2%E6%8E%A5airtable-api-e5a7e2b9e8d6?source=your_stories_page----------------------------------------">iOS| #25 | 約翰紅茶訂餐App 2.0–Part.1 串接Airtable API</a>。</h4><ul><li><strong>刪除訂單</strong></li></ul><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FfXbcUL8mkLQ%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DfXbcUL8mkLQ&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FfXbcUL8mkLQ%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/9e1a5644301e3833ac640c9e7556817a/href">https://medium.com/media/9e1a5644301e3833ac640c9e7556817a/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b6c8b5d0aff7fe7cc9a8680d26b2ca9a/href">https://medium.com/media/b6c8b5d0aff7fe7cc9a8680d26b2ca9a/href</a></iframe><h4>應用到的技術與前面雷同，相關的程式解說就不再贅述。</h4><h4>Call API相關程式解說請參考<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/ios-25-%E7%B4%84%E7%BF%B0%E7%B4%85%E8%8C%B6%E8%A8%82%E9%A4%90app-2-0-part-1-%E4%B8%B2%E6%8E%A5airtable-api-e5a7e2b9e8d6?source=your_stories_page----------------------------------------">iOS| #25 | 約翰紅茶訂餐App 2.0–Part.1 串接Airtable API</a>。</h4><p><em>系列文章：</em></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%E6%95%99%E5%AE%A4/ios-25-%E7%B4%84%E7%BF%B0%E7%B4%85%E8%8C%B6%E8%A8%82%E9%A4%90app2-0-%E6%88%90%E6%9E%9C%E5%B1%95%E7%A4%BA-142be05a5579">iOS| #25 | 約翰紅茶訂餐App2.0 成果展示</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%E6%95%99%E5%AE%A4/ios-25-%E7%B4%84%E7%BF%B0%E7%B4%85%E8%8C%B6%E8%A8%82%E9%A4%90app-2-0-part-1-%E4%B8%B2%E6%8E%A5airtable-api-e5a7e2b9e8d6">iOS| #25 | 約翰紅茶訂餐App 2.0–Part.1 串接Airtable API</a></li><li><a href="https://medium.com/@tommy5566123/ios-25-%E7%B4%84%E7%BF%B0%E7%B4%85%E8%8C%B6%E8%A8%82%E9%A4%90app-2-0-part-2-%E9%BB%9E%E9%A4%90%E8%88%87%E8%B3%BC%E7%89%A9%E8%BB%8A%E7%AF%87-42c578620922">iOS| #25 | 約翰紅茶訂餐App 2.0–Part.2 點餐與購物車篇</a></li><li><a href="https://medium.com/@tommy5566123/ios-25-%E7%B4%84%E7%BF%B0%E7%B4%85%E8%8C%B6%E8%A8%82%E9%A4%90app-2-0-part-3-%E9%80%81%E5%87%BA%E8%A8%82%E5%96%AE%E8%88%87%E4%BF%AE%E6%94%B9%E8%A8%82%E5%96%AE-65314e315cc4">iOS| #25 | 約翰紅茶訂餐App 2.0–Part.3 送出訂單與修改訂單</a></li></ul><p><em>GitHub：</em></p><p><a href="https://github.com/tommy6457/DrinkOrder">GitHub - tommy6457/DrinkOrder</a></p><p><em>參考資料：</em></p><p><a href="https://medium.com/%E5%BD%BC%E5%BE%97%E6%BD%98%E7%9A%84%E8%A9%A6%E7%85%89-%E5%8B%87%E8%80%85%E7%9A%84-100-%E9%81%93-swift-ios-app-%E8%AC%8E%E9%A1%8C/%E4%BD%A0%E5%87%BA%E5%8A%9B%E5%AF%AB-app-%E6%88%91%E5%87%BA%E9%8C%A2%E8%AB%8B%E9%A3%B2%E6%96%99-6a9ac14a2a22">#20 訂飲料 App，上傳資料到後台</a></p><p>若內容有誤煩請指教，感謝收看。</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=65314e315cc4" width="1" height="1" alt=""><hr><p><a href="https://medium.com/peter-pan-swift-ios-class/ios-25-%E7%B4%84%E7%BF%B0%E7%B4%85%E8%8C%B6%E8%A8%82%E9%A4%90app-2-0-part-3-%E9%80%81%E5%87%BA%E8%A8%82%E5%96%AE%E8%88%87%E4%BF%AE%E6%94%B9%E8%A8%82%E5%96%AE-65314e315cc4">iOS| #25 | 約翰紅茶訂餐App 2.0–Part.3 送出訂單與修改訂單</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[iOS| #25 | 約翰紅茶訂餐App 2.0–Part.2 點餐與購物車篇]]></title>
            <link>https://medium.com/peter-pan-swift-ios-class/ios-25-%E7%B4%84%E7%BF%B0%E7%B4%85%E8%8C%B6%E8%A8%82%E9%A4%90app-2-0-part-2-%E9%BB%9E%E9%A4%90%E8%88%87%E8%B3%BC%E7%89%A9%E8%BB%8A%E7%AF%87-42c578620922?source=rss-dcc5ce982008------2</link>
            <guid isPermaLink="false">https://medium.com/p/42c578620922</guid>
            <category><![CDATA[swift-programming]]></category>
            <dc:creator><![CDATA[Tommy]]></dc:creator>
            <pubDate>Fri, 11 Mar 2022 16:59:36 GMT</pubDate>
            <atom:updated>2022-03-21T05:21:46.918Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*szDRCaW7Th7W4DFKXSIgtw.png" /></figure><p>不久前已經實作過訂飲料App初版，那麼這次要利用目前所學的技能將其升級為2.0，並且加上數個功能使其成為一個更完整的產品。</p><h4>本篇文章主要會說明點餐與購物車的UI畫面與功能實現。</h4><blockquote>由於此系列文篇幅會較長，會拆分成多篇文章紀錄實作的過程與功能講解</blockquote><blockquote>技術應用</blockquote><ul><li>Programming Autolayout</li><li>Programming UIKit</li><li>StackView</li><li>TableView</li><li>AutoLayout</li><li>Airtable REST API — CRUD</li></ul><blockquote>UI畫面</blockquote><ul><li>Login Page<br>登入</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1002/1*ygsEYrcKB0CGOeqt0ObWFg.png" /></figure><ul><li>User Page <br>使用者資訊</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1016/1*OhzSQBxJnl2H3rxnc8c_4w.png" /></figure><ul><li>Menu Page<br>菜單</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ao0KGxmcjmf8V0gAMyYcXQ.png" /></figure><ul><li>Choose Page<br>選擇飲料屬性（EX: 冰塊、甜度等等）</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/874/1*J8qU-zWg4ywDaW87nNuHsA.png" /></figure><ul><li>Cart Page <br>購物車</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/910/1*i6xvozBn2MkQnhSjok6kcQ.png" /></figure><blockquote>功能解說＆程式解說</blockquote><h4>Login Page &amp; User Page：</h4><p>登入介面與使用者資料介面邏輯相似且較為單純，在這邊一起說明。<br>（登入功能目前規劃只要輸入任意使用者名稱即可，正式登入功能會在後續找時間補上）</p><ul><li><strong>Login Page ＆ User Page Textfield檢查機制</strong></li></ul><p><strong>拉好Login Page至User Page的Segue</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K8H9hbSZK_2eL8bRPnJ6lw.png" /></figure><p><strong>拉好SegueAction</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iEvODlXAeIXUsCWDI0vQ4g.png" /></figure><p>收鍵盤</p><pre>userNameTextField.resignFirstResponder()</pre><p><strong>實作func shouldPerformSegue(withIdentifier identifier: , sender: )</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EydykDg30yf7HZPMX0O7iw.png" /></figure><p>檢查若沒有輸入使用者名稱就show alert訊息，且return false（停留在這一頁）</p><pre><strong>if</strong> userNameTextField.text!.isEmpty {</pre><pre>  //alert</pre><pre>  NetWorkController.shared.showAlert(title: &quot;警告&quot;, message: &quot;請輸入使 用者名稱&quot;) { alert <strong>in</strong></pre><pre><strong>    self</strong>.present(alert, animated: <strong>true</strong>, completion: <strong>nil</strong>)</pre><pre>  }</pre><pre><strong>  return</strong> <strong>false</strong></pre><pre>}</pre><p>由於此App有許多地方都會需要show alert訊息，於是將其寫在struct NetWorkController裡面可供重複使用</p><pre>//show alert</pre><pre><strong>func</strong> showAlert(title: String , message: String ,handler: (UIAlertController) -&gt; Void ){</pre><pre><strong>  let</strong> alertController = UIAlertController(title: title, message:  message, preferredStyle: .alert)</pre><pre><strong>  let</strong> ok = UIAlertAction(title: &quot;OK&quot;, style: .default)</pre><pre>  alertController.addAction(ok)</pre><pre>  alertController.view.tintColor = .systemBlue</pre><pre>  handler(alertController)</pre><pre>}</pre><p>若有輸入，則將名稱 pass 給global 變數 g_headerInfo，且return true（去下一頁）</p><pre>//keep 使用者名稱</pre><pre>g_headerInfo.userName = userNameTextField.text</pre><pre><strong>return</strong> <strong>true</strong></pre><h4>User Page的檢查機制與Login Page相同，因此不再贅述。</h4><h4>Menu Page：</h4><ul><li><strong>根據AitTable設定檔 — DrinkType動態生成飲料類別Button</strong></li></ul><p><strong>原始資料</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iFCIlSxP9hNLqN4WpCd-3g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/296/1*8yAE_BciEp32gCsRVXtn6g.gif" /></figure><p><strong>新增測試資料</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CkQw4wXCXEIZvP_8kbB6gA.png" /></figure><p><strong>App相對新增Button</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/296/1*g2ck6O96yEa0su3v0Xl-HA.gif" /></figure><h4>技術解說請參考<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/ios-24-%E6%90%AD%E9%85%8D%E5%8B%95%E7%95%AB%E7%9A%84%E6%B0%B4%E5%B9%B3%E6%BB%91%E5%8B%95%E5%BA%95%E7%B7%9A%E6%8C%89%E9%88%95%E8%88%87%E9%A0%81%E9%9D%A2%E6%8E%A7%E5%88%B6-f9bd34d433e1">iOS| #24 | 搭配動畫的水平滑動底線按鈕與頁面控制</a></h4><p><strong>以下將說明動態產生UIButton的方式</strong></p><p><strong>首先各產生一個ScrollView與StackView，並讓ScrollView包住StackView</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aaYiH4omWI3ljVC-zFQofw.png" /></figure><p><strong>拉Stackview的@IBOutlet</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Wrds3jgz8-FqqQeXqYGJ2Q.png" /></figure><p><strong>在viewDidLoad()抓Menu資料，成功抓到資料後呼叫method setMenuButton(index: , records: )動態建立UIButton至buttonsStackView中</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6b5201407d4696674b1321b7f9f9ead5/href">https://medium.com/media/6b5201407d4696674b1321b7f9f9ead5/href</a></iframe><p><strong>抓資料程式碼解說可以參考</strong><a href="https://medium.com/p/e5a7e2b9e8d6/edit?source=your_stories_page----------------------------------------"><strong>iOS| #25 | 約翰紅茶訂餐App 2.0–Part.1 串接Airtable API</strong></a><strong>，以下將會說明動態建立UIButton至buttonsStackView</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9c2c173f6853461672b07438d516597f/href">https://medium.com/media/9c2c173f6853461672b07438d516597f/href</a></iframe><p>產生UIButton元件</p><pre><strong>let</strong> button = UIButton()</pre><p>設定button的title attribute</p><pre>button.setAttributedTitle(NSAttributedString(string: records.fields.typeName, attributes: [.foregroundColor: UIColor(named: &quot;AccentColor&quot;)!, .font: UIFont(name: &quot;Songti TC Bold&quot;, size: 15)!]), <strong>for</strong>: .normal)</pre><p>把index值給tag，日後將會利用tag判斷切換頁面與更新資料</p><pre>button.tag = index</pre><p>設定點擊button後要處理的動作 (method clickMenu 後續會再做說明)</p><pre>button.addTarget(<strong>self</strong>, action: <strong>#selector</strong>(<strong>self</strong>.clickMenu), <strong>for</strong>: .touchUpInside)</pre><p>將button加進stackView中。<br>注意：這邊要用addArrangedSubview而不是addSubview</p><pre>//stackView要使用addArrangedSubview</pre><pre>buttonsStackView.addArrangedSubview(button)</pre><h4>以下將說明method clickMenu的相關程式</h4><p><strong>每當點擊event touchUpInside發生時，會執行此method</strong></p><pre><strong>@objc</strong> <strong>func</strong> clickMenu(sender: UIButton){</pre><pre>currentPage = sender.tag</pre><pre>setUnderLineView(index: sender.tag)</pre><pre>setItemTableViewController(currentpage: sender.tag)</pre><pre>}</pre><p>在此頁面的ViewController宣告屬性currentPage，將前面設定好的button屬性tag作為換頁的依據，把值給currentPage。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/982/1*SFqcv0osMMIj9NJ_wteyKg.png" /></figure><pre>currentPage = sender.tag</pre><p>改變underLineView的位置（詳細解說請參考<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/ios-24-%E6%90%AD%E9%85%8D%E5%8B%95%E7%95%AB%E7%9A%84%E6%B0%B4%E5%B9%B3%E6%BB%91%E5%8B%95%E5%BA%95%E7%B7%9A%E6%8C%89%E9%88%95%E8%88%87%E9%A0%81%E9%9D%A2%E6%8E%A7%E5%88%B6-f9bd34d433e1">iOS| #24 | 搭配動畫的水平滑動底線按鈕與頁面控制</a>）</p><pre>setUnderLineView(index: sender.tag)</pre><p>根據點選的button切換對應的飲料類別Menu資料（在後續段落會詳細解說）</p><pre>setItemTableViewController(currentpage: sender.tag)</pre><ul><li><strong>根據AitTable設定檔 — Menu動態生成Menu</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/296/1*x1cXRCDJXoNUNqp345xuNg.gif" /></figure><p><strong>將AirTable — Menu資料維護齊全</strong></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fairtable.com%2Fembed%2FshrUzHWzis01CqMpR&amp;display_name=Airtable&amp;url=https%3A%2F%2Fairtable.com%2FshrUzHWzis01CqMpR&amp;image=https%3A%2F%2Fstatic.airtable.com%2Fimages%2Foembed%2Fairtable.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=airtable" width="800" height="533" frameborder="0" scrolling="no"><a href="https://medium.com/media/650fb94c8d5728613abde6485041134c/href">https://medium.com/media/650fb94c8d5728613abde6485041134c/href</a></iframe><p><strong>透過欄位type與AirTable — DrinkType的欄位typeID做mapping顯示菜單</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GFuT6i2ViUkTR52uj_6V-A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ds6n60nucBKLp2PJ7iPqxg.png" /></figure><h4><strong>method setItemTableViewControllert(currentpage: ) 解說：</strong></h4><p>承前述說明，當點擊button時會呼叫此method clickMenu(sender:)，而在此method中還會呼叫setItemTableViewController(currentpage: )切換頁面中的資料</p><pre><strong>@objc</strong> <strong>func</strong> clickMenu(sender: UIButton){</pre><pre>currentPage = sender.tag</pre><pre>setUnderLineView(index: sender.tag)</pre><pre><strong>setItemTableViewController(currentpage: sender.tag)</strong></pre><pre>}</pre><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f7f12259fa37eba7df4ce3a4aa11d39a/href">https://medium.com/media/f7f12259fa37eba7df4ce3a4aa11d39a/href</a></iframe><p>利用ViewController的children屬性跑迴圈。<br>children可以得出在自己Controller底下ContainerView中容納的ViewController元件。</p><pre><strong>self</strong>.children.forEach { viewController <strong>in </strong>想要做的動作 }</pre><p>取出ItemTableViewController</p><pre><strong>guard</strong> <strong>let</strong> itemTableViewController = viewController <strong>as</strong>? ItemTableViewController <strong>else</strong> { <strong>return</strong> }</pre><p>透過currentPage取出該分類的飲料菜單，getItemMenu(from: )參考以下說明</p><pre><strong>guard</strong> <strong>let</strong> itemMenu = getItemMenu(from: currentPage) <strong>else</strong> { <strong>return</strong> }</pre><p>利用Array的method filter() 過濾資料，利用欄位type、typeID將對應分類的資料篩選出來</p><pre>//根據飲料分類取得相對應的品項</pre><pre><strong>func</strong> getItemMenu(from currentPage: Int) -&gt; [Menu.Records]? {</pre><pre><strong>let</strong> records = menu?.records.filter({ result <strong>in</strong></pre><pre><strong>return</strong> result.fields.type == drinkTypes?.records[currentPage].fields.typeID</pre><pre>})</pre><pre><strong>return</strong> records</pre><pre>}</pre><p>由於是共用同一個tableViewController，所以當我們在不同分頁間滑動時，要將ContentOffset滑到最上面</p><pre>//換頁要滑到最上面</pre><pre>itemTableViewController.tableView.setContentOffset(CGPoint(x: 0, y: 0), animated: <strong>false</strong>)</pre><p>在ItemTableViewController中宣告屬性currentMenu，承接要顯示的值，並且把已過濾好的值pass給currentMenu</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zktQjXiA7ht7DWq_WA_Sjw.png" /></figure><pre>//給item值</pre><pre>itemTableViewController.currentMenu = itemMenu</pre><p>給完值以後要更新tableView才會顯示出來</p><pre>//更新tableview</pre><pre>itemTableViewController.tableView.reloadData()</pre><p>讓tableView更新資料時有動畫效果（by sections）<br>此例只有一個section，所以可以大膽的給參數IndexSet(integer: 0)，得出第一個Section</p><pre>//向右滑入cell動畫</pre><pre>itemTableViewController.tableView.reloadSections(IndexSet(integer: 0), with: .right)</pre><h4>Choose Page：</h4><ul><li><strong>根據設定檔資料決定輸出樣式</strong></li></ul><p><strong>在parent（ChooseViewController）中決定children（ChooseTableViewController）的UI畫面</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ygsckJCuFRLK8Xa2j6TAMw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d98YXtpPbQEoHXrCxknQ7w.png" /></figure><p>屬性Children的使用方式可以參考前述<strong>MENU</strong>解說</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d7C97EZoWWQi-5W6T6PxQQ.png" /></figure><p><strong>在containerView中的tableViewController實作func initialUI()<br></strong>進入此頁面時已經得到設定檔資料了，在func initialUI()中將會利用屬性item初始化UI輸出的樣式</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Pr6R6o9yh68cyRIsxvgKhQ.png" /></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6f3ca8d0ba16cefbe128bdcbe3a6ef3c/href">https://medium.com/media/6f3ca8d0ba16cefbe128bdcbe3a6ef3c/href</a></iframe><p><strong>根據MENU設定檔的欄位判斷是否為固定的冰塊、甜度、可否加珍珠。</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pyG_LfSFNIcWLJjPEL7h0g.png" /></figure><p><strong>都是呼叫同一個func setButtonsDisable(tag: , buttons: , equal: )</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6f0e3dba45ed01edd4cdec2e2a651580/href">https://medium.com/media/6f0e3dba45ed01edd4cdec2e2a651580/href</a></iframe><p>tag：Button的屬性tag值（在Interface Builder手動維護）。<br>以冰塊為例子會與Enum Ice做mapping控制button的狀態</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/43ce9738caa7a6901150794310b09d61/href">https://medium.com/media/43ce9738caa7a6901150794310b09d61/href</a></iframe><p>buttons：拉好的OutletCollections。（下圖以冰塊為例）</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VGsDjdxikiROlKEid5h7og.png" /></figure><p>equal：判斷等於tag設為不可點擊；不等於tag設為不可點擊。</p><p>根據條件設定button的圖片，因為是系統的圖片，所以要用systemName來生成</p><pre>button.setImage(UIImage(systemName: &quot;checkmark.circle.trianglebadge.exclamationmark&quot;), for: .normal)</pre><p>將button設為不可選取</p><pre>button.isEnabled = <strong>false</strong></pre><ul><li><strong>Radio Button實作</strong><br>由於Swift官方沒有Radio Button，於是在這邊自己實作</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1ad089661bf059862e541f502040c9e0/href">https://medium.com/media/1ad089661bf059862e541f502040c9e0/href</a></iframe><p>tag：Button的屬性tag值（在Interface Builder手動維護）。</p><p>buttons：拉好的OutletCollections。</p><p>利用for迴圈判斷被點選之button圖示改為”checkmark.circle.fill”，其餘改為”checkmark.circle”。<br>因為前面已經初始化UI畫面了，可能有部分飲料品項為固定的甜度、冰度。初始化的當下就已經將UIButton的state設為disabled，所以在這邊要下where條件排除這些用不到的UIButton。</p><pre><strong>for</strong> button <strong>in</strong> buttons <strong>where</strong> button.state != .disabled {</pre><pre><strong>  if</strong> button.tag == tag {</pre><pre>  button.setImage(UIImage(systemName: &quot;checkmark.circle.fill&quot;), for: .normal)</pre><pre>  }<strong>else</strong>{</pre><pre>  button.setImage(UIImage(systemName: &quot;checkmark.circle&quot;), for:  .normal)</pre><pre>  }</pre><pre>}</pre><p><strong>當點擊UIButton時更新UI畫面（以冰塊為例）</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/49130359e0617c0c42d231a5f51d230e/href">https://medium.com/media/49130359e0617c0c42d231a5f51d230e/href</a></iframe><p>實現radioButton功能</p><pre>radioButtonAction(tag: sender.tag, buttons: iceCheckButtons)</pre><p>keep選擇的冰塊屬性（currentIceAttribute宣告為Class ChooseTableViewController本身的屬性）</p><pre>currentIceAttribute = Ice.getIce(int: sender.tag)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y2FMqoqZl1nYFIL0mCgTLg.png" /></figure><p>更新UI Button的畫面<br>冰塊的判斷會比較特別，當選擇熱飲的時候(tag = 4)尺寸就只能選擇M，於是在這邊先判斷選擇熱飲要將M尺寸(tag = 0)設成Enable，且currentSizeAttribute要設為nil；L尺寸(tag = 1)設成Disable。<br>若選擇其他冷飲的話就將L尺寸(tag = 1)設成Enable。</p><pre>//熱飲的話不能選擇L尺寸</pre><pre><strong>if</strong> sender.tag == 4 {</pre><pre>  setButtonsEnable(tag: 0, buttons: sizeCheckButtons)</pre><pre>  setButtonsDisable(tag: 1,buttons: sizeCheckButtons, equal: <strong>true</strong>)</pre><pre>  currentSizeAttribute = <strong>nil</strong></pre><pre>}<strong>else</strong>{</pre><pre>  //如果選擇熱飲以外的，讓尺寸L可以被選擇</pre><pre><strong>  for</strong> button <strong>in</strong> sizeCheckButtons <strong>where</strong> button.tag == 1{</pre><pre><strong>    if</strong> !button.isEnabled {</pre><pre>      setButtonsEnable(tag: 1, buttons: sizeCheckButtons)</pre><pre>    }</pre><pre>  }</pre><pre>}</pre><p>func setButtonsEnable(tag: , buttons: )<br>與前述說明的func setButtonsDisable十分相似，都是更換Button圖片與控制屬性isEnabled</p><pre><strong>func</strong> setButtonsEnable(tag: Int, buttons: [UIButton]){</pre><pre>  //指定tag的button可被點擊</pre><pre><strong>  for</strong> button <strong>in</strong> buttons <strong>where</strong> button.tag == tag{</pre><pre>    button.setImage(UIImage(systemName: &quot;checkmark.circle&quot;), for: .normal)</pre><pre>    button.isEnabled = <strong>true</strong></pre><pre>  }</pre><pre>}</pre><p>利用parent屬性生成ChooseViewController，並且重新計算金額（後續會做解說）</p><pre><strong>let</strong> chooseViewController = parent <strong>as</strong>! ChooseViewController</pre><pre>chooseViewController.countPrice()</pre><ul><li><strong>根據數量、品項屬性動態計算當前金額<br></strong>當選擇品項的尺寸、增加或減少數量、加珍珠等等都會影響到當前的金額，所以在這邊實作<strong>func</strong> <strong>countPrice()</strong>，只要該品項與金額相關的屬性改變就會呼叫它更新金額。</li></ul><p><strong>數量控制邏輯<br></strong>使用兩個UIButton控制數量增減，一個UILabel負責顯示數量</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/620/1*K4BtmbNuCyz5A0IXS9bXnQ.png" /></figure><p><strong>宣告變數currentQuantity，記住當前數量</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d57fSpseZHFUpsyFaTU3qg.png" /></figure><p><strong>這兩個Button會共用同一個@IBAction</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d9fef30bb6d9927ab2cc07c388725f92/href">https://medium.com/media/d9fef30bb6d9927ab2cc07c388725f92/href</a></iframe><p>利用UIButton的tag判斷數量增減（0為減；1為加）。<br>減的部分要注意數量沒有負的，所以要判斷算出來小於0的話要改成0。</p><pre>//減</pre><pre><strong>if</strong> sender.tag == 0 {</pre><pre>  currentQuantity -= 1</pre><pre><strong>  if</strong> currentQuantity &lt; 0 {</pre><pre>    currentQuantity = 0</pre><pre>  }</pre><pre>}</pre><pre>//加</pre><pre><strong>else</strong>{</pre><pre>  currentQuantity += 1</pre><pre>}</pre><p>更新數量UILabel</p><pre>quantityLabel.text = &quot;\(currentQuantity)&quot;</pre><p>計算金額</p><pre>countPrice()</pre><p><strong>實作 func countPrice()</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/724efdb86c2ee336592cdabf7215db05/href">https://medium.com/media/724efdb86c2ee336592cdabf7215db05/href</a></iframe><p>利用屬性children取得ChooseTableViewController</p><pre><strong>self</strong>.children.forEach { viewController <strong>in</strong></pre><pre><strong> guard</strong> <strong>let</strong> chooseTableViewController = viewController <strong>as</strong>?   ChooseTableViewController <strong>else</strong> { <strong>return</strong> }</pre><pre>}</pre><p>避免殘留值，先將parent（ChooseViewController）的屬性金額歸零</p><pre>//金額先歸零</pre><pre>price = 0</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KIhrFEMuiUp0jKt-uydlrg.png" /></figure><p>取得children（ChooseTableViewController）的屬性currentSizeAttribute，確保使用者有選擇尺寸才做後續動作</p><pre><strong>guard</strong> <strong>let</strong> currentSizeAttribute = chooseTableViewController.currentSizeAttribute <strong>else</strong> { <strong>return</strong> }</pre><p>取得children（ChooseTableViewController）的屬性currentIceAttribute，確保使用者有選擇冰塊才做後續動作</p><pre><strong>guard</strong> <strong>let</strong> currentIceAttribute = chooseTableViewController.currentIceAttribute <strong>else</strong> { <strong>return</strong> }</pre><p>宣告變數currentPrice作為飲料品項的單價</p><pre>//單價</pre><pre><strong>var</strong> currentPrice = 0</pre><p>根據屬性取得單價</p><pre><strong>switch</strong> currentSizeAttribute {</pre><pre><strong>case</strong> .M:</pre><pre>  //熱飲只有M的價格</pre><pre><strong>  if</strong> currentIceAttribute == .hot {</pre><pre>    currentPrice = Int(chooseTableViewController.item.hotMPrice ?? 0)</pre><pre>  }<strong>else</strong>{</pre><pre>    currentPrice = Int(chooseTableViewController.item.coldMPrice ?? 0)</pre><pre>  }</pre><pre><strong>case</strong> .L:</pre><pre>  currentPrice = Int(chooseTableViewController.item.coldLPrice ?? 0)</pre><pre>}</pre><p>計算總價格（若加珍珠則+5塊）</p><pre><strong>if</strong> chooseTableViewController.currentAddBubble {</pre><pre>  price = currentQuantity * currentPrice + 5 * currentQuantity</pre><pre>}<strong>else</strong>{</pre><pre>  price = currentQuantity * currentPrice</pre><pre>}</pre><p>將總價格更新到UILabel上</p><pre>chooseTableViewController.priceLabel.text = &quot;\(price)&quot;</pre><ul><li><strong>新增品項至購物車</strong></li></ul><p><strong>點擊按鈕即可將該品項新增至購物車，若沒有選擇完整資訊會跳出Alert訊息</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/338/1*LteqNp7RLycI5FYwi2bACg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/330/1*oP2cD0KRXfyFjgB3jALU_w.png" /></figure><p><strong>實作@IBAction func clickAddToCart</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/388f77fd74e515b04eddb1829b07feaa/href">https://medium.com/media/388f77fd74e515b04eddb1829b07feaa/href</a></iframe><p>取得children（ChooseTableViewController）</p><pre><strong>self</strong>.children.forEach { viewController <strong>in</strong></pre><pre><strong>  guard</strong> <strong>let</strong> chooseTableViewController = viewController <strong>as</strong>?   ChooseTableViewController <strong>else</strong> { <strong>return</strong> }</pre><pre>}</pre><p>檢查品項的相關屬性是否為空。<br>（ice：冰塊、sugar：甜度、size：尺寸、currentQuantity：數量、price：金額）</p><pre><strong>if</strong> <strong>let</strong> ice = chooseTableViewController.currentIceAttribute,</pre><pre><strong>let</strong> sugar = chooseTableViewController.currentSugarAttribute,</pre><pre><strong>let</strong> size = chooseTableViewController.currentSizeAttribute,</pre><pre>currentQuantity != 0,</pre><pre>price != 0</pre><pre>{<br>  <strong> 新增至購物車，並且出提示訊息</strong></pre><pre>}<strong>else</strong>{</pre><pre><strong>   有屬性未選擇，出錯誤訊息</strong></pre><pre>}</pre><p>新增至購物車，並且出提示訊息</p><pre><strong>let</strong> cartData = Cart(ice: ice, sugar: sugar, size: size, bubble: chooseTableViewController.currentAddBubble ,quantity: currentQuantity,price: price, itemID: item.recordID , itemName: item.itemName)</pre><pre>g_cartData.append(cartData)</pre><pre>NetWorkController.shared.showAlert(title: &quot;提醒&quot;, message: &quot;已新增至購物車&quot;) { alert <strong>in</strong></pre><pre>  present(alert, animated: <strong>true</strong>, completion: <strong>nil</strong>)</pre><pre>}</pre><p>有屬性未選擇，出錯誤訊息</p><pre>NetWorkController.shared.showAlert(title: &quot;提醒&quot;, message: &quot;請輸入完整資訊&quot;) { alert <strong>in</strong></pre><pre>  present(alert, animated: <strong>true</strong>, completion: <strong>nil</strong>)</pre><pre>}</pre><h4><strong>Cart Page：</strong></h4><p>單純顯示global變數g_cart的資料與總金額，但考慮到有可能上一秒想喝煮濃那提，下一秒又想喝別的，所以做了刪除功能。<br>在購物車這邊除了送出訂單以外沒有比較特別的邏輯，關於送出訂單程式將會在下篇文章說明。</p><ul><li><strong>計算總金額</strong></li></ul><p><strong>在CartViewController宣告屬性total，負責紀錄總金額</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/968/1*4YBc8v8bEC6BPCI30ZRUFw.png" /></figure><p><strong>在viewDidLoad()計算總金額</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hratQimu1zpvaDXdpzPqPw.png" /></figure><p><strong>setTotalPrice()</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/802b2be170e76f0bb6364d5fad388ed4/href">https://medium.com/media/802b2be170e76f0bb6364d5fad388ed4/href</a></iframe><p>歸零</p><pre>total = 0</pre><p>根據g_cartData的內容計算總金額</p><pre><strong>if</strong> !g_cartData.isEmpty {</pre><pre>  total = g_cartData.reduce(0){ $0 + $1.price }</pre><pre>}</pre><p>判斷不是空的才要計算</p><pre><strong>if</strong> !g_cartData.isEmpty { <strong>加總程式</strong> }</pre><p>使用reduce加總</p><pre>total = g_cartData.reduce(0){ $0 + $1.price }</pre><h4>若沒有使用過的人看到reduce可能會有些疑惑，讓我們看看以下的例子：</h4><ol><li>宣告一個常數number型別為Int的Array</li><li>宣告一個常數total為常數number使用reduce加總後的結果</li><li>印出常數total</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f6jPrKnJgjQvA_UKWhz4Ng.png" /></figure><p>在reduce的method中可以看到兩個參數：initialResult、nextPartialResult。initialResult：初始值。<br>nextPartialResult：為閉包，在此閉包中還有兩個參數：<br>1. nextPartialResult中的參數Result：每次加總後的結果<br>2. nextPartialResult中的參數Int：number中的每筆數字。</p><p>將游標移到initialResult的placeHolder上，並且按下enter。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qmblgCNH3XOfnQ0AHvzGfg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NOogvw9Wqxf9To5Id_UvhQ.png" /></figure><p>將游標移到nextPartialResult的placeHolder上，並且按下enter。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aBC6N_iC607SLo4bvStb8Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mSe_AfWYs30XEDmvRzdKjA.png" /></figure><p>將初始值(Result)設為0、且在 in 中讓partialResult 加上 Int（因為只有一行程式碼，所以不需要return）</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TUwUztu0-Aaxx_cjqalxbQ.png" /></figure><p>可以得出total為33</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WVVBmnMiwWUlStRUCoBecw.png" /></figure><p>寫法還可以更簡潔，讓我們把閉包的內容都刪掉</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/798/1*SKf0BGAF36QrIBwL85R97g.png" /></figure><p>直接寫上$0(代表第一個參數) + $1(代表第二個參數)，結果相同。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NKK7r3FjjPkGIQQe3GwLRQ.png" /></figure><ul><li><strong>刪除購物車品項<br></strong>在tableView實作swipe的功能，點擊button達成刪除目的。</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/998ea108e471313d072710cde7b5597d/href">https://medium.com/media/998ea108e471313d072710cde7b5597d/href</a></iframe><h4>這裡沒有特別的地方，因此不再贅述。swipe相關程式解說可以參考<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/ios-23-%E4%BD%BF%E7%94%A8tableview%E8%88%87core-data%E5%AF%A6%E4%BD%9Ctodo-app-729a7b549bca">iOS| #23 | 使用TableView與Core Data實作ToDo App</a>。</h4><p><em>系列文章：</em></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%E6%95%99%E5%AE%A4/ios-25-%E7%B4%84%E7%BF%B0%E7%B4%85%E8%8C%B6%E8%A8%82%E9%A4%90app2-0-%E6%88%90%E6%9E%9C%E5%B1%95%E7%A4%BA-142be05a5579">iOS| #25 | 約翰紅茶訂餐App2.0 成果展示</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%E6%95%99%E5%AE%A4/ios-25-%E7%B4%84%E7%BF%B0%E7%B4%85%E8%8C%B6%E8%A8%82%E9%A4%90app-2-0-part-1-%E4%B8%B2%E6%8E%A5airtable-api-e5a7e2b9e8d6">iOS| #25 | 約翰紅茶訂餐App 2.0–Part.1 串接Airtable API</a></li><li><a href="https://medium.com/@tommy5566123/ios-25-%E7%B4%84%E7%BF%B0%E7%B4%85%E8%8C%B6%E8%A8%82%E9%A4%90app-2-0-part-2-%E9%BB%9E%E9%A4%90%E8%88%87%E8%B3%BC%E7%89%A9%E8%BB%8A%E7%AF%87-42c578620922">iOS| #25 | 約翰紅茶訂餐App 2.0–Part.2 點餐與購物車篇</a></li><li><a href="https://medium.com/@tommy5566123/ios-25-%E7%B4%84%E7%BF%B0%E7%B4%85%E8%8C%B6%E8%A8%82%E9%A4%90app-2-0-part-3-%E9%80%81%E5%87%BA%E8%A8%82%E5%96%AE%E8%88%87%E4%BF%AE%E6%94%B9%E8%A8%82%E5%96%AE-65314e315cc4">iOS| #25 | 約翰紅茶訂餐App 2.0–Part.3 送出訂單與修改訂單</a></li></ul><p><em>GitHub：</em></p><p><a href="https://github.com/tommy6457/DrinkOrder">GitHub - tommy6457/DrinkOrder</a></p><p><em>參考資料：</em></p><ul><li><a href="https://medium.com/%E5%BD%BC%E5%BE%97%E6%BD%98%E7%9A%84%E8%A9%A6%E7%85%89-%E5%8B%87%E8%80%85%E7%9A%84-100-%E9%81%93-swift-ios-app-%E8%AC%8E%E9%A1%8C/%E4%BD%A0%E5%87%BA%E5%8A%9B%E5%AF%AB-app-%E6%88%91%E5%87%BA%E9%8C%A2%E8%AB%8B%E9%A3%B2%E6%96%99-6a9ac14a2a22">#20 訂飲料 App，上傳資料到後台</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%BE%9E%E7%A8%8B%E5%BC%8F%E5%8B%95%E6%85%8B%E5%8A%A0-view-%E5%88%B0-stack-view-e5c2a2d01575">從程式動態加 view 到 stack view</a></li></ul><p>若內容有誤煩請指教，感謝收看。</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=42c578620922" width="1" height="1" alt=""><hr><p><a href="https://medium.com/peter-pan-swift-ios-class/ios-25-%E7%B4%84%E7%BF%B0%E7%B4%85%E8%8C%B6%E8%A8%82%E9%A4%90app-2-0-part-2-%E9%BB%9E%E9%A4%90%E8%88%87%E8%B3%BC%E7%89%A9%E8%BB%8A%E7%AF%87-42c578620922">iOS| #25 | 約翰紅茶訂餐App 2.0–Part.2 點餐與購物車篇</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[iOS| #25 | 約翰紅茶訂餐App 2.0–Part.1 串接Airtable API]]></title>
            <link>https://medium.com/peter-pan-swift-ios-class/ios-25-%E7%B4%84%E7%BF%B0%E7%B4%85%E8%8C%B6%E8%A8%82%E9%A4%90app-2-0-part-1-%E4%B8%B2%E6%8E%A5airtable-api-e5a7e2b9e8d6?source=rss-dcc5ce982008------2</link>
            <guid isPermaLink="false">https://medium.com/p/e5a7e2b9e8d6</guid>
            <category><![CDATA[swift-programming]]></category>
            <dc:creator><![CDATA[Tommy]]></dc:creator>
            <pubDate>Tue, 08 Mar 2022 09:12:25 GMT</pubDate>
            <atom:updated>2022-03-16T07:42:14.110Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*szDRCaW7Th7W4DFKXSIgtw.png" /></figure><p>不久前已經實作過訂飲料App初版，那麼這次要利用目前所學的技能將其升級為2.0，並且加上數個功能使其成為一個更完整的產品。</p><h4>本篇文章主要會說明Airtable設計Model的架構與App設計Model的架構。</h4><blockquote>由於此系列文篇幅會較長，會拆分成多篇文章紀錄實作的過程與功能講解</blockquote><blockquote>前情提要</blockquote><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/ios-14-1-%E7%B4%84%E7%BF%B0%E7%B4%85%E8%8C%B6%E9%BB%9E%E9%A4%90app%E5%88%9D%E7%89%88-part-1-menu%E7%AF%87-8bf5b3cf3c57?source=your_stories_page----------------------------------------">iOS| #14–1 | 約翰紅茶點餐App初版 part 1. MENU篇</a></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/ios-14-2-%E7%B4%84%E7%BF%B0%E7%B4%85%E8%8C%B6%E9%BB%9E%E9%A4%90app%E5%88%9D%E7%89%88-part-2-%E8%B3%87%E6%96%99%E5%82%B3%E9%81%9E%E8%88%87detail%E9%A0%81%E9%9D%A2%E7%AF%87-150a8be4d3b0?source=your_stories_page----------------------------------------">iOS| #14–2 | 約翰紅茶點餐App初版 part 2. 資料傳遞與Detail頁面篇</a></p><blockquote>技術應用</blockquote><ul><li>Airtable REST API — CRUD</li><li>Result Type</li><li>關聯式資料庫</li></ul><blockquote>Model設計 — Airtable</blockquote><ul><li>DrinkType<br>維護品項的類型，後續會利用此設定檔table產生出水平換頁選擇飲料Menu的功能。（參考：<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/ios-24-%E6%90%AD%E9%85%8D%E5%8B%95%E7%95%AB%E7%9A%84%E6%B0%B4%E5%B9%B3%E6%BB%91%E5%8B%95%E5%BA%95%E7%B7%9A%E6%8C%89%E9%88%95%E8%88%87%E9%A0%81%E9%9D%A2%E6%8E%A7%E5%88%B6-f9bd34d433e1?source=your_stories_page----------------------------------------">iOS| #24 | 搭配動畫的水平滑動底線按鈕與頁面控制</a>）</li></ul><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fairtable.com%2Fembed%2FshrVMBb99zSlywTdn&amp;display_name=Airtable&amp;url=https%3A%2F%2Fairtable.com%2FshrVMBb99zSlywTdn&amp;image=https%3A%2F%2Fstatic.airtable.com%2Fimages%2Foembed%2Fairtable.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=airtable" width="800" height="533" frameborder="0" scrolling="no"><a href="https://medium.com/media/bcdb9c1abd5440cc0b370062018f7d75/href">https://medium.com/media/bcdb9c1abd5440cc0b370062018f7d75/href</a></iframe><ul><li>Menu<br>維護所有品項的資料，後續將使用此設定檔table展開所有飲料品項提供User做選擇</li></ul><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fairtable.com%2Fembed%2FshrUzHWzis01CqMpR&amp;display_name=Airtable&amp;url=https%3A%2F%2Fairtable.com%2FshrUzHWzis01CqMpR&amp;image=https%3A%2F%2Fstatic.airtable.com%2Fimages%2Foembed%2Fairtable.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=airtable" width="800" height="533" frameborder="0" scrolling="no"><a href="https://medium.com/media/650fb94c8d5728613abde6485041134c/href">https://medium.com/media/650fb94c8d5728613abde6485041134c/href</a></iframe><ul><li>OrderHeader<br>透過App維護訂單的相關的表頭資訊將會記錄在此table</li></ul><p>這邊會利用到關連式資料庫的基本觀念，將表頭存在一個table中，藉由欄位OrderNumber關聯至表身Table — OrderItem，這樣假如有多筆item的話就只需要記一筆表頭的資料就好，不需要在每一筆item都記住一樣的表頭資料。</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fairtable.com%2Fembed%2FshrIzWejNR8NeuNf6%2FtblKWDTfhSaIK9B0f&amp;display_name=Airtable&amp;url=https%3A%2F%2Fairtable.com%2FshrIzWejNR8NeuNf6%2FtblKWDTfhSaIK9B0f&amp;image=https%3A%2F%2Fstatic.airtable.com%2Fimages%2Foembed%2Fairtable.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=airtable" width="800" height="533" frameborder="0" scrolling="no"><a href="https://medium.com/media/69aa4cc7830cfa9b2ec90c20776f58c8/href">https://medium.com/media/69aa4cc7830cfa9b2ec90c20776f58c8/href</a></iframe><pre><em>備註：後續實作發現Airtable的機制並不是這麼簡單，這裡的欄位OrderNumber並不是肉眼看到的”20210215000001”，call api時會返回關聯的table欄位id的string</em></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aQhTDxHipFCWo0ClX02Ghw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1016/1*hfF7oJ9hlg3rP3hMjkWZhQ.png" /></figure><ul><li>OrderItem<br>透過App維護訂單的相關的表身資訊將會記錄在此table</li></ul><p>OrderItem — OrderNumber關聯到OrderHeader — OrderNumber<br>OrderItem — itemID關聯到Menu — itemID</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fairtable.com%2Fembed%2FshrcjEuOlieTyaRdT&amp;display_name=Airtable&amp;url=https%3A%2F%2Fairtable.com%2FshrcjEuOlieTyaRdT&amp;image=https%3A%2F%2Fstatic.airtable.com%2Fimages%2Foembed%2Fairtable.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=airtable" width="800" height="533" frameborder="0" scrolling="no"><a href="https://medium.com/media/cd22b40262d415b2293d775fb704f4c9/href">https://medium.com/media/cd22b40262d415b2293d775fb704f4c9/href</a></iframe><p>ER Model：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UOc0ZbFRSR53PVnH-bRo9g.png" /></figure><blockquote>Model設計 — Swift</blockquote><ul><li>NetWorkController<br>有關網路的功能會使用它來實作</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/981ac27db4e16fb1f91f858083899e16/href">https://medium.com/media/981ac27db4e16fb1f91f858083899e16/href</a></iframe><ul><li>Ice<br>飲料冰塊</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/43ce9738caa7a6901150794310b09d61/href">https://medium.com/media/43ce9738caa7a6901150794310b09d61/href</a></iframe><ul><li>Sugar<br>飲料甜度</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/69a9ff894e0c779a81f385b7ad6a717c/href">https://medium.com/media/69a9ff894e0c779a81f385b7ad6a717c/href</a></iframe><ul><li>Size<br>飲料尺寸</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dce7d967c755b29bbc37e67f6f49dc9b/href">https://medium.com/media/dce7d967c755b29bbc37e67f6f49dc9b/href</a></iframe><ul><li>Status<br>訂單狀態</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/552e717eaaa5d8711a5b268fed2518fe/href">https://medium.com/media/552e717eaaa5d8711a5b268fed2518fe/href</a></iframe><h4>因為以下資訊橫跨多個頁面都會用到，再加上正常情況使用下，並不會有龐大的資料量。<br>在這邊設計讓以下兩個項目作為global data活在程式裡：</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nYKq4BwNTfc3iVtzu_q84Q.png" /></figure><ul><li>Cart<br>購物車項目</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d74cfe0450d685d167f9439cc9242fb6/href">https://medium.com/media/d74cfe0450d685d167f9439cc9242fb6/href</a></iframe><ul><li>HeaderInfo<br>表頭資訊</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/77569e550c315c0d5116c05407a9f29b/href">https://medium.com/media/77569e550c315c0d5116c05407a9f29b/href</a></iframe><blockquote>功能解說＆程式解說</blockquote><ul><li><strong>Result Type</strong></li></ul><p>在說明Call API的程式以前要先了解Result Type的用法，因為實作CRUD的程式都是使用Result Type來得出結果的。</p><p>首先我們來看一小段程式：</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b47032fdeb7da2bacaae3d8e6fa3f95c/href">https://medium.com/media/b47032fdeb7da2bacaae3d8e6fa3f95c/href</a></iframe><p>FoodType為食物類別：在這邊有兩種食物，分別為MCChicken (麥脆雞)、KFCChicken (肯德基)</p><pre><strong>enum</strong> FoodType {</pre><pre><strong>case</strong> MCChicken  //麥脆雞</pre><pre><strong>case</strong> KFCChicken //肯德基</pre><pre>}</pre><p>ErrorChicken為錯誤訊息：在這邊只需要判斷是不是肯得基就好<br>屬性errorMessage是型態為String的錯誤訊息</p><pre>//error</pre><pre><strong>enum</strong> ErrorChicken: Error {</pre><pre><strong>  case</strong> isNotKFCChicken</pre><pre><strong>  var</strong> errorMessage: String {</pre><pre><strong>  switch</strong> <strong>self</strong> {</pre><pre><strong>       case</strong> .isNotKFCChicken:</pre><pre><strong>       return</strong> &quot;這不是肯德基&quot;</pre><pre>        } <br>    } <br>}</pre><p>實作function判斷是否為肯德基，並且使用Result Type。<br>若為肯德基，則使用.success回傳string；不是肯德基就使用.failure回傳error</p><pre>//判斷是不是肯德基</pre><pre><strong>func</strong> checkChicken(food: FoodType , handler: <strong>@escaping</strong> (Result&lt;String,ErrorChicken&gt;) -&gt; Void){</pre><pre><strong>   switch</strong> food{</pre><pre><strong>   case</strong> .KFCChicken:</pre><pre>   handler(.success(&quot;肯德基好吃&quot;))</pre><pre><strong>   case</strong> .MCChicken:</pre><pre>   handler(.failure(ErrorChicken.isNotKFCChicken))</pre><pre>   }</pre><pre>}</pre><p>各自宣告型態為麥脆雞、肯德基的常數</p><pre>//生出麥脆雞</pre><pre><strong>let</strong> MCchicken = FoodType.MCChicken</pre><pre>//生成肯德基</pre><pre><strong>let</strong> KFCChicken = FoodType.KFCChicken</pre><p>將前面宣告好的常數當作參數傳入function checkChicken中。<br>並且根據result判斷.success／.failure 分別要做什麼事</p><pre>checkChicken(food: MCchicken) { result <strong>in</strong></pre><pre><strong>   switch</strong> result{</pre><pre><strong>   case</strong> .success(<strong>let</strong> string):</pre><pre>   print(&quot;沒錯！\(string)&quot;)</pre><pre><strong>   case</strong> .failure(<strong>let</strong> error):</pre><pre>   print(&quot;嗚嗚嗚～\(error.errorMessage)&quot;)</pre><pre>   }</pre><pre>} <strong><em>// 結果：嗚嗚嗚～這不是肯德基</em></strong></pre><pre>checkChicken(food: KFCChicken) { result <strong>in</strong></pre><pre><strong>   switch</strong> result{</pre><pre><strong>   case</strong> .success(<strong>let</strong> string):</pre><pre>   print(&quot;沒錯！\(string)&quot;)</pre><pre><strong>   case</strong> .failure(<strong>let</strong> error):</pre><pre>   print(&quot;嗚嗚嗚～\(error.errorMessage)&quot;)</pre><pre>   }</pre><pre>} <strong><em>// 結果：沒錯！肯德基好吃</em></strong></pre><h4>可以看得出來藉由Result Type可以讓source code更有可讀性與維護性。</h4><h4>那麼接下來就說明使用 CRUD API的部分，以下範例都由Airtable － OrderHeader來做說明。</h4><ul><li><strong>讀取資料（GET）</strong></li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6128afaa7b1af3e338073a47f381fcfb/href">https://medium.com/media/6128afaa7b1af3e338073a47f381fcfb/href</a></iframe><p>先複製一份URL string</p><pre><strong>var</strong> urlStringWithCondition = urlString<br></pre><p>幫url String加上where條件。（某些特別符號或中文URL可能會認不得，所以記得要使用addingPercentEncoding轉換成URL認得的格式。）</p><p>注意：在這邊使用了Airtable的function “SEARCH”，可以搜尋特定欄位的特定資料。詳情請參考<a href="https://support.airtable.com/hc/en-us/articles/203255215-Formula-Field-Reference">官方文件</a></p><pre><strong>if</strong> <strong>let</strong> field = condition.field,</pre><pre><strong>let</strong> value = condition.value{</pre><pre> urlStringWithCondition = urlStringWithCondition +      &quot;&amp;filterByFormula=&quot; + &quot;SEARCH(\&quot;\(value)\&quot;,{\ (field)})&quot;.addingPercentEncoding(withAllowedCharacters:  .urlQueryAllowed)!</pre><pre>}</pre><p>將string轉換成URL，若失敗的話則丟出Error</p><pre><strong>guard</strong> <strong>let</strong> url = URL(string: urlStringWithCondition) <strong>else</strong> {</pre><pre>completion(.failure(.invalidurl))</pre><pre><strong>return</strong> }</pre><p>產生data task上網抓資料</p><pre>URLSession.shared.dataTask(with: url) { data, response, error <strong>in</strong></pre><pre>   <strong>抓資料程式</strong></pre><pre>}.resume()</pre><p>檢查是否有錯誤，若有錯誤的話則丟出Error</p><pre><strong>if</strong> <strong>let</strong> error = error {</pre><pre>completion(.failure(.requestFailed))</pre><pre><strong>return</strong></pre><pre>}</pre><p>檢查status是否為OK，若失敗的話則丟出Error</p><pre><strong>guard</strong> <strong>let</strong> httpResponse = response <strong>as</strong>? HTTPURLResponse,</pre><pre>httpResponse.statusCode == 200</pre><pre><strong>else</strong> {</pre><pre>completion(.failure(.invalidResponse))</pre><pre><strong>return</strong></pre><pre>}</pre><p>檢查是否有抓到資料，若失敗的話則丟出Error</p><pre><strong>guard</strong> <strong>let</strong> data = data</pre><pre><strong>else</strong> {</pre><pre>completion(.failure(.invalidData))</pre><pre><strong>return</strong></pre><pre>}</pre><p>解析JSON格式的資料，若失敗的話則丟出Error</p><pre><strong>let</strong> decoder = JSONDecoder()</pre><pre><strong>guard</strong> <strong>let</strong> orderHeader = <strong>try</strong>? decoder.decode(OrderHeader.<strong>self</strong>, from: data)</pre><pre><strong>else</strong> {</pre><pre>completion(.failure(.invalidJsonFormat))</pre><pre><strong>return</strong>  }</pre><p>前面都成功的話就會走到這一步，最後將解析完的資料透過.success傳出去</p><pre>completion(.success(orderHeader))</pre><ul><li><strong>新增資料（POST）</strong></li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9fc74271c3a497fe51db45cf55e3f59d/href">https://medium.com/media/9fc74271c3a497fe51db45cf55e3f59d/href</a></iframe><h4>可以看得出來與讀取資料的程式十分雷同，接下來將會說明差異的地方，其餘相同部分不再贅述。</h4><p>建立request</p><pre><strong>var</strong> request = URLRequest(url: url)</pre><p>設好httpMethod</p><pre>request.httpMethod = &quot;POST&quot;</pre><p>給api所需的http Header值（建立好table後在<a href="https://airtable.com/api">官方文件</a>裡看找到curl，就可以利用它來知道要填哪些資訊）</p><pre>request.setValue(&quot;Bearer \(NetWorkController.apikey)&quot;, forHTTPHeaderField: &quot;Authorization&quot;)</pre><pre>request.setValue(&quot;application/json&quot;, forHTTPHeaderField: &quot;Content-Type&quot;)</pre><p>將組好的資料轉為JSON格式，並把值pass給http body</p><pre><strong>let</strong> encoder = JSONEncoder()</pre><pre><strong>let</strong> data = <strong>try</strong>? encoder.encode(orderHeader)</pre><pre>request.httpBody = data</pre><p>其餘部分可以參考上述<strong>讀取資料</strong>的說明。</p><ul><li><strong>修改資料（PATCH）</strong></li></ul><p>首先要了解PATCH、PUT都是跟Update Table有關的method，根據官方文件說明：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J61iBPOVP5V7-_sMNOYhBQ.png" /></figure><p>濃縮內容大致上為使用PATCH只會更改指定的fields；使用PUT會將指定的fields以外的欄位都清空。</p><h4>只透過文字說明可能還是會有一些理解上的困難，我們來看看下述例子吧！</h4><p>首先我們以訂單編號“20220226000002”為例子。</p><p>使用PATCH更新資料，將欄位totalPrice改為100。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QTE1xRjszV0X9otLbMyqDQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A5oHP3aNV63Zl3bAwciNXg.png" /></figure><p>使用PUT更新資料，將欄位totalPrice改為125。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/988/1*o-13QLlADWA5FMuW-xZ17w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t8789W6objuM3j-nLi91vg.png" /></figure><p>以上例子來看感覺沒有什麼差異，這是因爲我們同時有指定其他的fields，以下我們試看看在body只指定totalPrice與id：</p><p>使用PATCH更新資料，將欄位totalPrice改為100。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/702/1*r9CACkLVcjKVZ_FlvcmuLQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*03vHXGEuh2tNhIzaFegVDA.png" /></figure><p>使用PUT更新資料，將欄位totalPrice改為125。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/828/1*AG1Aq3rX5688K-luZb3BWA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HSUSmsbpXgeYSAdSIV0TfA.png" /></figure><p>可以明顯地看到使用PUT的話，totalPrice一樣成功被修改了，但由於其他欄位沒有被指定的關係，會全部被清空。<br><strong><em>備註：createdTime是因為欄位屬性本身就會自動產生值，所以沒有被清空。</em></strong></p><p>為了避免資料被清空，在這邊我們使用<strong>PATCH</strong>來修改訂單。</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/24705c72935b379cd8cd95646060b4b6/href">https://medium.com/media/24705c72935b379cd8cd95646060b4b6/href</a></iframe><h4>可以看得出來與新增資料的程式更是如出一徹，差別只在於httpMethod改為PATCH。</h4><pre>request.httpMethod = &quot;PATCH&quot;</pre><p>其餘部分可以參考上述<strong>新增資料</strong>的說明。</p><ul><li><strong>刪除資料（DELETE）</strong></li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7bf0456e5afdf79d74975c13c9f6a981/href">https://medium.com/media/7bf0456e5afdf79d74975c13c9f6a981/href</a></iframe><h4>可以看得出來與修改資料的程式非常相似，接下來將會說明差異的地方，其餘相同部分不再贅述</h4><p>組query string（在這邊只考慮刪除單筆的情況），可以參考官方文件給的範例</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UsQZPZX-uGMvUWRZrAqKIQ.png" /></figure><pre><strong>var</strong> urlStringWithCondition = urlString + &quot;?records[]=\(id)&quot;</pre><p>httpMethod改為DELETE</p><pre>request.httpMethod = &quot;DELETE&quot;</pre><p><em>系列文章：</em></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%E6%95%99%E5%AE%A4/ios-25-%E7%B4%84%E7%BF%B0%E7%B4%85%E8%8C%B6%E8%A8%82%E9%A4%90app2-0-%E6%88%90%E6%9E%9C%E5%B1%95%E7%A4%BA-142be05a5579">iOS| #25 | 約翰紅茶訂餐App2.0 成果展示</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%E6%95%99%E5%AE%A4/ios-25-%E7%B4%84%E7%BF%B0%E7%B4%85%E8%8C%B6%E8%A8%82%E9%A4%90app-2-0-part-1-%E4%B8%B2%E6%8E%A5airtable-api-e5a7e2b9e8d6">iOS| #25 | 約翰紅茶訂餐App 2.0–Part.1 串接Airtable API</a></li><li><a href="https://medium.com/@tommy5566123/ios-25-%E7%B4%84%E7%BF%B0%E7%B4%85%E8%8C%B6%E8%A8%82%E9%A4%90app-2-0-part-2-%E9%BB%9E%E9%A4%90%E8%88%87%E8%B3%BC%E7%89%A9%E8%BB%8A%E7%AF%87-42c578620922">iOS| #25 | 約翰紅茶訂餐App 2.0–Part.2 點餐與購物車篇</a></li><li><a href="https://medium.com/@tommy5566123/ios-25-%E7%B4%84%E7%BF%B0%E7%B4%85%E8%8C%B6%E8%A8%82%E9%A4%90app-2-0-part-3-%E9%80%81%E5%87%BA%E8%A8%82%E5%96%AE%E8%88%87%E4%BF%AE%E6%94%B9%E8%A8%82%E5%96%AE-65314e315cc4">iOS| #25 | 約翰紅茶訂餐App 2.0–Part.3 送出訂單與修改訂單</a></li></ul><p><em>GitHub：</em></p><p><a href="https://github.com/tommy6457/DrinkOrder">GitHub - tommy6457/DrinkOrder</a></p><p><em>參考資料：</em></p><ul><li><a href="https://medium.com/%E5%BD%BC%E5%BE%97%E6%BD%98%E7%9A%84%E8%A9%A6%E7%85%89-%E5%8B%87%E8%80%85%E7%9A%84-100-%E9%81%93-swift-ios-app-%E8%AC%8E%E9%A1%8C/%E4%BD%A0%E5%87%BA%E5%8A%9B%E5%AF%AB-app-%E6%88%91%E5%87%BA%E9%8C%A2%E8%AB%8B%E9%A3%B2%E6%96%99-6a9ac14a2a22">#20 訂飲料 App，上傳資料到後台</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/%E6%88%90%E5%8A%9F%E5%92%8C%E5%A4%B1%E6%95%97%E4%BA%8C%E6%93%87%E4%B8%80%E7%9A%84-result-type-e234c6fccc9c">成功和失敗二擇一的 Result type</a></li></ul><p>若內容有誤煩請指教，感謝收看。</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e5a7e2b9e8d6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/peter-pan-swift-ios-class/ios-25-%E7%B4%84%E7%BF%B0%E7%B4%85%E8%8C%B6%E8%A8%82%E9%A4%90app-2-0-part-1-%E4%B8%B2%E6%8E%A5airtable-api-e5a7e2b9e8d6">iOS| #25 | 約翰紅茶訂餐App 2.0–Part.1 串接Airtable API</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[iOS| #25 | 約翰紅茶訂餐App2.0 成果展示]]></title>
            <link>https://medium.com/peter-pan-swift-ios-class/ios-25-%E7%B4%84%E7%BF%B0%E7%B4%85%E8%8C%B6%E8%A8%82%E9%A4%90app2-0-%E6%88%90%E6%9E%9C%E5%B1%95%E7%A4%BA-142be05a5579?source=rss-dcc5ce982008------2</link>
            <guid isPermaLink="false">https://medium.com/p/142be05a5579</guid>
            <category><![CDATA[swift-programming]]></category>
            <dc:creator><![CDATA[Tommy]]></dc:creator>
            <pubDate>Fri, 04 Mar 2022 09:31:37 GMT</pubDate>
            <atom:updated>2022-04-13T07:41:58.783Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*evxv_tXqyjyOnKF75aYgkA.png" /></figure><p>不久前已經實作過訂飲料App初版，那麼這次要利用目前所學的技能將其升級為2.0，並且加上數個功能使其成為一個更完整的產品。</p><h4>本文將會展示此專案App的各項功能，技術文章將會陸續更新。</h4><blockquote>由於此系列文篇幅會較長，會拆分成多篇文章紀錄實作的過程與功能講解</blockquote><p>約翰紅茶的煮濃那提一直是我到現在為止心目中排名第一的奶茶，從內湖店一路喝到南港店，甚至信義店開幕後幾乎每週都至少喝兩次以上。那麼這次我就再來致敬第二次約翰紅茶，製作訂飲料App2.0吧！</p><blockquote>前情提要</blockquote><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/ios-14-1-%E7%B4%84%E7%BF%B0%E7%B4%85%E8%8C%B6%E9%BB%9E%E9%A4%90app%E5%88%9D%E7%89%88-part-1-menu%E7%AF%87-8bf5b3cf3c57?source=your_stories_page----------------------------------------">iOS| #14–1 | 約翰紅茶點餐App初版 part 1. MENU篇</a></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/ios-14-2-%E7%B4%84%E7%BF%B0%E7%B4%85%E8%8C%B6%E9%BB%9E%E9%A4%90app%E5%88%9D%E7%89%88-part-2-%E8%B3%87%E6%96%99%E5%82%B3%E9%81%9E%E8%88%87detail%E9%A0%81%E9%9D%A2%E7%AF%87-150a8be4d3b0?source=your_stories_page----------------------------------------">iOS| #14–2 | 約翰紅茶點餐App初版 part 2. 資料傳遞與Detail頁面篇</a></p><blockquote>成果展示</blockquote><ul><li><strong>Log In 畫面 ＆取件人資料輸入<br>（登入功能目前規劃只要輸入任意使用者名稱即可，正式登入功能會在後續找時間補上）</strong></li></ul><pre><strong>2022/04/13： 新增註冊、登入功能。原Log In畫面已廢除並增加卡控。</strong></pre><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FiVlyALyMDn8%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DiVlyALyMDn8&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FiVlyALyMDn8%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/15a42793628f40c33553b9d076695c66/href">https://medium.com/media/15a42793628f40c33553b9d076695c66/href</a></iframe><ul><li><strong>註冊功能（2022/04/13新增）</strong></li></ul><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FGBSDdncXN9c%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DGBSDdncXN9c&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FGBSDdncXN9c%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/7d210dc7d635c0ad9b9884df5970a473/href">https://medium.com/media/7d210dc7d635c0ad9b9884df5970a473/href</a></iframe><ul><li><strong>登入帳號（2022/04/13新增）</strong></li></ul><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FDtq0m57_7uU%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DDtq0m57_7uU&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FDtq0m57_7uU%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/498aa6e49eb3034d45194b8bc4c026af/href">https://medium.com/media/498aa6e49eb3034d45194b8bc4c026af/href</a></iframe><ul><li><strong>點餐加入購物車</strong></li></ul><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FvEiXYsFB1wA%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DvEiXYsFB1wA&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FvEiXYsFB1wA%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/021ba85cf97bf7f665290aa22e0f4c76/href">https://medium.com/media/021ba85cf97bf7f665290aa22e0f4c76/href</a></iframe><ul><li><strong>送出訂單</strong></li></ul><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FpmIUn1w8XY4%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DpmIUn1w8XY4&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FpmIUn1w8XY4%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/de21f240042c7a60cae00549364f550c/href">https://medium.com/media/de21f240042c7a60cae00549364f550c/href</a></iframe><ul><li><strong>查詢歷史訂單</strong></li></ul><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FCEnvoHpYGTI%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DCEnvoHpYGTI&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FCEnvoHpYGTI%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/60780030c3159d77d9db0d5514e54104/href">https://medium.com/media/60780030c3159d77d9db0d5514e54104/href</a></iframe><ul><li><strong>修改訂單</strong></li></ul><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FDF70CZZOAHo%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DDF70CZZOAHo&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FDF70CZZOAHo%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/b2fd5d48803300972099d406bf807179/href">https://medium.com/media/b2fd5d48803300972099d406bf807179/href</a></iframe><ul><li><strong>取消訂單</strong></li></ul><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F2R0gUKCTp-w%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D2R0gUKCTp-w&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F2R0gUKCTp-w%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/bf23306f940085fad980dc0c3bd5b236/href">https://medium.com/media/bf23306f940085fad980dc0c3bd5b236/href</a></iframe><ul><li><strong>刪除訂單</strong></li></ul><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FfXbcUL8mkLQ%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DfXbcUL8mkLQ&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FfXbcUL8mkLQ%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/9e1a5644301e3833ac640c9e7556817a/href">https://medium.com/media/9e1a5644301e3833ac640c9e7556817a/href</a></iframe><p><em>系列文章：</em></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%E6%95%99%E5%AE%A4/ios-25-%E7%B4%84%E7%BF%B0%E7%B4%85%E8%8C%B6%E8%A8%82%E9%A4%90app2-0-%E6%88%90%E6%9E%9C%E5%B1%95%E7%A4%BA-142be05a5579">iOS| #25 | 約翰紅茶訂餐App2.0 成果展示</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%E6%95%99%E5%AE%A4/ios-25-%E7%B4%84%E7%BF%B0%E7%B4%85%E8%8C%B6%E8%A8%82%E9%A4%90app-2-0-part-1-%E4%B8%B2%E6%8E%A5airtable-api-e5a7e2b9e8d6">iOS| #25 | 約翰紅茶訂餐App 2.0–Part.1 串接Airtable API</a></li><li><a href="https://medium.com/@tommy5566123/ios-25-%E7%B4%84%E7%BF%B0%E7%B4%85%E8%8C%B6%E8%A8%82%E9%A4%90app-2-0-part-2-%E9%BB%9E%E9%A4%90%E8%88%87%E8%B3%BC%E7%89%A9%E8%BB%8A%E7%AF%87-42c578620922">iOS| #25 | 約翰紅茶訂餐App 2.0–Part.2 點餐與購物車篇</a></li><li><a href="https://medium.com/@tommy5566123/ios-25-%E7%B4%84%E7%BF%B0%E7%B4%85%E8%8C%B6%E8%A8%82%E9%A4%90app-2-0-part-3-%E9%80%81%E5%87%BA%E8%A8%82%E5%96%AE%E8%88%87%E4%BF%AE%E6%94%B9%E8%A8%82%E5%96%AE-65314e315cc4">iOS| #25 | 約翰紅茶訂餐App 2.0–Part.3 送出訂單與修改訂單</a></li></ul><p><em>GitHub：</em></p><p><a href="https://github.com/tommy6457/DrinkOrder.git">GitHub - tommy6457/DrinkOrder</a></p><p><em>參考資料：</em></p><ul><li><a href="https://medium.com/%E5%BD%BC%E5%BE%97%E6%BD%98%E7%9A%84%E8%A9%A6%E7%85%89-%E5%8B%87%E8%80%85%E7%9A%84-100-%E9%81%93-swift-ios-app-%E8%AC%8E%E9%A1%8C/%E4%BD%A0%E5%87%BA%E5%8A%9B%E5%AF%AB-app-%E6%88%91%E5%87%BA%E9%8C%A2%E8%AB%8B%E9%A3%B2%E6%96%99-6a9ac14a2a22">#20 訂飲料 App，上傳資料到後台</a></li><li><a href="https://www.facebook.com/johnteacompany?locale=zh_TW">約翰紅茶公司</a></li></ul><p>若內容有誤煩請指教，感謝收看。</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=142be05a5579" width="1" height="1" alt=""><hr><p><a href="https://medium.com/peter-pan-swift-ios-class/ios-25-%E7%B4%84%E7%BF%B0%E7%B4%85%E8%8C%B6%E8%A8%82%E9%A4%90app2-0-%E6%88%90%E6%9E%9C%E5%B1%95%E7%A4%BA-142be05a5579">iOS| #25 | 約翰紅茶訂餐App2.0 成果展示</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>