<?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/@laijw4403?source=rss-70a85a72b783------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*_b9S16q_oc1D1v7556dz1A.jpeg</url>
            <title>Stories by Tommy on Medium</title>
            <link>https://medium.com/@laijw4403?source=rss-70a85a72b783------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 14:20:04 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@laijw4403/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[測試左移與右移]]></title>
            <link>https://laijw4403.medium.com/%E6%B8%AC%E8%A9%A6%E5%B7%A6%E7%A7%BB%E8%88%87%E5%8F%B3%E7%A7%BB-cfbb38954808?source=rss-70a85a72b783------2</link>
            <guid isPermaLink="false">https://medium.com/p/cfbb38954808</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[shift-left-testing]]></category>
            <dc:creator><![CDATA[Tommy]]></dc:creator>
            <pubDate>Sat, 18 May 2024 09:04:36 GMT</pubDate>
            <atom:updated>2024-05-18T09:04:36.140Z</atom:updated>
            <content:encoded><![CDATA[<p>近期看到文章中提到「Shift Left」的名詞，好奇的研究了一下這個概念，也跟幾位開發工程師和測試工程師討論了一下，這篇文章用來記錄這次學到的一些東西，如果有理解錯誤的地方，還請不吝指正。</p><h3>要解決的問題</h3><p>在傳統的軟體開發生命週期(SDLC)中，測試環節在開發完畢後才開始進行，可能會導致一些不得不修改的Bug到了這時候才發現，而這時候Debug的時程壓力就會非常大，難免有些疏漏，甚至無法顧及程式碼品質先趕鴨子上架再說。</p><p>有個做測試的朋友分享了他的經驗，他曾經在測試時才發現工程師開發的功能與需求幾乎不符，而這時才發現這個問題相當頭痛，也需要付出額外的時間修改甚至要打掉重練，若能提早發現就能避免問題繼續擴大。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/925/0*n2DlNYoYmePqvtBS.png" /><figcaption><a href="https://productcoalition.com/a-comprehensive-guide-to-the-software-development-life-cycle-sdlc-15b7892e1d44">軟體開發生命週期(SDLC)</a></figcaption></figure><h3>左移測試 (Shift left testing)</h3><p>強調在SDLC的早期進行測試活動，而不是等到最後階段，是一種主動測試的方法，越早發現問題可以越早解決，降低未來發現問題的修復成本，並提升產品的品質。</p><h3>如何進行</h3><p>團隊需要對產品效能、客戶需求及使用者期望做透徹的研究。</p><p>以及QA Team和Dev Team：</p><h4>QA Team</h4><ul><li>在開發前的規劃階段就請QA參與，以了解需求並設計測試案例</li><li>參與介面與架構設計階段</li><li>在考慮可測試性的情況下給予Coding的建議</li></ul><h4>Dev Team</h4><ul><li>導入自動化測試如單元測試、整合測試</li><li>API測試</li><li>Code Review</li><li>CI / CD</li><li>測試驅動開發(TDD)</li><li>行為驅動開發(BDD)</li></ul><h3>右移測試 (Shift right testing)</h3><p>在產品上線後才進行測試活動，主要關注在線上環境中的監控與回饋，深入瞭解解可用性與使用者體驗，以提升使用者體驗與線上產品穩定。</p><h4>灰度測試和A/B測試</h4><p>用來確定使用者偏好哪一個版本</p><h4>金絲雀測試</h4><p>只讓少部分使用者當白老鼠^_^</p><h3>兩者是否能同時進行呢?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/696/0*pnEFCuxJ0WxnDcrU.png" /><figcaption><a href="https://www.encora.com/insights/shift-left-and-shift-right-in-software-testing">Shift left and shift right</a></figcaption></figure><p>Shift left和Shift right並不互相衝突，兩者相輔相成</p><p>左移可以更有效地促進開發人員和測試人員之間的協作</p><p>右移有助於縮小測試人員、開發人員與維運團隊之間的差距</p><h3>目前團隊的作法</h3><p>我們是用Scrum來實現敏捷開發的團隊，由於目前沒有測試工程師，所以測試工作都是由開發工程師兼任。</p><ol><li>Design Sprint由工程師與UI/UX設計師一起進行設計，所以有參與設計的工程師都清楚客戶需求與使用者的期望。</li><li>開發階段通常是由原本參與設計的工程師進行開發，Spec文件也是由工程師撰寫，最後會再跟PO和所有DT成員確認有沒有遺漏。</li><li>開發時撰寫單元測試，有些工程師甚至用TDD的方式進行</li><li>開發完成後進行Code Review</li><li>後端和網頁端有跑CI / CD的流程 (APP目前還沒有)</li><li>接著再由團隊內的工程師依照Spec進行測試</li></ol><p>在我了解測試左移之後才發現原來我們團隊一直都在實踐這個概念，但常常還是覺得到了測試的時候有些瓶頸的感覺，需要花蠻多時間進行人工測試，而且通常也都是到了Sprint最後幾天，也還是有點時程壓力。</p><p>不知道有沒有其他團隊也遇到相同問題？又是如何解決的呢？如果可以的話，可以和我分享你們團隊的做法嗎？</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cfbb38954808" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[[iOS Notes]-AutoLayout Programmatically]]></title>
            <link>https://laijw4403.medium.com/ios-notes-autolayout-programmatically-8595370fc1e2?source=rss-70a85a72b783------2</link>
            <guid isPermaLink="false">https://medium.com/p/8595370fc1e2</guid>
            <category><![CDATA[programmatically]]></category>
            <category><![CDATA[autolayout]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[notes]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Tommy]]></dc:creator>
            <pubDate>Thu, 08 Apr 2021 17:36:23 GMT</pubDate>
            <atom:updated>2021-04-08T17:37:03.166Z</atom:updated>
            <content:encoded><![CDATA[<h3>[iOS Notes]-Auto Layout Programmatically</h3><h4>紀錄學習Auto Layout Programmatically的筆記</h4><h4>重點</h4><ul><li>.translatesAutoresizingMaskIntoConstraints<br>為使用自己設定的約束條件，需將此屬性設定為false，阻止iOS自動創建約束條件。</li><li>計算約束條件的公式 :目標視圖的屬性 = 引用視圖的屬性*倍數+常數<br>ex. subView.heightAnchor.constraint(equalTo: view.heightAnchor, multiplier: 0.5, constant: 10)<br>上述範例意指subView的高 = superView的高*0.5+10</li></ul><h4>設定Auto Layout的3個方式</h4><ol><li><strong>NSLayoutAnchor (<em>iOS 9.0)</em></strong><br>ex. subView.centerXAnchor.constraint(equalTo: view.leadingAnchor, constant: 0)</li><li><strong>NSLayoutConstraint(item:attribute:…) <em>(iOS 6.0)</em></strong></li><li><strong>VFL <em>(iOS 6.0)</em></strong></li></ol><h4>啟動約束條件的3個方式</h4><pre>// 設定一約束條件為 centerHorizontally，後續3啟動方式將以此作為範例<br>let centerHorizontally = NSLayoutConstraint(item: myView, attribute: .centerX, relatedBy: .equal, toItem: view, attribute: .centerX, multiplier: 1, constant: 0)</pre><ol><li><strong>.addConstraint() <br></strong>此方法為UIView Class的函式，使用此方法將約束條件直接加入super view。<strong>(需注意使用此方法時必須將約束條件添加到目標視圖與引用視圖的第一個共同super view)</strong><br><em>ex. view.addConstraint(centerHorizontally)</em></li><li><strong>NSLayoutConstraint.activate() <br></strong>此方法為NSLayoutConstraint Class的類別函式，使用此方法可一次啟動多個約束條件，參數為一陣列，可放入多個約束條件。<br><em>ex. NSLayoutConstraint.activate([centerHorizontally])</em></li><li><strong>.isActive <br></strong>將此屬性設定為true即可啟動約束條件。<br><em>ex. centerHorizontally.isActive = true</em></li></ol><h3>The Visual Format Language(VFL)</h3><blockquote><em>一種在視圖之間創建約束的</em><strong><em>描述性</em></strong><em>方法</em></blockquote><h4>建立描述約束條件之字串物件</h4><pre>let leftDist: CGFloat = 150.0<br>let rightDist: CGFloat = 25.0<br>let descHorizontal = “H:|-distanceLeft-[containerView1]-distanceRight-|”<br>let descVertical = &quot;V:|-20-[containerView1(100)]&quot;</pre><p>上述變數為一字串，其中<br><strong>”H:” — </strong>表示設定水平的約束條件<br><strong>”V:” — </strong>表示設定垂直的約束條件<br><strong>“|” — 表示</strong>super view，在左側則代表對應super view的左側(可看做leading)<br><strong>“-” — </strong>表示兩視圖間的距離<br><strong>“20” — </strong>意指super view左側至containerView1左側的距離為20points<br><strong>“[containerView1]” — </strong>此[]內為目標視圖名稱，在此目標視圖為containerView1，需注意[]內可為任意字串，後續會將目標視圖名稱與實際視圖連結<br><strong>“(200)”</strong> — 此()內的數字為宣告width，於”V:”則是宣告height</p><h4>連結目標視圖名稱與實際視圖、數值常數</h4><pre>let viewsDict = [&quot;containerView1&quot;: containerView1]</pre><p>創建Dictionary裡將目標視圖名稱設為Key，並與實際視配對</p><pre>let metrics = [&quot;distanceLeft&quot;: leftDist,<br>               &quot;distanceRight&quot;: rightDist]</pre><p>類似連結目標視圖名稱與實際視圖，將”distanceLeft”與實際值配對</p><h4>創建實際約束條件</h4><pre>let horizontalConstraints = NSLayoutConstraint.constraints(withVisualFormat: descHorizontal, options: .alignAllCenterY, metrics: metrics, views: viewsDict)</pre><p>使用NSLayouConstraint Class的方法constraints(withVisualFormat:)，將回傳約束條件的陣列。</p><p><strong>withVisualFormat : </strong>將描述約束條件之字串傳入此參數<strong><br>options: </strong>設置引用視圖間的對齊方式<strong><br>metrics: </strong>傳入描述VFL字串中的數值常數Dictionary<br><strong>views</strong>: 傳入描述VFL字串中的view變數Dictionary</p><h3>Stack View (iOS 9.0)</h3><p>適用於間距固定、較為規則的layout</p><ul><li><strong>將視圖加入StackView</strong><br>UIStackView(arrangedSubviews: [subView1, subView2, subView3])</li><li><strong>axis 屬性(預設為horizontal，可更改為vertical)</strong><br>設定軸線(subView的排列方式，可為水平排列或垂直排列)</li><li><strong>distribution屬性</strong>(預設為fill)<br>設定子視圖該如何分佈(fill、fillEqually、fillProportionally、equalSpacing、equalCentering)<br>各種分布選項詳細說明可參考以下資料</li></ul><p><a href="https://spin.atomicobject.com/2016/06/22/uistackview-distribution/">Exploring the 5 UIStackView Distribution Types for iOS Dev</a></p><h4>參考資料</h4><ul><li><a href="https://www.appcoda.com.tw/auto-layout-programmatically/">Auto Layout學習指南：利用Visual Format Language和程式碼設定約束畫面佈局</a></li><li><a href="https://denkeni.medium.com/%E7%B4%94%E7%A8%8B%E5%BC%8F%E7%A2%BC-auto-layout-%E8%88%87%E6%A6%82%E8%A6%81%E6%95%99%E5%AD%B8-%E4%B8%80-6077dd73dd3f">純程式碼 Auto Layout 與概要教學（一）</a></li></ul><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F9RydRg0ZKaI%3Flist%3DPL0dzCUj1L5JHdeOlzJtp5zlsdrliJTC7F&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D9RydRg0ZKaI&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F9RydRg0ZKaI%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/37c7ad8105e092c47f54c58c89d22d13/href">https://medium.com/media/37c7ad8105e092c47f54c58c89d22d13/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8595370fc1e2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[[iOS Task]-Sign in & Sign up#1]]></title>
            <link>https://medium.com/peter-pan-swift-ios-class/ios-task-sign-in-sign-up-1-cd642463e8be?source=rss-70a85a72b783------2</link>
            <guid isPermaLink="false">https://medium.com/p/cd642463e8be</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[login]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Tommy]]></dc:creator>
            <pubDate>Wed, 10 Feb 2021 13:38:30 GMT</pubDate>
            <atom:updated>2021-02-25T12:36:18.870Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*VF_hamxdH3nwRCJ0" /><figcaption>Photo by <a href="https://unsplash.com/@firmbee?utm_source=medium&amp;utm_medium=referral">William Iven</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>利用okta帳號管理API實現註冊與登入功能</h4><p><strong>現代人的日常生活中與手機息息相關，各種手機APP都會要求使用者註冊與登入，使用者也可以在其中設定自己的個人資訊，也希望自己有能力完成這些功能！</strong></p><h4><strong>本篇實作功能：使用者登入、註冊、修改個人資訊</strong></h4><blockquote><strong><em>畫面參考</em></strong></blockquote><p>從Mobbin網站參考TED APP 登入註冊畫面</p><p><a href="https://mobbin.design/apps/ted">Mobbin - Latest Mobile Design Patterns</a></p><p><strong>實作畫面</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/583/1*PKKHR6dKqlSvVHo9YT8Fbg.png" /></figure><blockquote><strong><em>登入 </em>Sign in</strong></blockquote><p><strong>登入畫面</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/318/1*OW5wuZAJYx1-2hJPUZySBg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/360/1*8MsjbvOooBKQ1RQiG1T8qA.png" /><figcaption>左圖為storyboard畫面，右圖為模擬器畫面</figcaption></figure><p>上圖黃色View的部分為Xib畫面(稍微練習一下)，畫面如下</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/384/1*prcPaNtiHnDiaPvIk5ajtQ.png" /><figcaption>Email Sign-in View</figcaption></figure><p>從storyboard 加入 xib View的方法可參考彼得潘的文章</p><p><a href="https://medium.com/%E5%BD%BC%E5%BE%97%E6%BD%98%E7%9A%84-swift-ios-app-%E9%96%8B%E7%99%BC%E5%95%8F%E9%A1%8C%E8%A7%A3%E7%AD%94%E9%9B%86/%E5%9C%A8-storyboard-%E5%8A%A0%E5%85%A5-xib-%E7%9A%84-view-e94826a7a8f3">在 storyboard 加入 xib 的 view</a></p><p><strong>使用者輸入email後，按下Continue判斷email格式是否正確</strong></p><p>由於email登入畫面由Xib製作，為控制畫面必須在自訂Class(EmailSignInView)中實作。</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dc548dcf178e3ac9c3d51c5ddbebf3dc/href">https://medium.com/media/dc548dcf178e3ac9c3d51c5ddbebf3dc/href</a></iframe><pre><strong>var</strong> delegate: LoginViewController?</pre><p>由於此畫面嵌入LoginViewController，為呼叫Controller才有的func present()，因此將delegate設定為LoginViewController</p><p><strong>取得使用者輸入的email：</strong>於自訂class建立textField IBOutlet，使用.text屬性</p><p><strong>判斷email格式：</strong>使用正則表達式判斷</p><pre>func validateEmail(email: String) -&gt; Bool {<br>        if email.count == 0 {<br>            return false<br>        }<br>        let emailPattern = &quot;^([a-z0-9]+(?:[._-][a-z0-9]+)*)@([a-z0-9]+(?:[.-][a-z0-9]+)*\\.[a-z]{2,3})$&quot;<br>        let emailRegular = try! NSRegularExpression(pattern: emailPattern, options: .caseInsensitive)<br>        let result = emailRegular.matches(in: email, range: NSMakeRange(0, (email as NSString).length))<br>        guard result.count &gt; 0 else {<br>            return false<br>        }<br>        return true<br>    }</pre><p>推薦一個可以測試Regular expressions的網站</p><p><a href="https://regex101.com/">regex101: build, test, and debug regex</a></p><p>若判斷email格式不符合則顯示提示訊息告知使用者</p><pre>func showAleart(message: String) {<br>        print(message)<br>        let alertController = UIAlertController(title: &quot;&quot;, message: message, preferredStyle: .alert)<br>        let okAction = UIAlertAction(title: &quot;OK&quot;, style: .default, handler: nil)<br>        alertController.addAction(okAction)<br>        present(alertController, animated: true, completion: nil)<br>    }</pre><p>符合email格式則present Sign up畫面，並傳遞email的值</p><pre>let controller = storyboard.instantiateViewController(identifier: &quot;\(EmailSignUpViewController.self)&quot;) as EmailSignUpViewController<br>            controller.email = email<br>            <br>            delegate.present(controller, animated: true, completion: {<br>                print(&quot;present success&quot;)<br>            })</pre><blockquote><strong><em>註冊 </em>Sign up</strong></blockquote><p><strong>註冊畫面</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/356/1*00alyBqNVUkWncwRLCa41A.png" /></figure><p><strong>儲存使用者照片</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/40e411f377467861d85e60bf27d05488/href">https://medium.com/media/40e411f377467861d85e60bf27d05488/href</a></iframe><p>實作此func決定選擇完照片後要做的事</p><pre><strong>func</strong> imagePickerController(<strong>_</strong> picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : <strong>Any</strong>])</pre><ul><li><strong>縮小圖片</strong></li></ul><pre>// 縮小圖片<br>    func resizeImage(image: UIImage, width: CGFloat) -&gt; UIImage {<br>        // 設定縮小後的圖片尺寸<br>        let size = CGSize(width: width, height: image.size.height * width / image.size.width)<br>        // 生成GraphicsImageRenderer物件，設定繪製圖片大小<br>        let renderer = UIGraphicsImageRenderer(size: size)<br>        // 呼叫func image(actions:)產生縮小的UIImage<br>        let newImage = renderer.image { (context) in<br>            // 繪製圖片<br>            image.draw(in: renderer.format.bounds)<br>        }<br>        return newImage<br>    }</pre><ul><li><strong>儲存圖片至使用者的document資料夾</strong></li></ul><pre>// 將圖片儲存至document資料夾<br>    func storeImage(image: UIImage, name: String, compressionQuality: CGFloat) {<br>        let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!<br>        let url = documentsDirectory.appendingPathComponent(name).appendingPathExtension(&quot;jpg&quot;)<br>        do {<br>            print(&quot;store image success&quot;)<br>            try image.jpegData(compressionQuality: compressionQuality)?.write(to: url)<br>        } catch  {<br>            print(&quot;store image fail&quot;)<br>        }<br>    }</pre><p>取得使用者的document資料夾，urls(for:in:)取得urls陣列，需用.first取得第一個url(https://medium.com/%E5%85%B6%E5%AF%A6%E4%B9%9F%E5%8F%AA%E6%9C%89%E4%B8%80%E5%80%8B)</p><pre>let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!</pre><p>加入檔名(appendingPathComponent)與副檔名(appendingPathExtension)，並組合url</p><pre>documentsDirectory.appendingPathComponent(name).appendingPathExtension(&quot;jpg&quot;)</pre><p>將圖片轉成jpg格式的Data型別(可透過compressionQuality參數壓縮大小)，並寫入至指定的url</p><pre>try image.jpegData(compressionQuality: compressionQuality)?.write(to: url)</pre><ul><li><strong>上傳圖片至imgur並取得圖片url(https://medium.com/%E4%BD%BF%E7%94%A8Result%20type)</strong></li></ul><pre>func uploadImage(uiImage: UIImage, completion: <a href="http://twitter.com/escaping">@escaping</a> (Result&lt;URL,Error&gt;) -&gt; Void) {<br>        let headers: HTTPHeaders = [<br>            &quot;Authorization&quot;: &quot;Client-ID \(clientId)&quot;,<br>        ]<br>        AF.upload(multipartFormData: { (data) in<br>            let imageData = uiImage.jpegData(compressionQuality: 1)<br>            data.append(imageData!, withName: &quot;image&quot;)<br>            <br>        }, to: &quot;<a href="https://api.imgur.com/3/image">https://api.imgur.com/3/image</a>&quot;, headers: headers).responseDecodable(of: ImageUpLoadResponse.self, queue: .main, decoder: JSONDecoder()) { (response) in<br>            //print(String(data: response.data!, encoding: .utf8))<br>            switch response.result {<br>            case .success(let result):<br>                completion(.success(result.data.link))<br>                print(result.data.link)<br>            case .failure(let error):<br>                completion(.failure(error))<br>                print(error)<br>            }<br>        }<br>    }</pre><p>由於imgur API上傳的格式為<strong>multipart/form-data</strong>，因此必須使用<strong>Alamofire</strong>套件做資料的上傳，並解析response為自訂型別<strong>ImageUpLoadResponse</strong>，成功上傳後透過讀取result.data.link取得圖片的url</p><pre>struct <strong>ImageUpLoadResponse</strong>: Codable {<br>    struct Data: Codable {<br>        let link: URL<br>    }<br>    let data: Data<br>}</pre><p><strong>註冊使用者並登入</strong></p><p>點擊continue後讀取個欄位資料，呼叫自訂類別AccountController的func createAccount(forAccount:)來建立帳戶</p><p>註冊成功後呼叫func loginAccount登入帳戶</p><p>登入成功後儲存使用者資訊並切換至使用者個人頁面</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4a43b6bd38dd87f9efed321fb39ad449/href">https://medium.com/media/4a43b6bd38dd87f9efed321fb39ad449/href</a></iframe><p><strong>註冊帳號</strong></p><p>使用okta API (<strong><em>Create Activated User with Password &amp; Recovery Question)</em></strong></p><p><a href="https://developer.okta.com/docs/reference/api/users/#create-user-with-password-recovery-question">Users | Okta Developer</a></p><p>查看此API範例</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/857/1*q73hjBBqKtZeVPBc68Ushg.png" /></figure><p>根據範例寫出對應的自訂型別，其中birthdayDate是我自訂的欄位</p><pre>struct Account: Codable {<br>    let profile: Profile<br>    let credentials: Credential<br>}</pre><pre>struct Profile: Codable {<br>    var firstName: String<br>    var lastName: String<br>    var email: String<br>    var login: String<br>    var birthdayDate: String<br>    var profileUrl: URL<br>}</pre><pre>struct Credential: Codable {<br>    let password: Password<br>    let recovery_question: RecoveryQuestion<br>    struct Password: Codable {<br>        var value: String<br>    }<br>    struct RecoveryQuestion: Codable {<br>        var question: String<br>        var answer: String<br>    }<br>}</pre><p><strong>如何在okta Users Profile中加入自訂的欄位</strong></p><p>點擊Users-&gt;Profile Editor</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/783/1*8LBRXZN2LhMcTVHUYo4l4w.png" /></figure><p>選取自己的APP右方的Profile</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1002/1*BeEYWGvF2UA8A3O34C8uWA.png" /></figure><p>點選+Add Attribute 即可設定想要加入的欄位型別、名稱等等</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/905/1*ucrfFwlCqym9slpOxU_caw.png" /></figure><p><strong>註冊帳號func說明</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/727700dd7c525fa56a01a6ad07c8a6ee/href">https://medium.com/media/727700dd7c525fa56a01a6ad07c8a6ee/href</a></iframe><p>透過.appendingPathComponent組成基本的註冊url</p><p>再將url轉為URLComponents型別，利用.queryItems變數設定url的queryItem</p><pre><strong>let</strong> baseCreateURL = baseURL.appendingPathComponent(&quot;users&quot;)<br><strong>var</strong> components = URLComponents(url: baseCreateURL, resolvingAgainstBaseURL: <strong>true</strong>)!<br>components.queryItems = [URLQueryItem(name: &quot;activate&quot;, value: &quot;true&quot;)]<br><strong>let</strong> createURL = components.url!</pre><p>將自訂型別編譯成JSON格式並加入request body</p><pre>let jsonData = try? JSONEncoder().encode(account)<br>request.httpBody = jsonData</pre><p>將response轉型為HTTPURLResponse，利用其.statusCode屬性判斷request是否成功(200為成功)</p><pre>if let response = response as? HTTPURLResponse {<br>    if response.statusCode == 200 {<br>        let successResponse = try JSONDecoder().decode(CreateAndUpdateResponse.self, from: data)<br>        completion(.success(successResponse.profile))<br>    } else {<br>        let failResponse = try JSONDecoder().decode(FailCreateAccountResponse.self, from: data)<br>        if let errorSummary = failResponse.errorCauses.first?.errorSummary {<br>            completion(.failure(CustomError.error(errorSummary)))<br>        }<br>    }<br>}</pre><ul><li>request success</li></ul><p>將回應的data貼到JSON Editor，這邊我需要的部分只有profile</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/664/1*FuZFNa61kenpTDx9otcbuw.png" /></figure><p>自訂型別CreateAndUpdateResponse，此型別在update時也可使用</p><pre>struct CreateAndUpdateResponse: Codable {<br>    let profile: Profile<br>}</pre><ul><li>request fail</li></ul><p>失敗時我為了將失敗的提示訊息印出來，必須先將失敗的回應解析成自訂型別，先用postman送出會失敗的request，得到data後再將其貼到JSON Editor</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/673/1*Pt6Kf822xtR4xW9sQKuVtA.png" /></figure><p>自訂型別FailCreateAccountResponse，我需要取得errorSummary的失敗訊息，這樣就可以在註冊fail時將錯誤訊息使用alert提示使用者</p><pre>struct FailCreateAccountResponse: Codable {<br>    let errorCauses: [ErrorCause]<br>    struct ErrorCause: Codable {<br>        let errorSummary: String<br>    }<br>}</pre><p>特別說明一下由於.failure的參數必須是Error型別，然而解析出來的errorSummary為String型別，因此必須將其轉為Error型別才能夠當做.failure的參數</p><pre>let failResponse = try JSONDecoder().decode(FailCreateAccountResponse.self, from: data)<br>if let errorSummary = failResponse.errorCauses.first?.errorSummary {<br>    completion(.failure(CustomError.error(errorSummary)))<br>}</pre><p>解決方法：自訂一個繼承Error的Enum <strong>CustomError</strong>型別，並利用enum associated value，即可將errorSummary包成CustomError型別作為.failure參數</p><pre>enum CustomError: Error {<br>    case error(String)<br>}</pre><p>註冊成功後呼叫登入func</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b17c451131d61b1a8dcd316d14e3b78c/href">https://medium.com/media/b17c451131d61b1a8dcd316d14e3b78c/href</a></iframe><p>登入API</p><p><a href="https://developer.okta.com/docs/reference/api/authn/">Authentication | Okta Developer</a></p><p>登入成功後取得<strong>seesionToken</strong>及<strong>userId</strong>並將其與註冊後得到的<strong>userprofile</strong>儲存在UserDefaults</p><pre>let sessionToken = userinfo.sessionToken<br>let userId = userinfo._embedded.user.id<br>// 儲存使用者個人資訊<br>UserInfo.saveToFile(userInfo: UserInfo(sessionToken: sessionToken, id: userId, profile: userprofile))</pre><p>在UserInfo型別內宣告儲存與讀取的func</p><pre>struct UserInfo: Codable {<br>    var sessionToken: String<br>    var id: String<br>    var profile: Profile<br>    <br>    // 宣告為static 可直接用型別呼叫func. ex: UserInfo.saveToFile()<br>    static func saveToFile(userInfo: UserInfo) {<br>        if let data = try? JSONEncoder().encode(userInfo) {<br>            let userDefault = UserDefaults.standard<br>            userDefault.set(data, forKey: &quot;userInfo&quot;)<br>        }<br>    }<br>    <br>    static func readFile() -&gt; UserInfo? {<br>        let userDefault = UserDefaults.standard<br>        if let data = userDefault.data(forKey: &quot;userInfo&quot;),<br>           let userInfo = try? JSONDecoder().decode(UserInfo.self, from: data) {<br>            return userInfo<br>        } else {<br>            return nil<br>        }<br>    }<br>}</pre><blockquote><strong><em>個人主頁 </em>Profile</strong></blockquote><p>個人主頁畫面</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/359/1*NMO5X5hxn7D1aQwD70Mdrw.png" /></figure><p>為了讓註冊後的使用者再次使用APP時不需重新登入，因此在SceneDelegate的optional func scene(_ scene:willConnectTo session:options connectionOptions:)內藉由讀取UserDefault的資料，取出sessionToken判斷使用者是否已經登入，若已登入直接切換至個人主頁</p><pre>let userInfo = UserInfo.readFile()<br>if let sessionToken = userInfo?.sessionToken {<br>    if sessionToken.isEmpty {<br>        // No sessionToken will do...<br>        print(&quot;no user log in&quot;)<br>    } else {<br>        // Have sessionToken will do...<br>        print(&quot;user already log in&quot;)<br>        guard let profile = userInfo?.profile else { return }<br>        self.showProfileView(profile: profile)<br>    }<br>}</pre><p><em>#多次用到showProfileView，需優化改善</em></p><p>個人主頁的重點就是右上角的Edit，點擊後進入修改個人資訊頁面</p><blockquote><strong><em>修改個人資訊 </em>Update Profile</strong></blockquote><p>修改Profile畫面</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/355/1*w9PoyrROtyMmB4oixFstcQ.png" /></figure><p>修改個人資訊其實與註冊帳號的API差不多，差別只在於需要使用者的Id</p><p><a href="https://developer.okta.com/docs/reference/api/users/#create-user-with-password-recovery-question">Users | Okta Developer</a></p><p>使用者修改完資料後，按下Done呼叫updateProfile(update:for:)送出Update Request</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0cd06c29c194d3675f2e9c53631f3280/href">https://medium.com/media/0cd06c29c194d3675f2e9c53631f3280/href</a></iframe><p>修改成功後一樣將資料儲存到UserDefault(由於key都是使用userInfo，因此每次儲存都會覆寫原本的資料)，接著呼叫navigationController專屬的func popViewController(animated:)回到上一頁</p><pre>DispatchQueue.main.async {<br>    self.navigationController?.popViewController(animated: true)<br>}</pre><p># <em>更新畫面時必須使用main queue</em></p><blockquote>Demo gif</blockquote><p><strong>註冊並登入</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3P5OCccbkE1ZwhoIoveIRA.gif" /></figure><p><strong>修改個人資訊</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Os3zjD_QOcD2cw27luDQ5g.gif" /></figure><p><strong>登入後重新開啟APP</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/337/1*ARjxVhAiveGWVmQUhBRQ9A.gif" /></figure><blockquote><strong><em>後記</em></strong></blockquote><p>目前進度就到這邊，後續會再補上以下功能</p><ul><li>登出</li><li>註冊畫面使用者輸入email若已註冊，則會切換到登入畫面，輸入密碼即可登入</li><li>修改密碼</li><li>忘記密碼(利用recovery question &amp; answer)</li><li>FB &amp; Google 登入</li></ul><h4>彼得潘iOS課程小小心得</h4><p>彼得潘iOS課程正式於今年1/29結束了，但是成為iOS Developer之路才剛開始，感謝彼得潘給予初心者非常有趣的入門教學方式，俗話說的好「師父領進門，修行在個人」，彼得潘出了非常豐富的作業讓初學者大量練習，儘管上完課後還是能靠著彼得潘出的作業不斷練習，有問題問彼得潘他還是一樣非常有耐心的解答，遇上瓶頸無助之時有彼得潘的解答真的是天降甘霖，再次感謝彼得潘耐心的指導。(有興趣想上課的朋友可以參考以下連結)</p><p><a href="https://www.apppeterpan.com/">彼得潘的 Swift iOS App 程式設計入門</a></p><p><strong>參考文章</strong></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/109-%E7%99%BB%E5%85%A5%E8%A8%BB%E5%86%8A-%E5%80%8B%E4%BA%BA%E5%B8%B3%E8%99%9F%E9%A0%81%E9%9D%A2-17465b478133">#109 登入註冊，個人資訊(profile)頁面 &amp; Result type</a></li><li><a href="https://ithelp.ithome.com.tw/articles/10094951">[Javascript] Regular Expression - Email 表單驗證 - iT 邦幫忙::一起幫忙解決難題，拯救 IT 人的一天</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%88%A9%E7%94%A8-contentinset-%E8%AE%93%E9%8D%B5%E7%9B%A4%E5%87%BA%E7%8F%BE%E6%99%82-scroll-view-%E8%87%AA%E5%8B%95%E4%B8%8A%E7%A7%BB-687ab82990f7">利用 contentInset 讓鍵盤出現時 scroll view 自動上移</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%A8%A1%E4%BB%BF-apple-%E5%AE%98%E6%96%B9%E7%AF%84%E4%BE%8B%E4%B8%B2%E6%8E%A5-json-api-84139d10a7c9">模仿 Apple 官方範例串接 JSON API，定義 function 型別的 completion 參數</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><em>-Github</em></p><p><a href="https://github.com/laijw4403/LoginDemo">laijw4403/LoginDemo</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cd642463e8be" width="1" height="1" alt=""><hr><p><a href="https://medium.com/peter-pan-swift-ios-class/ios-task-sign-in-sign-up-1-cd642463e8be">[iOS Task]-Sign in &amp; Sign up#1</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[Peter’s 100 task #6–1 Order Drinks APP]]></title>
            <link>https://medium.com/peter-pan-swift-ios-class/peters-100-task-6-1-order-drinks-app-701c8f259eca?source=rss-70a85a72b783------2</link>
            <guid isPermaLink="false">https://medium.com/p/701c8f259eca</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[airtable]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Tommy]]></dc:creator>
            <pubDate>Mon, 11 Jan 2021 15:01:44 GMT</pubDate>
            <atom:updated>2021-01-11T16:57:42.302Z</atom:updated>
            <content:encoded><![CDATA[<h4>新增訂單列表頁面、修改與刪除功能</h4><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/peters-100-task-6-order-drinks-app-b6d78013da3f">Peter’s 100 task #6 Order Drinks APP</a></p><p><strong>本篇實作功能：</strong></p><ol><li><strong>利用Airtable API PUT &amp; DELETE 實現訂單修改、刪除</strong></li><li><strong>訂購飲料時加入防呆機制</strong></li></ol><blockquote>訂單列表頁面</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/257/1*ppfbP2JMWXeZ0HPn1g-1Pg.png" /><figcaption>Order Data List</figcaption></figure><blockquote>訂單修改</blockquote><p>使用者點擊訂單即可進入修改訂單頁面(同加入訂單頁面)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/253/1*4lxwgKasPCdZgAzvWRJE1Q.png" /><figcaption>Update Order</figcaption></figure><p>修改完畢後點選修改訂單，透過API PUT將資料庫的資料更新，來看看Airtable的說明吧～</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zy3yVJJIxgRj4bzePf2scw.png" /></figure><p>後來有對資料庫做一些更新，<strong>刪除price欄位</strong>並<strong>新增drinkImage欄位</strong>，因此本篇的欄位與前篇有些不同。</p><p>上圖可看見Update有兩種request，分別是<strong>PATCH</strong>、<strong>PUT</strong>，兩種的差別只在於<strong>PUT會將未指定更新的欄位清除</strong>，這次更新用的data資料JSON格式沿用上次上傳用的JSON格式，因此使用PATCH與PUT都可以。</p><p>由於<strong>PUT需要使用到id</strong>(如上圖url最後的<strong>/recjjQ6C6m1o23wEM</strong>)，因此在呈現訂單列表時，必須解析id property，並在使用者點擊該訂單後將id傳遞過去修改訂單頁面。</p><pre>struct DrinkOrder: Codable {<br>    var id: String<br>    var fields: OrderData<br>    var createdTime: String<br>}</pre><p>利用updateOrderData屬性檢查判斷是否為修改模式，設定request &amp; url</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b22ae5bb27dcb98dbeb5ea2862addb40/href">https://medium.com/media/b22ae5bb27dcb98dbeb5ea2862addb40/href</a></iframe><blockquote>訂單刪除</blockquote><p>使用者左滑顯示刪除按鈕</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/258/1*T07gytbvj8PuRlsAJ0xfPA.png" /></figure><p>按下Delete透過API DELETE將資料庫資料刪除</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NuWqXItm56UKl6Agtj5AwA.png" /></figure><p>上圖說明非常簡單，只需要將request設為DELETE，並在url後加上id</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4452a9e33f15dda3745a2137f736b1b4/href">https://medium.com/media/4452a9e33f15dda3745a2137f736b1b4/href</a></iframe><p>由於Airtable資料刪除後，原本訂單列表的orderDrinkData Array仍是尚未刪除前的資料，因此在完成Airtable資料刪除後，呼叫.remove()將該row的資料刪除。</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fc9671ba0dbce3b8b1d3b03e5673faaf/href">https://medium.com/media/fc9671ba0dbce3b8b1d3b03e5673faaf/href</a></iframe><blockquote>APP Demo</blockquote><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FyKQF4qvkxLo%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DyKQF4qvkxLo&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FyKQF4qvkxLo%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/3c556e2d718d6aa73169858596b63bc8/href">https://medium.com/media/3c556e2d718d6aa73169858596b63bc8/href</a></iframe><blockquote>後記</blockquote><p>Airtable API的說明文件非常簡單明瞭，容易理解，但是APP相較於過去複雜了許多，程式碼也複雜許多，許多檔案顯得雜亂，剛好昨天peter講完專案分類檔案的概念(MVC)，正好運用在此APP上，將檔案分成Model、View、Controller三個資料夾，讓整個專案檔案較有邏輯且一目瞭然。</p><p>這次的可不可訂飲料APP就到這邊完成了，過程中遇到許多問題，雖然都解決了，但感覺自己在寫code時腦中思考邏輯、架構不夠清晰，導致常常卡關卡很久，不過相信每次的挫敗都是成長的動力！</p><h4>參考資料</h4><ul><li><a href="https://medium.com/@cwlai.unipattern/app%E9%96%8B%E7%99%BC-%E4%BD%BF%E7%94%A8swift-9-swipe-%E5%90%91%E5%B7%A6%E6%BB%91%E5%8B%95-a0e286660211">[APP開發-使用Swift] 9. Swipe 向左滑動</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/%E7%B0%A1%E6%98%93%E8%AA%AA%E6%98%8Excode%E4%B8%AD%E7%9A%84%E8%B3%87%E6%96%99%E5%82%B3%E9%81%9E-%E4%BD%BF%E7%94%A8prepare%E5%82%B3%E9%81%9Eproperty%E7%9A%84%E6%96%B9%E5%BC%8F-a5666ca36114">『簡易說明Xcode』資料傳遞（使用Prepare傳遞Property的方式）</a></li></ul><p><em>-Github</em></p><p><a href="https://github.com/laijw4403/DrinkOrder">laijw4403/DrinkOrder</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=701c8f259eca" width="1" height="1" alt=""><hr><p><a href="https://medium.com/peter-pan-swift-ios-class/peters-100-task-6-1-order-drinks-app-701c8f259eca">Peter’s 100 task #6–1 Order Drinks 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[Peter’s 100 task #6 Order Drinks APP]]></title>
            <link>https://medium.com/peter-pan-swift-ios-class/peters-100-task-6-order-drinks-app-b6d78013da3f?source=rss-70a85a72b783------2</link>
            <guid isPermaLink="false">https://medium.com/p/b6d78013da3f</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[airtable]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Tommy]]></dc:creator>
            <pubDate>Mon, 04 Jan 2021 10:43:35 GMT</pubDate>
            <atom:updated>2021-02-16T16:20:45.973Z</atom:updated>
            <content:encoded><![CDATA[<h4>串接Airtable API Get &amp; Post</h4><h4>本篇實作功能：Menu呈現、訂單上傳Airtable資料庫</h4><blockquote>Menu呈現</blockquote><ol><li>建立菜單資料表(設定欄位，並輸入資料)</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c7yD1Wkko50hzGYzDUj3eQ.png" /></figure><p>詳細串接Airtable API可參考Peter教學文章</p><p><a href="https://medium.com/%E5%BD%BC%E5%BE%97%E6%BD%98%E7%9A%84-swift-ios-app-%E9%96%8B%E7%99%BC%E5%95%8F%E9%A1%8C%E8%A7%A3%E7%AD%94%E9%9B%86/%E4%B8%B2%E6%8E%A5-airtable%E7%9A%84-api-%E9%96%8B%E7%99%BC-ios-app-5e5c86c8ca7d">串接 Airtable的 API 開發 iOS App</a></p><p>特別說明下圖紅色框起部分, -H指的是http header</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/641/1*ovlYhqV45FGJBLRFswSqGw.png" /></figure><p>2. 透過API回傳JSON格式的資料(使用Postman或是<a href="https://jsoneditoronline.org/#left=local.himoru">JSON Editor Online</a>)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/666/1*U0mqk4d2w6HvdcmKhBEJ6A.png" /></figure><p>3. 解析JSON</p><p>上圖可以看到需要的資料位於records陣列的fields物件內, 而飲料圖片的部分則是在drinkImage陣列內, 建立自訂型別</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/26290ebe8b0bbc9a84b9a034bdd7d777/href">https://medium.com/media/26290ebe8b0bbc9a84b9a034bdd7d777/href</a></iframe><p>其中drinkImage只需要url屬性, 不需全部解析</p><p>為了讓飲料按照資料表的順序去做排列, 設定了一個sort的欄位,並且在使用API時加上sort指令控制資料的排序</p><pre><strong>let</strong> urlStr = &quot;https://api.airtable.com/v0/appObOrAHeovNgbQb/Menu?sort[][field]=sort&quot;</pre><p>加入sort[][field],其中第一個中括號的參數用於若多個條件排序時,需輸入數字,[field]則是需排序的欄位名稱,還有direction方向可以設定,分為asc由小到大 &amp; desc由大到小,若沒特別設定則預設為由小到大(參考上面peter教學文章)</p><p>接著將解析出來的資料存取即可做使用啦</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/114868580f7750c4d9b0119abfdbafba/href">https://medium.com/media/114868580f7750c4d9b0119abfdbafba/href</a></iframe><p>由於飲料圖片資料是url,因此在呼叫collectionView(cellForItemAt:)呈現collectionView時將圖片下載,並顯示於UI畫面</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7b0213c755b2a301dc8dda53b7b4bc08/href">https://medium.com/media/7b0213c755b2a301dc8dda53b7b4bc08/href</a></iframe><p>這樣就完成Menu的呈現啦～</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/338/1*onUq6tDyY_RDtupdFRhaxA.gif" /></figure><blockquote>訂單上傳</blockquote><ol><li>使用者選擇想喝的飲料後，進入訂購畫面</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/336/1*WqNyiI1_2TgyypNmkHQwhw.png" /></figure><p>這個畫面最困難的部分就是radio button, 這邊使用最簡單的方法ImageView當作button, 並且在選取到cell時更改ImageView的圖片, 為避免cell重複利用導致ImageView跑走, 建立陣列用於存取選項是否已選取</p><pre><strong>var</strong> sizeChecked = Array(repeating: <strong>false</strong>, count: Size.allCases.count)</pre><pre><strong>var</strong> tempChecked = Array(repeating: <strong>false</strong>, count: Temp.allCases.count)</pre><pre><strong>var</strong> sugarChecked = Array(repeating: <strong>false</strong>, count: Sugar.allCases.count)</pre><pre><strong>var</strong> feedChecked = Array(repeating: <strong>false</strong>, count: Feed.allCases.count)</pre><p>另外為取得textField的文字, 需讓controller遵從UITextFieldDelegate,並將delegate設為此controller, 接著實作func textFieldDidEndEditing, 此func在結束編輯textfield時由delegate呼叫</p><pre>func textFieldDidEndEditing(_ textField: UITextField) {<br>    ordererName = textField.text<br>}</pre><p>2. 填寫完畢後點擊加入訂單, 將資料上傳至Airtable</p><p>首先建立一個資料表用於存取訂單資料</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J9_p5fcNuxcvkGb96Hib9Q.png" /></figure><p>利用API POST新增資料</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WsmzOWOZiSjcx64vL-QSog.png" /></figure><p>由上圖可見所需上傳的data資料JSON格式為</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/657/1*JwCpIFrA1eL6TavsUd0-8A.png" /></figure><p>建立自訂型別</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3b0d7acba55afdc0073a784d386ef64a/href">https://medium.com/media/3b0d7acba55afdc0073a784d386ef64a/href</a></iframe><p>設定http request method &amp; content type</p><pre>urlRequest.httpMethod = &quot;PUT&quot;<br>urlRequest.setValue(&quot;Bearer \(apiKey)&quot;, forHTTPHeaderField: &quot;Authorization&quot;)</pre><pre>urlRequest.setValue(&quot;application/json&quot;, forHTTPHeaderField: &quot;Content-Type&quot;)</pre><p>搭配 JSONEncoder 將自訂型別變成 JSON 格式的 Data, 利用.statusCode屬性判斷request是否成功</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8755d3da6e8d08b3d75ece16a0636d3b/href">https://medium.com/media/8755d3da6e8d08b3d75ece16a0636d3b/href</a></iframe><p>最後放上成品gif</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e_4twfMF0dlHKc8ty6reaQ.gif" /><figcaption>APP Demo gif</figcaption></figure><p>目前先將做到能夠上傳資料，後續會補上修改(update)與刪除(delete)功能以及訂購清單頁面，並判斷必填選項是否填寫，否則無法加入訂單。</p><p><strong>參考資料</strong></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%88%A9%E7%94%A8-airtable-%E8%A3%BD%E4%BD%9C-ios-app-%E9%80%A3%E7%B5%90%E7%9A%84%E5%BE%8C%E5%8F%B0%E8%B3%87%E6%96%99-e22378536acb">利用 Airtable 製作 iOS 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%E6%95%99%E5%AE%A4/ios-17-%E5%8F%AF%E4%B8%8D%E5%8F%AF%E9%A3%B2%E6%96%99%E8%A8%82%E8%B3%BCapp-part2-sheetdb-%E5%AD%98%E5%8F%96%E8%A8%82%E8%B3%BC%E6%B8%85%E5%96%AE%E8%B3%87%E6%96%99-d549976e45df">【iOS】#17 可不可飲料訂購APP Part2: SheetDB 存取訂購清單資料</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/%E4%BE%86%E5%81%9A%E5%80%8B%E8%A8%82%E9%A3%B2%E6%96%99-app-%E5%90%A7-%E5%AE%8C-a57e67443a4f">來做個訂飲料 app 吧（完）!</a></li></ul><p><em>-Github</em></p><p><a href="https://github.com/laijw4403/DrinkOrder">laijw4403/DrinkOrder</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b6d78013da3f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/peter-pan-swift-ios-class/peters-100-task-6-order-drinks-app-b6d78013da3f">Peter’s 100 task #6 Order Drinks 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[Peter’s 100 task #4–1 誰是臥底]]></title>
            <link>https://medium.com/peter-pan-swift-ios-class/peters-100-task-4-1-%E8%AA%B0%E6%98%AF%E8%87%A5%E5%BA%95-b735a32db86c?source=rss-70a85a72b783------2</link>
            <guid isPermaLink="false">https://medium.com/p/b735a32db86c</guid>
            <category><![CDATA[json]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[google-sheets-api]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Tommy]]></dc:creator>
            <pubDate>Sat, 19 Dec 2020 15:06:27 GMT</pubDate>
            <atom:updated>2021-02-16T16:45:45.573Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*7VYCmRZDxscxIP4bTzvQCQ.png" /></figure><h4>新增自訂暱稱與忘詞功能，使用Google Spreadsheet當後台</h4><h4>前篇連結</h4><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/peters-100-task-4-%E8%AA%B0%E6%98%AF%E8%87%A5%E5%BA%95-7bce319466cb">Peter’s 100 task #4 誰是臥底</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/284/1*un5PB_pazfXIX-0vJkFMdg.gif" /></figure><h3>新增功能說明</h3><blockquote><strong>自訂暱稱功能</strong></blockquote><p><strong>點擊自訂暱稱按鈕後跳出Alert，內容為依據玩家人數產生textField，輸入完畢按下OK按鈕，存取輸入的名字</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b257190cd6365eefc326b932ad6a111f/href">https://medium.com/media/b257190cd6365eefc326b932ad6a111f/href</a></iframe><p>利用.addTextField(configurationHandler:)，將textField加入alert</p><p>於configurationHandler參數closure內設定textField之屬性</p><blockquote><strong>忘詞功能</strong></blockquote><p><strong>點擊忘詞按鈕出現忘詞頁面，利用IBSegueAction做資料傳遞，忘詞頁面內容為依據玩家人數產生Button，點擊玩家Button後顯示該玩家的題目</strong></p><p>新增一個自訂ViewController類別，名稱為ForgetQuestionViewController</p><pre>func initButton() {<br>        // 初始玩家暱稱<br>        for i in 0...playerNumber-1 {<br>            playerForgetQuestionButton[i].setTitle(player[i].name, for: .normal)<br>        }<br>        // 初始按鈕數量<br>        var index = playerForgetQuestionButton.count<br>        print(index)<br>        while index &gt; player.count {<br>            print(player.count)<br>            //playerVoteButton[index-1].isHidden = true<br>            playerForgetQuestionButton[index-1].alpha = 0<br>            index -= 1<br>        }<br>    }</pre><p>於自訂類別內建立一個initButton()依據玩家人數顯示對應Button數量，在viewDidLoad()呼叫initButton()</p><pre><a href="http://twitter.com/IBAction">@IBAction</a> func showQuestion(_ sender: UIButton) {<br>        switch sender {<br>        case playerForgetQuestionButton[0]:<br>            confirmQuestion(index: 0)<br>        case playerForgetQuestionButton[1]:<br>            confirmQuestion(index: 1)<br>        case playerForgetQuestionButton[2]:<br>            confirmQuestion(index: 2)<br>        case playerForgetQuestionButton[3]:<br>            confirmQuestion(index: 3)<br>        case playerForgetQuestionButton[4]:<br>            confirmQuestion(index: 4)<br>        case playerForgetQuestionButton[5]:<br>            confirmQuestion(index: 5)<br>        case playerForgetQuestionButton[6]:<br>            confirmQuestion(index: 6)<br>        case playerForgetQuestionButton[7]:<br>            confirmQuestion(index: 7)<br>        case playerForgetQuestionButton[8]:<br>            confirmQuestion(index: 8)<br>        case playerForgetQuestionButton[9]:<br>            confirmQuestion(index: 9)<br>        default:<br>            break<br>        }<br>    }</pre><p>將每個Button都拉進IBAction，利用Switch判斷按下哪個按鈕，並呼叫顯示題目的func</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d8d325ca6fcfdfe4ac1166e38a12c3d6/href">https://medium.com/media/d8d325ca6fcfdfe4ac1166e38a12c3d6/href</a></iframe><p>判斷目前Button的Titile，若為玩家名稱則顯示題目，反之則顯示玩家名稱</p><blockquote><strong>利用 Google Spreadsheet 當後台，作為題目資料來源</strong></blockquote><p>建立Google sheets表單</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/257/1*2G5jHUvD-UK2kLw9_cbHDg.png" /></figure><p>產生JSON</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/377/1*_pUSuw_oVowHyYB9s81nTQ.png" /></figure><p>題目資料陣列放在feed-&gt;entry，其中gsx$civilianquestion及gsx$spyquestion為儲存題目內容的欄位，由於gsx$及$t無法做為物件屬性名稱，因此需利用enum CodingKeys將其轉換為可使用的名稱</p><pre>struct SearchResponse: Codable {<br>    let feed: QuestionData<br>    <br>    struct QuestionData: Codable {<br>        let entry: [IdentityQuestion]<br>    }<br>}</pre><pre>struct IdentityQuestion: Codable {<br>    let civilianQuestion: Question<br>    let spyQuestion: Question<br>    <br>    enum CodingKeys: String, CodingKey {<br>        case civilianQuestion = &quot;gsx$civilianquestion&quot;<br>        case spyQuestion = &quot;gsx$spyquestion&quot;<br>    }<br>}</pre><pre>struct Question: Codable {<br>    let question: String<br>    <br>    enum CodingKeys: String, CodingKey {<br>        case question = &quot;$t&quot;<br>    }<br>}</pre><p>自訂的資料型別遵從Codable(可編碼、解碼)或DeCodable(可解碼)</p><p>將JSON內的物件的Key設定為自訂的資料型別的屬性名稱(<strong>需與Key一模一樣</strong>)</p><p>在自訂型別內加入enum CodingKeys，並設定raw value加以描述屬性名稱對應JSON Key<strong>(注意:每個屬性名稱都要有對應之case，無需加以描述則不用設定raw value)</strong></p><p>這樣就可以順利解析啦～</p><blockquote><strong>將抓題庫程式寫成func，抓題庫時以ActivityIndicatorView顯示loading中</strong></blockquote><p>宣告全域變數question存取題目</p><pre>var question = [IdentityQuestion]()</pre><p><strong>利用UIActivityIndicatorView表示下載中，以及isUserInteractionEnabled屬性讓畫面無法操作</strong></p><pre>loadingActivityIndicator = UIActivityIndicatorView(style: .medium)<br>loadingActivityIndicator.center = view.center<br>view.addSubview(loadingActivityIndicator)</pre><p>建立loadingActivityIndicator變數為UIActivityIndicatorView物件，設定對齊畫面中央，並將ActivityIndicatorView加入view</p><p>實現將資料下載好後放至question陣列內</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/82ca82baa815de9d7c14a366adaa8316/href">https://medium.com/media/82ca82baa815de9d7c14a366adaa8316/href</a></iframe><p>利用completionHandler func當參數，設定完成後執行的動作，func內需放入型別為[IdentityQuestion]</p><pre>loadingActivityIndicator.startAnimating()<br>view.isUserInteractionEnabled = false</pre><p>進入fetchQuestion func時，呼叫.startAnimating啟動loadingActivityIndicator，並將isUserInteractioinEnabled屬性設為false，讓使用者無法操作畫面</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cb8c7df1f1ee2b2880d0e27cda76f25e/href">https://medium.com/media/cb8c7df1f1ee2b2880d0e27cda76f25e/href</a></iframe><p>在viewDidLoad()呼叫fetchQuestion func，並在completionHandler closure內將資料存取</p><pre>DispatchQueue.main.async {<br>    self.loadingActivityIndicator.stopAnimating()<br>    self.view.isUserInteractionEnabled = true<br>}</pre><p>完成下載後將loadingActivityIndicator關閉(關閉後預設為隱藏該元件)，並且將isUserInteractionEnabled設為true，讓使用者可以操作畫面</p><p>大致上想實現的功能都完成啦～原本只是想把自訂暱稱與忘詞功能寫完，後來突然看到peter說可以用google spreadsheets做資料來源，也順利實現從網路上抓題庫的想法。</p><p>後續如果有發現什麼問題會再陸續更新，有興趣的人可以去github載來玩玩看喔，有做autolayout應該是目前的iphone都可以玩～</p><h4>參考資料</h4><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/%E5%88%A9%E7%94%A8-google-spreadsheet-%E7%9A%84-json-imgur-%E7%9A%84%E5%9C%96%E7%89%87%E9%96%8B%E7%99%BC-ios-app-%E6%AF%94%E6%96%B9%E9%9B%BB%E5%BD%B1-app-37c1c1adb3b8">#100 利用 Google Spreadsheet 的 JSON &amp; imgur 的圖片開發 iOS App，比方電影 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%88%A9%E7%94%A8-enum-codingkeys-%E5%AE%A2%E8%A3%BD-json-%E5%B0%8D%E6%87%89%E7%9A%84-property-1b27f29c0c32">利用 CodingKey 客製 JSON 對應的 property</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/isenabled-%E5%92%8C-isuserinteractionenabled-%E7%9A%84%E6%AF%94%E8%BC%83-639a31690980">isEnabled 和 isUserInteractionEnabled 的比較</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/%E7%B0%A1%E6%98%93%E8%AA%AA%E6%98%8Excode%E4%B8%ADobject-library%E7%9A%84activity-indicator-view-8bda79608a3b">『簡易說明Xcode』Object Library的Activity Indicator View</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%88%A9%E7%94%A8-swift-4-%E7%9A%84-jsondecoder-%E5%92%8C-codable-%E8%A7%A3%E6%9E%90-json-%E5%92%8C%E7%94%9F%E6%88%90%E8%87%AA%E8%A8%82%E5%9E%8B%E5%88%A5%E8%B3%87%E6%96%99-ee793622629e">利用 JSONDecoder 把 JSON 轉換成自訂型別的資料</a></li></ul><p><em>-Github</em></p><p><a href="https://github.com/laijw4403/WhoIsSpy">laijw4403/WhoIsSpy</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b735a32db86c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/peter-pan-swift-ios-class/peters-100-task-4-1-%E8%AA%B0%E6%98%AF%E8%87%A5%E5%BA%95-b735a32db86c">Peter’s 100 task #4–1 誰是臥底</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[Peter’s 100 task #5 模仿IG使用者頁面]]></title>
            <link>https://medium.com/peter-pan-swift-ios-class/peters-100-task-5-%E6%A8%A1%E4%BB%BFig%E4%BD%BF%E7%94%A8%E8%80%85%E9%A0%81%E9%9D%A2-e24cb569ee8a?source=rss-70a85a72b783------2</link>
            <guid isPermaLink="false">https://medium.com/p/e24cb569ee8a</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[instagram]]></category>
            <category><![CDATA[collectionview]]></category>
            <dc:creator><![CDATA[Tommy]]></dc:creator>
            <pubDate>Thu, 17 Dec 2020 05:30:21 GMT</pubDate>
            <atom:updated>2021-02-17T07:39:11.397Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*RqCDr7RsD0dYjkO6" /><figcaption>Photo by <a href="https://unsplash.com/@erik_lucatero?utm_source=medium&amp;utm_medium=referral">Erik Lucatero</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>使用collection view &amp; Interface Builder製作</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/352/1*yIne-GbPeDHOD54ecOnJVQ.gif" /></figure><h4>此作業主要實現</h4><ol><li>使用flow layout 的collection view製作照片牆</li><li>搭配 Lorem Picsum API抓圖</li><li>滑動後 profile tab 卡在上方的效果</li><li>點選照片後跳到下一頁呈現大圖</li></ol><blockquote>這次UI layout的部分使用Sketch&amp;Zeplin製作,這邊分享一個可以免費下載他人設計的Sketch網站(感謝Peter提供)</blockquote><p><a href="https://www.sketchappsources.com/">Sketch App Sources - New Free Design Resources - Icons, UI/UX Kits, Wireframes, iOS, Android Templates for Sketch</a></p><blockquote>使用flow layout 的collection view製作照片牆</blockquote><p><strong>以下說明一下比較重要的部分，詳細步驟可參考Peter的文章</strong></p><p><a href="https://medium.com/%E5%BD%BC%E5%BE%97%E6%BD%98%E7%9A%84-swift-ios-app-%E9%96%8B%E7%99%BC%E5%95%8F%E9%A1%8C%E8%A7%A3%E7%AD%94%E9%9B%86/%E5%88%A9%E7%94%A8-flow-layout-%E7%9A%84-collection-view-%E8%A3%BD%E4%BD%9C%E7%85%A7%E7%89%87%E7%89%86-e31dad55a7ac">利用 flow layout 的 collection view 製作照片牆</a></p><p>CollectionView原已遵從<strong>UICollectionViewDataSource Protocol</strong>,且設定為collection view的datasource.</p><p>建立自訂CollectionViewController與CollectionViewCell類別</p><p><strong>cell內容的顯示</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c250bf01efd427e561f75c191ae84281/href">https://medium.com/media/c250bf01efd427e561f75c191ae84281/href</a></iframe><p>需注意將cell轉型為自訂的cell類別<strong>UserPhotoGridCollectionViewCell</strong></p><p>利用URLSession在background thread抓圖片,保持main thread與UI的運作</p><pre>// 這段程式碼將於background thread執行<br>    { (data, response, error) in<br>            if let data = data, let image = UIImage(data: data) {<br>                DispatchQueue.main.async {<br>                    cell.photoImageView.image = image<br>                }<br>            }<br>        }</pre><p>更新UI畫面必須利用func DispatchQueue.main.async將程式碼排入main queue執行</p><p><strong>設定cell的大小與間距</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4d1f21db3a1b7444883c0682542efb29/href">https://medium.com/media/4d1f21db3a1b7444883c0682542efb29/href</a></iframe><p><strong>floor() 回傳不大於參數之最大整數值</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/225/1*2Hnt6ofNcc9NniLZzu7DdA.png" /></figure><blockquote>Lorem Picsum API抓圖</blockquote><p>使用API(https://picsum.photos/seed/picsum(id)/500),抓取指定id照片</p><blockquote>滑動後 profile tab 卡在上方的效果</blockquote><p>設定collection view上方的空白為379</p><pre>func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -&gt; UIEdgeInsets {<br>        return UIEdgeInsets(top: 379, left: 0, bottom: 0, right: 0)<br>    }</pre><p>在Interface Builder放進一個空白的View,高度設為379</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/306/1*-IX3Q3LhO688MI3BvTsE0A.png" /></figure><p>畫面設計好後將View拉一個IBOutlet至自訂CollectionViewController類別</p><pre><a href="http://twitter.com/IBOutlet">@IBOutlet</a> var profileView: UIView!</pre><p>在viewDidLoad()呼叫自訂addProfileView()加入View</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b3f3cf7d04587863de2cd7c268fef6a7/href">https://medium.com/media/b3f3cf7d04587863de2cd7c268fef6a7/href</a></iframe><p><strong>利用frameLayoutGuide與contentLayoutGuide讓profile tab固定在上方</strong></p><p>將ProfileView的top設定與contentLayoutGuide的top相同,bottom設定為safeArea的top+50,由於當畫面向上滑動到ProfileView bottom = safeArea top+50時,將產生約束條件的衝突,因此需將profileView的top與contentLayoutGuide的top對齊的priority設定為999,表示若約束條件發生衝突,將先捨去此條件.</p><blockquote>點選照片後跳到下一頁呈現大圖</blockquote><p>利用IBSegueAction傳送資料</p><pre><a href="http://twitter.com/IBSegueAction">@IBSegueAction</a> func showPhoto(_ coder: NSCoder) -&gt; ShowPhotoViewController? {<br>        let index = self.collectionView.indexPathsForSelectedItems?.first?.item<br>        return ShowPhotoViewController(coder: coder, indexPathItem: index!)<br>    }</pre><p>用indexPathsForSelectedItems.first.item取得所選擇的item</p><p>indexPathsForselectedItems回傳選取cell的陣列,內容為[[section,item]],因此用first取得第一個陣列後,再取得item</p><p><strong>後記</strong></p><p>花太多時間在於刻Profile View設定autolayout，下次試試用code刻出畫面(可能會更久?)</p><p>下次要用IG API將公開帳號資料抓回呈現</p><p><strong>參考文章</strong></p><ul><li><a href="https://medium.com/%E5%BD%BC%E5%BE%97%E6%BD%98%E7%9A%84-swift-ios-app-%E9%96%8B%E7%99%BC%E5%95%8F%E9%A1%8C%E8%A7%A3%E7%AD%94%E9%9B%86/%E5%88%A9%E7%94%A8-flow-layout-%E7%9A%84-collection-view-%E8%A3%BD%E4%BD%9C%E7%85%A7%E7%89%87%E7%89%86-e31dad55a7ac">利用 flow layout 的 collection view 製作照片牆</a></li><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/83-%E8%A3%BD%E4%BD%9C-ig-%E6%BB%91%E5%8B%95%E5%BE%8C-profile-tab-%E5%8D%A1%E5%9C%A8%E4%B8%8A%E6%96%B9%E7%9A%84%E6%95%88%E6%9E%9C-360e6e6a380e">#83 製作 IG 滑動後 profile tab 卡在上方的效果</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%8A%A0%E5%85%A5-document-outline-%E7%9A%84%E5%85%83%E4%BB%B6-778d2a930d95">從程式加入 Document Outline 的元件</a></li></ul><p><em>-Gihub</em></p><p><a href="https://github.com/laijw4403/InstagramDemo">laijw4403/InstagramDemo</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e24cb569ee8a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/peter-pan-swift-ios-class/peters-100-task-5-%E6%A8%A1%E4%BB%BFig%E4%BD%BF%E7%94%A8%E8%80%85%E9%A0%81%E9%9D%A2-e24cb569ee8a">Peter’s 100 task #5 模仿IG使用者頁面</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[Peter’s 100 task #4 誰是臥底]]></title>
            <link>https://medium.com/peter-pan-swift-ios-class/peters-100-task-4-%E8%AA%B0%E6%98%AF%E8%87%A5%E5%BA%95-7bce319466cb?source=rss-70a85a72b783------2</link>
            <guid isPermaLink="false">https://medium.com/p/7bce319466cb</guid>
            <category><![CDATA[pickerview]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[game-development]]></category>
            <dc:creator><![CDATA[Tommy]]></dc:creator>
            <pubDate>Thu, 10 Dec 2020 10:05:16 GMT</pubDate>
            <atom:updated>2021-02-16T16:29:14.761Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*7VYCmRZDxscxIP4bTzvQCQ.png" /></figure><h4>一群朋友相聚可共同遊玩的小遊戲</h4><p>平時與三五好友同聚，室內活動就以桌遊為主，上次露營時用網站玩了這款遊戲，心想自己也試著做出有趣的小遊戲，玩著自己做的遊戲，格外開心呢</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/359/1*Bbl0Oe5cgzcf49X_rMHM8A.gif" /></figure><h3><strong>構想</strong></h3><h4>遊戲基本設定(人數、身份、題目)</h4><p>可選擇玩家人數、臥底人數、是否加入白板(無題目)</p><h4>隨機分配玩家身份與題目</h4><p>玩家一一傳閱確認題目，平民題目與臥底題目依前頁設定之數量分配(玩家不知自己是平民還是臥底)</p><h4>描述身份詞與投票規則說明</h4><p>玩家依序描述自己的身份詞，描述完畢將投票決定最像臥底的人使其出局</p><h4>投票環節</h4><p>選擇大家最後決定的人選，顯示其身份，並判斷遊戲是否結束(臥底全出局則平民獲勝，所剩平民人數與臥底相同則臥底獲勝)</p><h3>草擬畫面</h3><p>使用figma勾勒腦中畫面，不過實際畫面有稍作修改。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*ejzRcd77jUlYP3yzrMO8jA.png" /></figure><h3>APP實作</h3><h4>storyboard layout</h4><p>設定各元件大小、位置、顏色, 設定autolayout、stackView</p><h4>基本設定頁面</h4><p>使用 textField+pickerView、switch、button</p><blockquote><strong>說明 textField+pickerView做人數的選擇</strong></blockquote><p><strong>step1. 繼承UIPickerViewDelegate, UIPickerViewDataSource</strong></p><p>採用UIPickerViewDataSource protocol 用於顯示pickerView的資料</p><p>採用UIPickerViewDelegate 用於選擇pickerView</p><p><strong>step2. 建立玩家與臥底之pickerView物件及人數資料陣列</strong></p><pre><strong>var</strong> playerPicker = UIPickerView()<br><strong>var</strong> spyPicker = UIPickerView()<br><strong>let</strong> playerNumberForSelect = [4, 5, 6, 7, 8, 9, 10]<br><strong>let</strong> spyNumberForSelect = [1, 2, 3]<br>// 預設人數<br><strong>var</strong> playerNumber = 4<br><strong>var</strong> spyNumber = 1<br><strong>var</strong> blankNumber = 0</pre><p>玩家可選擇人數為4~10人,臥底可選擇1~3人</p><p><strong>step3. 於viewDidLoad將textField inputView設定為pickerView, 設定delegate與dataSource來源為此viewController, 加入手勢(endEditing)</strong></p><pre>// 設定delegate, dataSource來源<br>playerPicker.dataSource = self<br>playerPicker.delegate = self<br>spyPicker.dataSource = self<br>spyPicker.delegate = self<br>        <br>// 設定textField inputView為pickerView<br>playerPickerTextField.inputView = playerPicker<br>spyPickerTextField.inputView = spyPicker<br>        <br>// 設定手勢(endEditing)<br><strong>let</strong> tap = UITapGestureRecognizer(target: self, action: #selector(closeKeyboard))<br>// 將手勢加入view<br>view.addGestureRecognizer(tap)</pre><p><strong>step4. 實作繼承之protocol方法</strong></p><pre>func numberOfComponents(in pickerView: UIPickerView) -&gt; Int {<br>    return 1<br>}</pre><p>設定pickerView區塊數量為1(就是可以捲動的部分)</p><pre>func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -&gt; Int {<br>    if pickerView == playerPicker {<br>        return playerNumberForSelect.count<br>    } else {<br>        return spyNumberForSelect.count<br>    }        <br>}</pre><p>設定兩個pickerView的列數分別為playerNumberForSelect陣列及spyNumberForSelect陣列之元素數量</p><pre>func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -&gt; String? {<br>    if pickerView == playerPicker {<br>        return String(playerNumberForSelect[row])+&quot;人&quot;<br>    } else {<br>        return String(spyNumberForSelect[row])+&quot;人&quot;<br>    }<br>}</pre><p>設定pickerView每列的顯示標題為使用者選擇的人數</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cc8e39210e7c946f7a21d843181dd06b/href">https://medium.com/media/cc8e39210e7c946f7a21d843181dd06b/href</a></iframe><p>此func分為兩區塊(玩家人數選擇及臥底人數選擇),將人數顯示在textField上,並且存至變數playerNumber、spyNumber</p><blockquote>使用IBSegueAction將資料傳遞至下一頁</blockquote><pre>init?(coder: NSCoder, playerNumber: Int, spyNumber: Int, blankNumber: Int) {<br>        self.playerNumber = playerNumber<br>        self.spyNumber = spyNumber<br>        self.blankNumber = blankNumber<br>        super.init(coder: coder)<br>    }</pre><p>需先在QuestionViewController宣告init?()</p><pre><strong>@IBSegueAction</strong> <strong>func</strong> showQuestion(<strong>_</strong> coder: NSCoder) -&gt; QuestionViewController? {<br>    // 程式只有一行時可省略return<br>    QuestionViewController(coder: coder, playerNumber: playerNumber, spyNumber: spyNumber, blankNumber: blankNumber)<br>}</pre><p>接著藉由SegueAction做資料傳遞</p><h4>傳閱題目頁面</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/296/1*uyFDYH3NdWWZ1ap7PwikUw.png" /></figure><p>在QuestionViewController接受前頁傳遞人數,將每位玩家之身份與對應題目隨機分配,並由每個玩家傳閱確認題目</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/614c13efa38f638ed8312ca4c825df02/href">https://medium.com/media/614c13efa38f638ed8312ca4c825df02/href</a></iframe><p>自訂玩家、身份、題目三種型別</p><h4>投票頁面</h4><blockquote>stackView問題</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/368/1*rGV2cvGOWL4GLQcp0XvIqw.jpeg" /></figure><ul><li>問題:button在只有奇數為玩家,位置會跑掉</li><li>說明:stackView內之元件,若使用isHidden屬性將其隱藏,APP將忽略其位置</li><li>解決方法:將alpha設為1(原本擔心就算看不到也點得到,但後來peter告知看不到即無法點擊)</li></ul><blockquote>使用UIAlertController做投票確認</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/309/1*sCC-BeLSwBNhwPfCeXuNpw.png" /></figure><p><strong>step1. 建立UIAlertController物件</strong></p><pre><strong>let</strong> controller = UIAlertController(title: &quot;&quot;, message: &quot;確定要讓\(name)出局嗎?&quot;, preferredStyle: .alert)</pre><p>preferredStyle有兩種可以選擇</p><p><em>.alert 直接跳出提示訊息</em></p><p>.<em>actionSheet 由下往上彈出訊息</em></p><p><strong>step2. 建立UIAlertAction物件(提示訊息下方的選項)</strong></p><pre><strong>let</strong> confirmAction = UIAlertAction(title: &quot;滾吧！&quot;, style: .default) { (<strong>_</strong>) <strong>in<br>    self</strong>.votedPlayer(index: index)<br>}</pre><p>其中closure部分為handler: ((UIAlertAction) -&gt; Void)? = nil)當作參數,該參數為選擇該選項後要做的事情,UIAlertAction參數沒用到,因此用(_)代替</p><p><strong>step3. 呼叫.addAction()將建立的Action加入UIAlertController</strong></p><pre>controller.addAction(confirmAction)</pre><p><strong>step4. 呼叫present()顯示UIAlertController</strong></p><pre>present(controller, animated: <strong>true</strong>, completion: <strong>nil</strong>)</pre><blockquote>多個元件outlet、action</blockquote><p>此頁需產生多個button、label且每個button都有對應的動作</p><p>用outlet collection將多個元件放在array裡面,元件將按照拉進去的順序存取</p><p>將每個button拉到同一個IBAction,用switch比對button物件</p><p>詳細介紹可參考peter的文章</p><ul><li><a href="https://medium.com/%E5%BD%BC%E5%BE%97%E6%BD%98%E7%9A%84-swift-ios-app-%E9%96%8B%E7%99%BC%E5%95%8F%E9%A1%8C%E8%A7%A3%E7%AD%94%E9%9B%86/%E5%88%A9%E7%94%A8-switch-%E6%AF%94%E5%B0%8D-button-%E5%88%A4%E6%96%B7%E4%BD%BF%E7%94%A8%E8%80%85%E9%BB%9E%E6%93%8A%E7%9A%84-button-611522502aa7">利用 switch 比對 button，判斷使用者點擊的 button</a></li><li><a href="https://medium.com/%E5%BD%BC%E5%BE%97%E6%BD%98%E7%9A%84-swift-ios-app-%E9%96%8B%E7%99%BC%E5%95%8F%E9%A1%8C%E8%A7%A3%E7%AD%94%E9%9B%86/%E5%B0%87%E7%95%AB%E9%9D%A2%E4%B8%8A%E5%A4%9A%E5%80%8B%E5%85%83%E4%BB%B6%E8%AE%8A%E6%88%90-array-%E7%9A%84-outlet-collection-8b908900ce57">將畫面上多個元件變成 array 的 outlet collection</a></li></ul><p>目前已可以正常遊戲，但題庫尚屬不足，未來希望能直接從網路上抓題庫。</p><p>之後再新增<strong>自訂暱稱</strong>及<strong>忘記題目</strong>功能</p><p>參考資料</p><ul><li><a href="https://medium.com/@elsonhao88/%E5%88%A9%E7%94%A8uipickerview-%E8%AE%93textfield-%E9%81%B8%E6%93%87%E6%9B%B4%E6%9C%89%E8%B6%A3-58ec3d0c21c5">利用UIPickerView,讓textfield 選擇更有趣</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/%E9%A1%AF%E7%A4%BA%E8%AD%A6%E5%91%8A%E8%A8%8A%E6%81%AF%E5%92%8C%E9%81%B8%E5%96%AE%E7%9A%84-uialertcontroller-a7548b606eea">顯示警告訊息和選單的 UIAlertController</a></li></ul><p><em>-Github</em></p><p><a href="https://github.com/laijw4403/WhoIsSpy">laijw4403/WhoIsSpy</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7bce319466cb" width="1" height="1" alt=""><hr><p><a href="https://medium.com/peter-pan-swift-ios-class/peters-100-task-4-%E8%AA%B0%E6%98%AF%E8%87%A5%E5%BA%95-7bce319466cb">Peter’s 100 task #4 誰是臥底</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[Peter’s 100 task #3 10YearChallenge]]></title>
            <link>https://medium.com/peter-pan-swift-ios-class/peters-100-task-3-10yearchallenge-d2c82ddcd504?source=rss-70a85a72b783------2</link>
            <guid isPermaLink="false">https://medium.com/p/d2c82ddcd504</guid>
            <category><![CDATA[api]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[peter-pan]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[datepicker]]></category>
            <dc:creator><![CDATA[Tommy]]></dc:creator>
            <pubDate>Thu, 26 Nov 2020 15:40:12 GMT</pubDate>
            <atom:updated>2020-11-26T15:40:12.907Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*uvSX0FvfxXtv6Fgf" /><figcaption>Photo by <a href="https://unsplash.com/@aronvisuals?utm_source=medium&amp;utm_medium=referral">Aron Visuals</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>利用date picker &amp; slider控制時間，顯示從 flickr API 抓取的圖片</h4><p>為紀念Kobe做了一個簡單的回顧APP(2009~2019)，圖片來源是flickr，用datepicker及slider選擇年份，並顯示圖片，用switch做自動播放功能。</p><p><a href="https://www.flickr.com/">Flickr</a></p><blockquote>成品</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/294/1*FTkvE9okqTAvPbMfpxBt9Q.gif" /></figure><h4>步驟說明</h4><blockquote><strong>設定UI介面</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/626/1*jnk7UCKr6jpBAcAPx_5hPg.png" /></figure><blockquote>建立各元件之物件變數並與程式連結(IBOutlet)</blockquote><p>設定datepicker style&amp;mode，設定slider 最大值＆最小值及初始值</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/620/1*MJ-Zp9QmJBWs1nv7bH1zuw.png" /></figure><blockquote>建立各元件之互動方法</blockquote><p>同步slider、datepicker、yearLabel及switch自動播放功能</p><ul><li><strong>slider</strong></li></ul><pre>        // 取得slider年份<br>        let year = sender.value<br>        <br>        var dateComponents = DateComponents()<br>        <br>        dateComponents.calendar = Calendar.current<br>       <br>        dateComponents.year = Int(year)<br>       <br>        datePicker.date = dateComponents.date!<br>        <br>        // 同步label年份<br>        yearLabel.text = String(Int(year))<br>        <br>        // update image<br>        let index = Int(year) - 2009<br>        showImage(index)</pre><p>使用DateComponents物件的year屬性存取當前選擇的年份，取得目前的日曆物件(用於計算時間)，再使用DateComponents物件的date屬性，將目前設定的年份使用當前的日曆計算成日期，再將其存入datepicker。</p><ul><li><strong>datepicker</strong></li></ul><pre>let comp = sender.calendar.dateComponents([.year], from: sender.date)<br>        dateSlider.value = Float(comp.year!)<br>        <br>        yearLabel.text = String(comp.year!)<br>        <br>        // update imageView<br>        let index = comp.year! - 2009<br>        showImage(index)</pre><p>使用calendar.dateComponents將date拆成只有年份的DateComponents</p><ul><li><strong>switch</strong></li></ul><p>用isOn屬性判斷開關，true時建立timer每隔1.5秒自動播放下一張圖片，並重複觸發timer，false時呼叫invalidate()將timer關閉</p><ul><li><strong>timer</strong></li></ul><p>宣告一全域變數timer(若宣告在func內，則每次觸發switch便產生一個新的timer變數，將無法關閉timer)</p><pre>        timer = Timer.scheduledTimer(withTimeInterval: 1.5, repeats: true) { block  in<br>                var currentYear = Int(self.yearLabel.text!)<br>                var index = currentYear! - 2009<br>                <br>                // 判斷年份若超過2019則重新回到2009<br>                (index &gt;= 10) ? (index = 0) : (index += 1)<br>                print(&quot;index:&quot;, index)<br>                print(&quot;Auto Play&quot;)<br>                    <br>                self.showImage(index)<br>                <br>                // update slider &amp; datepicker<br>                currentYear = index + 2009<br>                self.yearLabel.text = String(currentYear!)<br>                self.dateSlider.setValue(Float(currentYear!), animated: true)<br>                <br>                var dateComponents = DateComponents()<br>                dateComponents.calendar = Calendar.current<br>                dateComponents.year = currentYear<br>                self.datePicker.date = dateComponents.date!<br>                print(&quot;update Date done&quot;)</pre><p>用scheduledTimer(withTimeInterval:repeats:block:)產生一個Timer物件</p><p><em>withTimeInterval : 觸發計時器的間隔秒數</em></p><p><em>repeats: 是否重複觸發計時器</em></p><p><em>block: 計時器觸發時所要做的事</em></p><blockquote>利用flickr API抓取圖片</blockquote><p>希望從flickr抓取2009–2019年間的Kobe照片</p><p>宣告apiKey變數存放API Key，宣告一個變數為陣列內存放2009–1019，用flickr.photos.search產生客製化url(https://medium.com/%E5%8F%83%E6%95%B8%E5%8F%AF%E5%8F%83%E8%80%83API%E6%96%87%E4%BB%B6)</p><p><a href="https://www.flickr.com/services/api/flickr.photos.search.html">flickr.photos.search</a></p><pre>struct Photo: Decodable {<br>    let farm: Int<br>    let secret: String<br>    let id: String<br>    let server: String<br>    let title: String<br>    var imageUrl: URL {<br>        return URL(string: &quot;<a href="https://farm/(farm).staticflickr.com//(server)//(id)_/(secret)_m.jpg">https://farm\(farm).staticflickr.com/\(server)/\(id)_\(secret)_m.jpg</a>&quot;)!<br>    }<br>    <br>}</pre><pre>struct PhotoData: Decodable {<br>    let photo: [Photo]<br>}</pre><pre>struct SearchData: Decodable {<br>    let photos: PhotoData<br>}</pre><p>分析取得後的JSON資料，建立SearchData物件用於存取所需Data</p><pre>if let url = URL(string: url) {<br>    // 抓取Data<br>    let task = URLSession.shared.dataTask(with: url) { (data, response, error) in<br>    // 解析JSON<br>    if let data = data, let searchData = try? JSONDecoder().decode(SearchData.self, from: data) {<br>        self.photos.remove(at: index)<br>        self.photos.insert(contentsOf: searchData.photos.photo, at: index)<br>        self.showImage(0)<br>        }<br>    }<br>    // 啟動任務<br>    task.resume()<br>}</pre><p>接著產生URLSession物件呼叫task至url抓取資料，並在completionHandler內呼叫JSONDecoder物件將所抓回的JSON資料解析為我們所需要的資料類型(SearchData)，將解析後的資料存到photos陣列內，由於抓取資料時程式在背景執行並不會依照順序，透過index將該年份所對應的Data放進photos陣列</p><p>## 最後必須呼叫task.resume()啟動task</p><blockquote>程式載入時初始化及呼叫抓取圖片之 func</blockquote><p>建立showImage func用於下載圖片並更新imageView</p><pre>let photo = photos[index]<br>imageURL = photo.imageUrl<br>downloadImage(url: imageURL) { (image) in<br>    if self.imageURL == photo.imageUrl, let image = image {<br>         DispatchQueue.main.async {<br>             self.photoImageView.image = image<br>         }<br>    }<br>}</pre><p>呼叫downloadImage方法傳入重組後的url參數下載圖片</p><p>這次作業原本只是簡單的把照片傳上去做一個datepicker與slider的連動，但看到進階題有API的使用，就很想嘗試看看，第一次接觸API，碰了很多壁看了很多文章，所幸有學姊的程式可以參考抄襲哈哈，其中幾個問題像是URL資料抓取的function、closure的用法、執行緒的問題，都是未來還需要研究的部分，還有讀懂API文件也非常重要，flickr有中文翻譯真的輕鬆許多!</p><h4>參考文章</h4><ul><li><a href="https://medium.com/%E5%BD%BC%E5%BE%97%E6%BD%98%E7%9A%84-swift-ios-app-%E9%96%8B%E7%99%BC%E5%95%8F%E9%A1%8C%E8%A7%A3%E7%AD%94%E9%9B%86/%E9%81%A9%E5%90%88%E7%B7%B4%E7%BF%92%E7%85%A7%E7%89%87%E7%89%86-app-%E7%9A%84-flickr-api-99a5a53b5f86">適合練習照片牆 App 的 flickr API</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/5-10yearchallenge-%E6%99%82%E9%96%93%E9%83%BD%E5%8E%BB%E5%93%AA%E4%BA%86-2537daccd73d">#5 10YearChallenge，時間都去哪了</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%8C%87%E5%AE%9A%E7%89%B9%E5%AE%9A%E6%99%82%E9%96%93%E7%94%9F%E6%88%90-date-%E7%9A%84%E5%B9%BE%E7%A8%AE%E6%96%B9%E6%B3%95-e6101685d6b0">指定特定時間生成 Date 的幾種方法</a></li><li><a href="https://www.jianshu.com/p/a6275cc54e04">Swift 3 关于Date的一些操作</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/%E9%80%8F%E9%81%8E-timer-%E8%A8%AD%E5%AE%9A%E6%AF%8F%E5%B9%BE%E7%A7%92%E9%87%8D%E8%A4%87%E5%9F%B7%E8%A1%8C-function-3c80f449107">透過 Timer 設定每幾秒重複執行 function</a></li><li><a href="https://franksios.medium.com/ios-closure-%E9%96%89%E5%8C%85-cf8ab16d6efc">Swift Closure(閉包)</a></li></ul><p><em>-Github</em></p><p><a href="https://github.com/laijw4403/TenYearChallenge">laijw4403/TenYearChallenge</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d2c82ddcd504" width="1" height="1" alt=""><hr><p><a href="https://medium.com/peter-pan-swift-ios-class/peters-100-task-3-10yearchallenge-d2c82ddcd504">Peter’s 100 task #3 10YearChallenge</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[Peter’s 100 task #2 deploy UIBezierPath draw pattern]]></title>
            <link>https://medium.com/peter-pan-swift-ios-class/peters-100-task-2-deploy-uibezierpath-draw-pattern-ca849f44aa43?source=rss-70a85a72b783------2</link>
            <guid isPermaLink="false">https://medium.com/p/ca849f44aa43</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[peter-pan]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Tommy]]></dc:creator>
            <pubDate>Fri, 20 Nov 2020 08:30:26 GMT</pubDate>
            <atom:updated>2020-11-20T15:08:08.509Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*IC6a8q0ixeQvdLyb" /><figcaption>Photo by <a href="https://unsplash.com/@kmkr?utm_source=medium&amp;utm_medium=referral">Kris Mikael Krister</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>利用 SwiftUI 快速預覽 UIBezierPath 的繪圖結果</h4><p>這次作業除了讓自己更加熟悉UIBezierPath外，還有助於磨練耐心…雖然畫得不是特別精緻，但我真的是在過程中不斷有想放棄的念頭哈哈，後來看到一個同學的文章，裡面提到繪圖軟體也是透過背後的程式完成繪圖，就像那位同學說的立馬醍醐灌頂，最後也漸漸掌握到訣竅，終於完成！</p><p><a href="https://medium.com/%E5%BD%BC%E5%BE%97%E6%BD%98%E7%9A%84-swift-ios-app-%E9%96%8B%E7%99%BC%E6%95%99%E5%AE%A4/%E7%94%A8%E7%A8%8B%E5%BC%8F%E7%95%AB%E5%87%BA%E5%99%97%E6%B5%AA%E5%BD%A9%E8%99%B9%E6%97%97-uibezierpath%E7%B9%AA%E5%9C%96%E7%B7%B4%E7%BF%92-9061fe131ce1">用程式畫出噗浪彩虹旗─UIBezierPath繪圖練習</a></p><h4>主題選擇</h4><p>曾經在小琉球浮潛時看過綠蠵龜相當悠遊自在的游上海面換氣，也多虧了台灣有素養的水上活動業者，非常保護也尊重海裡的生物，我們才能有幸看到海中豐富的樣貌，因此便也想對保育海龜盡一份力，就拿此圖來練習啦。</p><p>原圖</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/414/1*Yyc0eT00OK00vZP7DGt9ig.jpeg" /></figure><h4>程式架構</h4><p>烏龜底圖是用SVG轉換而成(偷懶呵呵)，字體則是親手刻的，用func把每個繪製過程包在裡面。</p><p><strong>使用到UIBezierPath(以下point參數型別皆須為CGPoint)：</strong></p><ul><li>.move 移動繪圖起始位置</li><li>.addLine 與起始點直線相連(而此point則為下一個起始點)</li><li>.addQuadCurve &amp; .addCurve 與起始點或上一點以曲線相連，利用controlPoint控制曲度</li><li>.close 將起始點與終點以直線相連</li></ul><p><strong>使用到CAShapeLayer</strong></p><ul><li>.path 存取繪圖路徑</li><li>.fillColor 設定path內的顏色(圖形顏色)</li><li>.strokeColor 設定path顏色</li><li>.lineWidth 設定path寬度</li><li>.fillRule 設定填滿規則，這邊使用CAShpaeLayerFillRule.<strong>evenOdd</strong>，簡單說明就是有個人拿著雷射筆隨意站在圖上任何一點，並發射雷射光，若醫道雷射光穿過繪製的path次數為<strong>奇數</strong>則那一點為<strong>內部</strong>，反之為外部，內部則填滿，外部則不填滿(詳細說明參考以下連結)。</li></ul><p><a href="https://www.zhangxinxu.com/wordpress/2018/10/nonzero-evenodd-fill-mode-rule/">搞懂SVG/Canvas中nonzero和evenodd填充规则 &quot; 张鑫旭-鑫空间-鑫生活</a></p><ul><li>.setAffineTransform 利用CGAffineTransform控制縮放、位移、旋轉(詳細說明可參考peter的說明，非常清楚)</li></ul><p><a href="https://medium.com/%E5%BD%BC%E5%BE%97%E6%BD%98%E7%9A%84-swift-ios-app-%E9%96%8B%E7%99%BC%E5%95%8F%E9%A1%8C%E8%A7%A3%E7%AD%94%E9%9B%86/%E5%88%A9%E7%94%A8-cgaffinetransform-%E6%8E%A7%E5%88%B6%E5%85%83%E4%BB%B6%E7%B8%AE%E6%94%BE-%E4%BD%8D%E7%A7%BB-%E6%97%8B%E8%BD%89%E7%9A%84%E4%B8%89%E7%A8%AE%E6%96%B9%E6%B3%95-dca1abbf9590">利用 CGAffineTransform 控制元件縮放，位移，旋轉的三種方法</a></p><h4>問題</h4><p>對於CGAffineTransform不太理解，縮放、旋轉後的位置是如何決定，常常跑到不知道哪去？</p><h4>成品圖</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/374/1*G61oQzlsxOjIK4pqq_a_kw.png" /></figure><h4>參考文章</h4><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/%E4%BD%9C%E6%A5%AD-52-%E4%BD%BF%E7%94%A8-swiftui-%E9%A0%90%E8%A6%BD-uibezierpath-%E7%95%AB%E5%87%BA%E5%96%9C%E6%AD%A1%E8%A7%92%E8%90%BD%E7%9A%84%E8%B2%93%E5%92%AA-ed4042a23303">作業 #52 使用 SwiftUI 預覽 UIBezierPath 畫出喜歡角落的貓咪</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/uibezierpath-%E8%B2%9D%E8%B3%BD%E7%88%BE%E7%9A%84%E9%81%8B%E7%94%A8-33fb4da08016">UIBezierPath 貝賽爾的運用</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/%E4%BD%BF%E7%94%A8-swiftui-%E9%A0%90%E8%A6%BD-uibezierpath-%E7%9A%84%E7%B9%AA%E5%9C%96%E7%B5%90%E6%9E%9C-5d5b8e679287">使用 SwiftUI 預覽 UIBezierPath 的繪圖結果</a></li></ul><p><em>-Github</em></p><p><a href="https://github.com/laijw4403/UIBezierPath-draw">laijw4403/UIBezierPath-draw</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ca849f44aa43" width="1" height="1" alt=""><hr><p><a href="https://medium.com/peter-pan-swift-ios-class/peters-100-task-2-deploy-uibezierpath-draw-pattern-ca849f44aa43">Peter’s 100 task #2 deploy UIBezierPath draw pattern</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>