<?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 Kyle X Swift on Medium]]></title>
        <description><![CDATA[Stories by Kyle X Swift on Medium]]></description>
        <link>https://medium.com/@kyleswift?source=rss-77011e3e0806------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Y9bnqYzDtPIfOsuYlPPjtA.png</url>
            <title>Stories by Kyle X Swift on Medium</title>
            <link>https://medium.com/@kyleswift?source=rss-77011e3e0806------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 00:17:10 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kyleswift/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[4週達成！商品結帳APP設計開發，直上市集實用！]]></title>
            <link>https://kyleswift.medium.com/4%E9%80%B1%E9%81%94%E6%88%90-%E5%95%86%E5%93%81%E7%B5%90%E5%B8%B3app%E8%A8%AD%E8%A8%88%E9%96%8B%E7%99%BC-%E7%9B%B4%E4%B8%8A%E5%B8%82%E9%9B%86%E5%AF%A6%E7%94%A8-2c4104b9846d?source=rss-77011e3e0806------2</link>
            <guid isPermaLink="false">https://medium.com/p/2c4104b9846d</guid>
            <category><![CDATA[apps]]></category>
            <category><![CDATA[uxui-design]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Kyle X Swift]]></dc:creator>
            <pubDate>Tue, 19 Dec 2023 10:31:19 GMT</pubDate>
            <atom:updated>2023-12-19T10:31:19.202Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*En3RyDr3OkK_EkKNjydRMw.png" /></figure><p>oSold是一款協助夢行者，將夢想轉換成具體形狀的商品銷售APP。目標族群為獨立或小規模的線下商品販售者，協助其在販售商品時能快速結算款項。oSold APP從確認需求，介面設計與軟體開發，到直接應用於創意市集只花了四個禮拜。</p><p>如何達到如此高效的敏捷開發呢？</p><p><em>更多內容請參考原文：</em></p><p><a href="https://kylelei.medium.com/4%E9%80%B1%E9%80%9F%E6%88%90-%E5%95%86%E5%93%81%E7%B5%90%E5%B8%B3app%E8%A8%AD%E8%A8%88%E9%96%8B%E7%99%BC-%E7%9B%B4%E4%B8%8A%E5%B8%82%E9%9B%86%E5%AF%A6%E7%94%A8-41d4d06d8489">4週速成！商品結帳APP設計開發，直上市集實用！</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2c4104b9846d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[透過SwiftUI Material 實現Glassmorphism]]></title>
            <link>https://kyleswift.medium.com/%E9%80%8F%E9%81%8Eswiftui-material-%E5%AF%A6%E7%8F%BEglassmorphism-9b1372eb5ea5?source=rss-77011e3e0806------2</link>
            <guid isPermaLink="false">https://medium.com/p/9b1372eb5ea5</guid>
            <category><![CDATA[swiftui]]></category>
            <dc:creator><![CDATA[Kyle X Swift]]></dc:creator>
            <pubDate>Thu, 14 Dec 2023 05:10:13 GMT</pubDate>
            <atom:updated>2023-12-14T05:10:13.094Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*CSyTyLAxrE3bQRzP.png" /></figure><p>Glassmorphism設計風格，是從2020就開始流行的UI設計趨勢，概念是Glass(玻璃)和 Skeuomorphism(擬物化)的結合，中文稱為毛玻璃效果。Glassmorphism 讓元素看起來像是透明玻璃一樣，同時保留了一些模糊的背景效果，在介面中創造了一種立體感，可以讓介面元素更加引人注目並增加互動性。Glassmorphism特別強調4個特徵：</p><ul><li>透明感/Transparency（背景模糊的磨砂效果）</li><li>物件於空間漂浮的多層次感 / Multi-layered approach with objects floating in space</li><li>強調模糊透明度的鮮明顏色 / Vivid colors to highlight the blurred transparency</li><li>於半透明物件上的細微且光亮的邊框 / A subtle, light border on the translucent objects</li></ul><p><strong>Table of content</strong></p><ul><li>SwiftUI Material</li><li>Glassmorphism with SwiftUI</li><li>Demonstration</li><li>Design Case — oThings</li></ul><p><em>更多內容請訪問以下連結：</em></p><p><a href="https://kylelei.medium.com/glassmorphism-ui-by-swiftui-e081544d2544">透過SwiftUI Material 實現Glassmorphism | Glassmorphism with SwiftUI Material</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9b1372eb5ea5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[彼得潘班與完成APP上架後的心得]]></title>
            <link>https://medium.com/peter-pan-swift-ios-class/%E5%BD%BC%E5%BE%97%E6%BD%98%E7%8F%AD%E8%88%87%E5%AE%8C%E6%88%90app%E4%B8%8A%E6%9E%B6%E5%BE%8C%E7%9A%84%E5%BF%83%E5%BE%97-eaeb810e2887?source=rss-77011e3e0806------2</link>
            <guid isPermaLink="false">https://medium.com/p/eaeb810e2887</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[apple]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Kyle X Swift]]></dc:creator>
            <pubDate>Tue, 27 Jun 2023 12:09:44 GMT</pubDate>
            <atom:updated>2023-06-29T07:13:29.428Z</atom:updated>
            <content:encoded><![CDATA[<p>在上完彼得潘202111課程結束後(是的，一年前的事了)，並沒有立即撰寫課程心得(Peter並沒有強迫大家，但儘管有我也不能說…)，原因是個人目標是希望能完成並上架一款符合個人理想體驗的App，由於已經在6月初上架我的第一款App，便想藉此分享在我的學習之路上從彼得潘獲得的收穫。給希望能掌握App開發能力或是正在道路上的朋友們增加信心。</p><p>剛開始決定要學習iOS程式開發時，買了幾本含UIKit與SwiftUI應用的電子書，想說以以前讀書的經驗，K完應該就學會了…結果按教學嘗試幾個案例後就放棄了。以現在來評估當然就是，不瞭解基本Swift程式語言就無法駕馭程式，尤其是SwiftUI邏輯基本上就是Swift語言的概念拓展。</p><p>總之，我展開了很多同學們經歷過的過程，網路搜尋相關課程然後比較與比價。後來我選擇Peter的原因是：</p><ol><li><strong>課程介紹與脈絡清楚</strong>：對於程式生手而言，能讓我可以預期我將如何學習與收穫是很重要且安心的。除非本身或周圍就有程式背景的朋友跟諮詢，不然這條路一開始就跟我們初次駕駛上高速公路一樣不安的。</li><li><strong>週末的課程安排</strong>：對於上班族而言是很友善的時間。但是當你下定決心要好好學會這項技能時，你所使用的時間將不是Only the weekend，而是All the week。</li><li><strong>CP值很高</strong>：有認真做功課的就知道了。</li></ol><p>對於程式完全很陌生的朋友我會很推薦彼得潘的課程，彼得潘課程就像有駕駛經驗的副駕會從旁引導或協助你。對於已有程式背景的人，你可以找Peter諮詢再自己評估，就算決定其它方案，也請你訂閱他的medium文章。我覺得是國內iOS領域裡耕耘很深的資源，未來一定對你有幫助。</p><p>如果你課程完成了以後，恭喜你，你將有基本的程式認知，能安穩地繼續探索未來未知的路段。以我自己而言，課程結束後我就開始學習SwiftUI，對我而言SwiftUI特點是邏輯表達更接近於人類語言的宣告式語法(Declarative syntax)，以及它核心就是Swift概念了，再來就是SwiftUI對於動畫轉場的使用非常容易與強大；接著因為要儲存資料，所以再接續學習Core Data的應用，雖然今年Apple推出了SwiftData，完全是SwiftUI的本地資料儲存方案，但SwiftUI對於CoreData的使用相對UIKit已是相當人性化。關於SwiftUI與CoreData雖然當時彼得潘課程因為篇幅有限，只有簡單提及，但在我後續自學的過程遇到一些問題，還是在他的文章內找到的解答。</p><p>針對有心想學習iOS的朋友們，以下幾點要點提供給你們參考：</p><ul><li><strong>認識彼得潘</strong>：無論是課程或文章</li><li><strong>以上架一個APP的目標</strong>：有目標才能前進，也才有成果展示你的技術能力</li><li><strong>持續學習的心態</strong>：iOS的API非常豐富，當你瞭解愈深就會發現還有很多知識需要學習，況且Apple每年都會更新(像今年的WWDC就很豐富)，但你同時也會體認到選擇Apple是對的決定</li></ul><p>最後提供我自己設計開發的app介紹給有興趣的朋友們，謝謝閱讀。</p><p><strong>APP 介紹</strong></p><p><a href="https://www.linkedin.com/pulse/othings-app-%25E5%2588%259D%25E5%259B%259E%25E7%2599%25BB%25E5%25A0%25B4-kyle-lei/?trackingId=6AFz71OGStqhiY61hwpZ%2FQ%3D%3D">oThings APP 初回登場</a></p><p><strong>APP 下載</strong></p><p><a href="https://apps.apple.com/tw/app/othings/id6448870649">‎oThings</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eaeb810e2887" width="1" height="1" alt=""><hr><p><a href="https://medium.com/peter-pan-swift-ios-class/%E5%BD%BC%E5%BE%97%E6%BD%98%E7%8F%AD%E8%88%87%E5%AE%8C%E6%88%90app%E4%B8%8A%E6%9E%B6%E5%BE%8C%E7%9A%84%E5%BF%83%E5%BE%97-eaeb810e2887">彼得潘班與完成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 Clock — iOS的里程碑專案與SwiftUI的學習開始]]></title>
            <link>https://kyleswift.medium.com/ios-clock-ios%E7%9A%84%E9%87%8C%E7%A8%8B%E7%A2%91%E5%B0%88%E6%A1%88%E8%88%87swiftui%E7%9A%84%E5%AD%B8%E7%BF%92%E9%96%8B%E5%A7%8B-e66168ab6ac5?source=rss-77011e3e0806------2</link>
            <guid isPermaLink="false">https://medium.com/p/e66168ab6ac5</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[uikit]]></category>
            <dc:creator><![CDATA[Kyle X Swift]]></dc:creator>
            <pubDate>Fri, 08 Apr 2022 15:27:04 GMT</pubDate>
            <atom:updated>2022-04-08T15:27:04.409Z</atom:updated>
            <content:encoded><![CDATA[<h3>iOS Clock — iOS的里程碑專案</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m7Ry-JeymKqSF-_f_KzSpQ.png" /></figure><p>iOS時鐘是接觸iOS程式後第一個功能完整實踐的app專案，作為初步階段的自我挑戰。目標完整呈現iOS時鐘的所有功能和UI設計，包含了世界時鐘、鬧鐘、碼錶與計時器的功能，除了串接後台API的功能外，基本的Swift程式語言與UIKit框架技能都用上了。</p><p>未來會朝向SwiftUI的應用並結合UI設計，並將相關文章發佈在以下出版，有興趣的朋友歡迎追蹤。</p><p><a href="https://medium.com/hybrid-x">Hybrid X</a></p><p>儘管平時在設計UI便著重於資訊階層與細節的處理，在重新建構iOS時鐘的功能與設計過程中，因瞭解iOS UI 元件可提供的參數定義，相較以往能更全面地思索UI的可能性，回想到以前從事工業設計時很重要的一個觀念：「瞭解材質的特性與製造的原理，才能掌握你的設計。」，而呼應到現今的軟體能力與生態則是：</p><blockquote><em>瞭解元件特性與程式原理，才能駕馭想像力與掌握設計。</em></blockquote><p>以下是在執行iOS時鐘開發所體會到的幾項元件特性，可做為UI設計的原則參考：</p><ol><li>畫面資訊階層，隨著使用者的瀏覽而動態的改變</li><li>區分畫面狀態，隱藏當前狀態不需要的功能資訊</li><li>資訊的視覺化，純文字數位資訊的視覺與圖像化</li></ol><h4>畫面資訊階層，隨著使用者的瀏覽而動態的改變</h4><p>iOS 導航列的標題提供了largeTitleDisplayMode的參數，允許定義進入頁面時顯示large title，可一目了然知道當前頁面的功能；頁面向下滑時，標題變成small title，可專注在內文資訊。</p><h4>區分畫面狀態，隱藏當前狀態不需要的功能資訊</h4><p>一般清單提供資料的刪除、排序等的編輯功能，當沒有任何資料的時候不需要讓使用者看到編輯按鈕。可根據資料陣列isEmpty的布林參數作為顯示與否的判斷。</p><h4>資訊的視覺化，純文字數位資訊的視覺與圖像化</h4><p>以碼表與計時器功能來說，固然可以純數字顯示，透過數字的變化使用者也能感受到時間的改變。但透過圖像視覺的輔助，除了能傳遞更強烈的時間速度，透過刻度也能讓使用者意識到目前的時間階段，以更直覺的方式接收資訊。</p><figure><img alt="Animation image, might take time for loading" src="https://cdn-images-1.medium.com/max/1024/1*SGsRhP_XI9elyS11P6ATAA.gif" /></figure><p>以下是最終完整的程式碼，之後會嘗試用SwiftUI重新建構一次。</p><p><a href="https://github.com/kylekylei/iOSClock">GitHub - kylekylei/iOSClock</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e66168ab6ac5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[#30 模仿 iOS Clock App - 4 ：Timer]]></title>
            <link>https://medium.com/peter-pan-swift-ios-class/30-%E6%A8%A1%E4%BB%BF-ios-clock-app-4-timer-defe4a8e6e48?source=rss-77011e3e0806------2</link>
            <guid isPermaLink="false">https://medium.com/p/defe4a8e6e48</guid>
            <category><![CDATA[uikit]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Kyle X Swift]]></dc:creator>
            <pubDate>Sat, 12 Feb 2022 14:56:19 GMT</pubDate>
            <atom:updated>2022-02-12T14:59:44.707Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*9Q9lEsEACj1A5Ui8rD8l9w.gif" /></figure><p><strong>模仿 iOS Clock App系列：</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%E6%95%99%E5%AE%A4/27-%E6%A8%A1%E4%BB%BF-ios-clock-app-1-world-clock-e2b6f70cc2ca">#27 模仿 iOS Clock App - 1 ：World Clock</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/28-%E6%A8%A1%E4%BB%BF-ios-clock-app-2-alarm-37b43edaf9d1">#28 模仿 iOS Clock App — 2 ：Alarm</a></li><li><a href="https://kyleswift.medium.com/29-%E6%A8%A1%E4%BB%BF-ios-clock-app-3-stopwatch-96ac6888328f">#29 模仿 iOS Clock App - 3 ：Stopwatch</a></li></ul><p>繼上一篇完成碼錶功能後，這次接續完成最後的計時器功能。</p><h3>實現功能</h3><ul><li>實現 timer 的 start，pause，resume，cancel 功能。</li></ul><h3>建立Time picker</h3><p>UIKit內建的Date Picker只有顯示小時與分鐘，沒有秒數。所以使用Picker View進行客製化。</p><h4>時間單位Label</h4><p>如不定義何事label的寬度的話，寬度會被壓縮而無法完全顯示lable。</p><pre>extension UIPickerView {<br>    func setPickerLabelSize(labels: [Int: UILabel]) {<br>        let fontSize: CGFloat = 20<br>        let labelWidth: CGFloat = self.frame.width / CGFloat(self.numberOfComponents)<br>        let y: CGFloat = (self.frame.height / 2) - (fontSize / 2)<br>        <br>        for i in 0...self.numberOfComponents {<br>            if let label = labels[i] {<br>                label.frame = CGRect(x: labelWidth * CGFloat(i), y: y, width: labelWidth, height: fontSize)<br>                label.font = UIFont.systemFont(ofSize: fontSize, weight: .medium)<br>                label.backgroundColor = .clear<br>                label.textAlignment = NSTextAlignment.left<br>                self.addSubview(label)<br>            }<br>        }<br>    }<br>}</pre><p>就如table view一樣，picker view也需要代理。</p><pre>let numbersOf24 = [Int](0...23)<br>let numbersOf60 = [Int](0...59)</pre><pre>extension TimerViewController: UIPickerViewDataSource, UIPickerViewDelegate {<br>  </pre><p>包含數字與label總共６個欄位</p><pre>func numberOfComponents(in pickerView: UIPickerView) -&gt; Int {<br>        6<br>    }   </pre><p>每個欄位的顯示數量</p><pre>func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -&gt; Int {<br>        switch component {<br>        case 0: return numbersOf24.count //小時<br>        case 2: return numbersOf60.count //分鐘<br>        case 4: return numbersOf60.count //秒數<br>        default: return 1 //label<br>        }</pre><pre>}<br>   </pre><p>每個欄位的顯示內容</p><pre>func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -&gt; String? {<br>        switch component {<br>        case 0: return numbersOf24[row].description<br>        case 1:<br>            let hour = UILabel()<br>            hour.text = &quot;hours&quot;<br>            timePicker.setPickerLabelSize(labels: [1 : hour])<br>            return &quot;&quot;<br>        case 2: return numbersOf60[row].description<br>        case 3:<br>            let min = UILabel()<br>            min.text = &quot;min&quot;<br>            timePicker.setPickerLabelSize(labels: [3 : min])<br>            return &quot;&quot;<br>        case 4: return numbersOf60[row].description<br>        case 5:<br>            let sec = UILabel()<br>            sec.text = &quot;sec&quot;<br>            timePicker.setPickerLabelSize(labels: [5 : sec])<br>            return &quot;&quot;<br>        default: return &quot;error&quot;<br>        }</pre><pre>}    <br></pre><p>選擇列後直接儲存數字。</p><pre>func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {<br>        switch component {<br>        case 0: hour = numbersOf24[row]<br>        case 2: minute = numbersOf60[row]<br>        case 4: second = numbersOf60[row]<br>        default: return<br>        }<br>    }<br>}</pre><h3>計時</h3><h4>時間處理</h4><p>將從time picker獲取到的時間即時換算成時間差</p><pre>var timeInterval: Int {<br>        hour * 3600 + minute * 60 + second<br>    }</pre><p>設定結束時間的字串顯示</p><pre>func setEndTime() -&gt; String {<br>        let endTimeInterval: TimeInterval = TimeInterval(timeInterval) + Date().timeIntervalSince1970<br>        endTime = Date(timeIntervalSince1970: endTimeInterval)<br>        let formatter = DateFormatter()<br>        formatter.dateStyle = .short<br>        formatter.dateFormat = &quot;HH:mm&quot;<br>        return formatter.string(from: endTime)<br>    }</pre><h4>開始計時</h4><p>顯示剩餘的倒數時間，倒數到0之後會結束倒數。</p><pre>func start() {<br>        countdownInterval = isReset ? Double(timeInterval) : Double(resumeInterval)<br>        isReset = false<br>        isRunning = true<br>        <br>        endTimeLabel.text = setEndTime()<br>        <br>        <br>        let startAngle: CGFloat = 270<br>        let perAngle = CGFloat(360 / timeInterval)<br>        var currentAngle: CGFloat = 360</pre><pre>timer = Timer.scheduledTimer(withTimeInterval: 0.01, repeats: true, block: { [self](_) in<br>            let countdownStr:String = {<br>                let hour = (Int(countdownInterval) / 3600).formatted(.number.precision(.integerLength(2)))<br>                let minute = ((Int(countdownInterval) % 3600) / 60).formatted(.number.precision(.integerLength(2)))<br>                let second = (Int(countdownInterval) % 60).formatted(.number.precision(.integerLength(2)))<br>                return Int(hour) == 0 ? &quot;\(minute):\(second)&quot; : &quot;\(hour):\(minute):\(second)&quot;<br>            }()<br>            digitalTimerLabel.text = countdownStr<br>            <br>    </pre><p>顯示剩餘時間的progress bar</p><pre>currentAngle = startAngle + CGFloat(countdownInterval) * perAngle<br>            let path = UIBezierPath()<br>            path.addArc(withCenter: center, radius: radius, startAngle: startAngle.degree, endAngle: currentAngle.degree, clockwise: true)<br>            progressBar.path = path.cgPath<br>            <br>            countdownInterval -= 0.01<br>            <br>            if countdownInterval &lt; 0 {<br>                createNotificationNow()<br>                cancel()<br>            }<br>        })<br>        timer.fire()</pre><pre>}</pre><h3>成果展示</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2CKbGSnhNBh7P0zLvMHGng.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iy8bpdG_0V5cZNdueiocqg.png" /></figure><p><a href="https://github.com/kylekylei/iOSClock/releases/tag/4.0">Release 4.0 · kylekylei/iOSClock</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=defe4a8e6e48" width="1" height="1" alt=""><hr><p><a href="https://medium.com/peter-pan-swift-ios-class/30-%E6%A8%A1%E4%BB%BF-ios-clock-app-4-timer-defe4a8e6e48">#30 模仿 iOS Clock App - 4 ：Timer</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[#29 模仿 iOS Clock App - 3 ：Stopwatch]]></title>
            <link>https://medium.com/peter-pan-swift-ios-class/29-%E6%A8%A1%E4%BB%BF-ios-clock-app-3-stopwatch-96ac6888328f?source=rss-77011e3e0806------2</link>
            <guid isPermaLink="false">https://medium.com/p/96ac6888328f</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[uikit]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Kyle X Swift]]></dc:creator>
            <pubDate>Sat, 12 Feb 2022 10:08:14 GMT</pubDate>
            <atom:updated>2022-02-13T05:32:29.404Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*EN-sGdfGh5NeOdtOl-vH5Q.gif" /></figure><p><strong>模仿 iOS Clock App系列：</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%E6%95%99%E5%AE%A4/27-%E6%A8%A1%E4%BB%BF-ios-clock-app-1-world-clock-e2b6f70cc2ca">#27 模仿 iOS Clock App - 1 ：World Clock</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/28-%E6%A8%A1%E4%BB%BF-ios-clock-app-2-alarm-37b43edaf9d1">#28 模仿 iOS Clock App — 2 ：Alarm</a></li></ul><p>繼上一篇完成鬧鐘功能後，這次接續完成碼錶的功能。</p><h3>實現功能</h3><ul><li>實現碼錶的 start，stop，lap(分段)，reset 功能。</li><li>已分段的時間會顯示最長與最短的時間。</li><li>App 進入背景，再回到前景時，碼錶顯示的數字要包含在背景的時間。</li><li>水平滑動切換以數字和圓形時鐘顯示的畫面。</li></ul><h3>數字和類比時鐘畫面切換</h3><h4>利用Scroll View 和Container View完成可水平滑動切換</h4><ul><li>利用scroll view實現水平滑動，要把Page Enabled打開才能整頁切換。</li><li>加入水平排列的stack view，stack view加入兩個container view。</li><li>container view分別連接到數字時鐘和類比時鐘。</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kBpBL_t8-D--XlwxetYXPA.png" /></figure><p>細節步驟可參考彼得潘的教學</p><p><a href="https://apppeterpan.medium.com/%E5%88%A9%E7%94%A8-scroll-view-container-view-%E6%B0%B4%E5%B9%B3%E6%BB%91%E5%8B%95%E5%88%87%E6%8F%9B%E9%A0%81%E9%9D%A2-18cec0f910dc">利用 scroll view &amp; container view 水平滑動切換頁面</a></p><h4>Scroll view的 page indicator</h4><pre><a href="http://twitter.com/IBOutlet">@IBOutlet</a> weak var containerIndicator: UIPageControl!<br>var pageNumber: Int = 0</pre><blockquote>用UIScrollViewDelegate的scrollViewDidScroll方法，偵測scroll view滑動後的行為。</blockquote><p>利用內容移動的Ｘ距離/整個scroll view寬度便可以得到頁面整數。</p><pre>extension StopwatchViewController: UIScrollViewDelegate {<br>    func scrollViewDidScroll(_ scrollView: UIScrollView) {<br>        pageNumber = Int(stopWatchScrollView.contentOffset.x / stopWatchScrollView.bounds.size.width)<br>        containerIndicator.currentPage = pageNumber<br>    }<br>}</pre><p>記得指定scroll view代理</p><pre>override func viewDidLoad() {<br>        super.viewDidLoad()       <br><br>        stopWatchScrollView.delegate = self</pre><h4>傳遞資料給透過Container view連結view controller</h4><blockquote>重點來了！如何在parent view將資料傳遞給child view?只要透過seague連接的view就可以使用到func prepare的功能來傳遞資料。</blockquote><p>首先建立 兩個view controller的變數</p><pre>private var digitViewController: DigitViewController?<br>private var analogViewController:  AnalogViewController?</pre><p>在與兩個container view連接的segue identifier分別命名為digitTimeSegue和analogTimeSegue。接著將個別segue終點連到的controller指定為digitViewController和analogViewController。</p><pre>override func prepare(for segue: UIStoryboardSegue, sender: Any?) {<br>        if segue.identifier == &quot;digitTimeSegue&quot;, let controller = segue.destination as? DigitViewController {<br>            digitViewController = controller<br>        }<br>        if  segue.identifier == &quot;analogTimeSegue&quot;, let controller = segue.destination as? AnalogViewController {<br>            analogViewController = controller                      <br>        }</pre><p>這樣就可以在parent controller控制container view的controller了。</p><h3>計時功能</h3><h4>開始計時</h4><p>經過研究理解後，利用Date()建立時間戳記來計算時間差，會比只使用timer來加數值累計時間來的精準，尤其是app到背景後timer可能會不精準。</p><p>所以當按下開始按鈕變建立mainStartTime，利用 mainTimeInterval = -(mainStartTime?.timeIntervalSinceNow ?? 0) 可以計算與目前時間的時間差。</p><p>另外要按下暫停後，利用mainRestingTimeeInterval = mainRestingTimeeInterval + Date().timeIntervalSince(mainStartTime ?? Date()) 紀錄當下的時間差。</p><p>所以重新按下開始按鈕後，mainStartTime會更新為當下的時間，再加上mainRestingTimeeInterval就可以繼續暫停前的時間了。</p><p>也因為要排除暫停的時間，mainTimeInterval的程式要更新為</p><p>mainTimeInterval = -(mainStartTime?.timeIntervalSinceNow ?? 0) + mainRestingTimeeInterval</p><pre>class StopwatchViewController: UIViewController {<br>var isReset = true //是否清空<br>var isRunning = false //是否正在計時</pre><pre>var mainStartTime: Date? //按下開始時的時間<br>var mainTimeInterval: TimeInterval = 0 //按下開始到目前的時間差<br>var mainRestingTimeeInterval: TimeInterval = 0 //按下暫停到重新開始的時間差<br>var mainTimeString: String {</pre><p>按下開始時便啟動func start()與裡面的timer，將要即時變化的時間計算寫在closure裡</p><pre>func start() {<br>        isReset = false<br>        isRunning = true<br>        <br>        mainStartTime = Date()<br>        lapStartTime = Date()<br>        lapLabel.text = &quot;Lap \(lapIndex)&quot;<br>        <br>        timer = Timer.scheduledTimer(withTimeInterval: 0.0, repeats: true, block: { [self](_) in<br>            mainTimeInterval = -(mainStartTime?.timeIntervalSinceNow ?? 0) + mainRestingTimeeInterval           <br>            <br>            lapTimeInterval = -(lapStartTime?.timeIntervalSinceNow ?? 0) + lapRestingTimeeInterval<br>            timeLabel.text = lapTimeString<br>            <br>        })<br>    }</pre><h4>停止計時</h4><pre>func stop() {        <br>        mainRestingTimeeInterval = mainRestingTimeeInterval + Date().timeIntervalSince(mainStartTime ?? Date())<br>        lapRestingTimeeInterval = lapRestingTimeeInterval + Date().timeIntervalSince(lapStartTime ?? Date())//<br>        isRunning = false<br>        timer.invalidate()<br>    }</pre><h3>Lap分段時間</h3><pre>struct Lap: Codable {<br>    let lapIndex: Int<br>    let lapTimeString: String<br>    let lapTime: TimeInterval    <br><br>}</pre><p>當碼錶開始跑動時按下Lap會將目前的lap記錄下來，並重新重新開始計算新Lap時間。</p><pre>func setLap(){<br>        lapStartTime = Date()<br>        lapRestingTimeeInterval = 0<br>        laps.insert(Lap(lapIndex: lapIndex, lapTimeString: lapTimeString, lapTime: lapTimeInterval), at: 0)<br>        lapIndex += 1<br>        lapLabel.text = &quot;Lap \(lapIndex)&quot;<br>        tableView.reloadData()        <br></pre><h4>比較時間長短</h4><p>紀錄最長與最短的時間差，用於lap清單裡顯示最長與最短的分段</p><pre>var maxLapTime: TimeInterval = 0<br>var minLapTime: TimeInterval = TimeInterval(Int.max)</pre><pre>maxLapTime = lapTimeInterval &gt; maxLapTime ? lapTimeInterval : maxLapTime<br>        minLapTime = lapTimeInterval &lt; minLapTime ? lapTimeInterval : minLapTime<br>    }</pre><h4>顯示時間分段紀錄</h4><pre>extension StopwatchViewController: UITableViewDataSource, UITableViewDelegate {<br>    <br>    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -&gt; Int {<br>        laps.count<br>    }<br>    <br>    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -&gt; UITableViewCell {<br>        let cell = tableView.dequeueReusableCell(withIdentifier: &quot;\(StopwatchTableViewCell.self)&quot;, for: indexPath) as! StopwatchTableViewCell<br>        let lap = laps[indexPath.row]<br>            cell.lapLabel.text = &quot;Lap \(lap.lapIndex)&quot;<br>            cell.timeLabel.text = lap.lapTimeString<br>        <br>        if laps.count &gt; 1 {<br>            if lap.lapTime &gt;= maxLapTime {<br>                cell.lapLabel.textColor = .lightRed<br>                cell.timeLabel.textColor = .lightRed<br>            }else if lap.lapTime &lt;= minLapTime {<br>                cell.lapLabel.textColor = .lightGreen<br>                cell.timeLabel.textColor = .lightGreen<br>            }else {<br>                cell.lapLabel.textColor = .white<br>                cell.timeLabel.textColor = .white<br>            }<br>        }<br>        return cell<br>    }<br>}</pre><h3>時鐘顯示</h3><h4>數字時鐘</h4><pre>//顯示目前的時間字串<br>digitViewController?.digitTimeLabel.text = mainTimeString</pre><h4>類比時鐘</h4><pre>//顯示目前的時間字串<br>analogViewController?.digitTimeLabel.text = mainTimeString </pre><pre>//目前主要的時間差，提供指針旋轉的數值計算<br>analogViewController?.mainTimeInterval = mainTimeInterval </pre><pre>//目前分段的時間差，提供指針旋轉的數值計算analogViewController?.lapTimeInterval = lapTimeInterval<br>analogViewController?.lapWatchView.isHidden = laps.isEmpty ? true : false</pre><h4>指針旋轉</h4><p>建立以下三個個別包含分針、秒針與分段指針繪圖的view。</p><ul><li>mainMinuteWatchView</li><li>mainSecondWatchView</li><li>lapWatchView</li></ul><p>控制指針旋轉的指令如下，至於指針繪圖的部分這裡就不贅述了。</p><pre>class AnalogViewController: UIViewController {</pre><pre><br>var center: CGPoint?<br>    var mainTimeInterval: TimeInterval = 0 {<br>        didSet {<br>            let secondAngle = CGFloat(mainTimeInterval.truncatingRemainder(dividingBy: 60) * 6)<br>            mainSecondWatchView.transform = CGAffineTransform.identity.rotated(by: secondAngle.degree)<br>            <br>            let minuteAngle = CGFloat(mainTimeInterval / 60 * 6)<br>            mainMinuteWatchView.transform = CGAffineTransform.identity.rotated(by: minuteAngle.degree)<br>        }<br>    }<br>    var lapTimeInterval: TimeInterval = 0 {<br>        didSet {<br>            let secondAngle = CGFloat(lapTimeInterval.truncatingRemainder(dividingBy: 60) * 6)<br>            lapWatchView.transform = CGAffineTransform.identity.rotated(by: secondAngle.degree)<br>        }<br>    }</pre><h3>成果展示</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_vKUr4ym_p4BrPbTGeW4-A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h8rPfVlFSzOBt1n5mQNs7w.png" /></figure><p><a href="https://github.com/kylekylei/iOSClock/releases/tag/3.0">Release 3.0 · kylekylei/iOSClock</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=96ac6888328f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/peter-pan-swift-ios-class/29-%E6%A8%A1%E4%BB%BF-ios-clock-app-3-stopwatch-96ac6888328f">#29 模仿 iOS Clock App - 3 ：Stopwatch</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[#28 模仿 iOS Clock App — 2 ：Alarm]]></title>
            <link>https://medium.com/peter-pan-swift-ios-class/28-%E6%A8%A1%E4%BB%BF-ios-clock-app-2-alarm-37b43edaf9d1?source=rss-77011e3e0806------2</link>
            <guid isPermaLink="false">https://medium.com/p/37b43edaf9d1</guid>
            <category><![CDATA[ios-alarm]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[uikit]]></category>
            <dc:creator><![CDATA[Kyle X Swift]]></dc:creator>
            <pubDate>Wed, 26 Jan 2022 14:36:40 GMT</pubDate>
            <atom:updated>2022-02-12T03:25:10.931Z</atom:updated>
            <content:encoded><![CDATA[<h3>#28 模仿 iOS Clock App - 2 ：Alarm</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*0sc0YtGXsuRwOvGT4obvlA.gif" /></figure><p><strong>模仿 iOS Clock App系列：</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%E6%95%99%E5%AE%A4/27-%E6%A8%A1%E4%BB%BF-ios-clock-app-1-world-clock-e2b6f70cc2ca">#27 模仿 iOS Clock App - 1 ：World Clock</a></p><p>繼上一篇完成World Clock功能後，這次完成鬧鐘的功能。除了睡眠時間調整和鈴聲的功能，其它都盡量還原呈現。</p><h3>實現功能</h3><ul><li>鬧鐘的新增，修改，刪除和儲存。</li><li>編輯鬧鐘的欄位，包含鬧鐘時間與名稱、週日期重複設定，鈴聲設定。</li><li>利用UserNotifications實現鬧鐘功能(目前有立即觸發兩次的現象的debug)。</li><li>利用UIResponder與NotificationCenter實現自動點選textField與觸發keyboard展開且textField向上移動</li><li>利用textFieldShouldReturn按鍵盤return結束編輯</li></ul><h3>練習目地</h3><ul><li>UIResponder</li><li>NotificationCenter</li><li>UserNotifications</li></ul><h3>週日期是否重複的功能</h3><p>利用weekdaySymbols建立週日期的陣列，格式顯示成Monday…。這樣就不用自己手打星期一到星期日</p><pre>let weekdaySymbols: [String] = {<br>    let formatter = DateFormatter()<br>    guard let weekdaySymbols = formatter.weekdaySymbols else { return [&quot;&quot;] }<br>    return weekdaySymbols<br>}()</pre><p>weekdaySymbols建立repeatDays，要同時記錄週日期與是否重複，</p><pre>var repeatDays: [RepeatDay] = {<br>        var repeatDays = [RepeatDay]()<br>        for weekdaySymbol in weekdaySymbols {<br>            let repeatDay = RepeatDay(weekDay: weekdaySymbol, isRepeat: true)<br>            repeatDays.append(repeatDay)<br>        }<br>        return repeatDays<br> }()</pre><pre>struct RepeatDay: Codable {<br>    var weekDay: String<br>    var isRepeat: Bool<br>}</pre><p>選擇重複的天數將顯示checkmark</p><pre>override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -&gt; UITableViewCell {<br>        let cell = tableView.dequeueReusableCell(withIdentifier: &quot;\(RepeatTableViewCell.self)&quot;, for: indexPath) as! RepeatTableViewCell<br>        let row = indexPath.row<br>        cell.weekDayButton.text = &quot;Every \(String(describing: repeatDays[row].weekDay))&quot;</pre><pre>//如果已選擇將顯示checkmark</pre><pre>        if repeatDays[row].isRepeat {<br>            cell.accessoryType = .checkmark<br>            cell.selectionStyle = .none<br>        }</pre><pre>return cell<br>    }</pre><p>點選表格將開關該週日期是否重複</p><pre>override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {<br>        let cell  = tableView.cellForRow(at: indexPath)<br>        <br>        if cell?.accessoryType == .checkmark {<br>            cell?.accessoryType = .none<br>            repeatDays[indexPath.row].isRepeat = false<br>            <br>        } else {<br>            cell?.accessoryType = .checkmark<br>            repeatDays[indexPath.row].isRepeat = true<br>        }<br>    }</pre><h3>鬧鐘名稱編輯</h3><p>進入畫面時，textField為firstUIResonder，keyboard將自動展開。</p><pre>textField.becomeFirstResponder()</pre><p>keyboard展開後，textField往上移動，避免被keyboard遮到。</p><h4>利用NotificationCenter通知系統鍵盤展開的行為</h4><pre><a href="http://twitter.com/objc">@objc</a> func handleKeyboardDidShowNotificaion() {<br>        UIViewPropertyAnimator(duration: 0.3, curve: .easeInOut) {<br>            self.textField.transform = CGAffineTransform(translationX: 0, y: -100)<br>        }.startAnimation()<br>    }</pre><pre>NotificationCenter.default.addObserver(self, selector: #selector(handleKeyboardDidShowNotificaion), name: UIResponder.keyboardDidShowNotification, object: nil)</pre><h4>利用textFieldShouldReturn按鍵盤返回鍵便能結束編輯</h4><p>指定textField的delegate</p><pre>textField.delegate = self</pre><p>按return鍵後執行unwindTSegue</p><pre>extension LabelViewController: UITextFieldDelegate {<br>    func textFieldShouldReturn(_ textField: UITextField) -&gt; Bool {<br>        textField.resignFirstResponder()<br>        performSegue(withIdentifier: &quot;unwindToEditAlarm&quot;, sender: nil)    <br>        return true<br>    }</pre><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-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></p><h3>本地推播通知</h3><p>本地推播通知使用的觸發條件，主要有三種：</p><ol><li>UNTimeIntervalNotificationTrigger 間隔多久，發送一次通知。</li><li>UNCalendarNotificationTrigger 指定時間點，發送一次通知。</li><li>UNLocationNotificationTrigger 進入某個範圍或離開某個範圍，發送一次通知。</li></ol><p>本鬧鐘功能使用的是UNCalendarNotificationTrigger</p><p><a href="https://developer.apple.com/documentation/usernotifications/scheduling_a_notification_locally_from_your_app">Scheduling a notification locally from your app | Apple Developer Documentation</a></p><h4>向系統請求授權</h4><p>在 AppDelegate.swift內，app完成啟動後向系統請求授權。APP初次使用便會收到授權請求。</p><p>先import UserNotifications的API</p><pre>import UserNotifications</pre><p>接著didFinishLaunchingWithOptions的函式內建立授權申請的程式。</p><pre>func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -&gt; Bool {<br>    <br>        UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound]) { granted, error in<br>            if granted {<br>                print(&quot;Success&quot;)<br>            } else {<br>                print(&quot;Failed&quot;)<br>            }<br>        }<br>        <br>        return true<br>    }</pre><p>options裡包含需要授權的形式，這裡包含.alert, .sound 還有.badge可以授權。</p><h4>註冊本地推播實現鬧鐘通知功能</h4><p>宣告UNMutableNotificationContent()輸入推播的title與內文，當然包含鬧鐘的鈴聲。</p><pre>func createNotifiction(time: Date, label: String, sound: String, weekdaySet: [Int]) {<br>        <br>        let content = UNMutableNotificationContent()<br>        content.title = &quot;K Clock&quot;<br>        content.body = label<br>        content.sound = UNNotificationSound(named: UNNotificationSoundName(rawValue: &quot;\(sound).mp3&quot;))<br>        <br>       </pre><h4>註冊鬧鐘</h4><p>利用dataComponets.weekday輸入數值可帶入工作日，如果輸入3則代表Tuesday，以此類推。所以利用for-in可以為單一鬧鐘定義重複的設定。</p><pre>for weekday in weekdaySet {<br>            var dataComponets = Calendar.current.dateComponents([.hour, .minute], from: time)<br>            dataComponets.weekday = weekday</pre><pre>let trigger = UNCalendarNotificationTrigger(dateMatching: dataComponets, repeats: false)<br>            let request = UNNotificationRequest(identifier: &quot;set\(alarmIndex)&quot;, content: content, trigger: trigger)<br>            UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)<br>            <br>            alarmIndex += 1<br>        }<br>    }</pre><h4>允許APP開啟時一樣收到推播</h4><p>如果做到目前的設定，只有回到home可以收到推播，如果要在app開啟時仍然收到通知則要設定以下程式。</p><pre>func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: <a href="http://twitter.com/escaping">@escaping</a> (UNNotificationPresentationOptions) -&gt; Void) {<br>        completionHandler([.sound, .banner, .list, .badge])<br>    }</pre><h3>成果展示</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S7J1J___xqIFzzAjlfZOaw.png" /></figure><p><a href="https://github.com/kylekylei/iOSClock/releases/tag/2.0">Release 2.0 · kylekylei/iOSClock</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=37b43edaf9d1" width="1" height="1" alt=""><hr><p><a href="https://medium.com/peter-pan-swift-ios-class/28-%E6%A8%A1%E4%BB%BF-ios-clock-app-2-alarm-37b43edaf9d1">#28 模仿 iOS Clock App — 2 ：Alarm</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[#27 模仿 iOS Clock App - 1 ：World Clock]]></title>
            <link>https://medium.com/peter-pan-swift-ios-class/27-%E6%A8%A1%E4%BB%BF-ios-clock-app-1-world-clock-e2b6f70cc2ca?source=rss-77011e3e0806------2</link>
            <guid isPermaLink="false">https://medium.com/p/e2b6f70cc2ca</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[uikit]]></category>
            <category><![CDATA[ios-clock]]></category>
            <dc:creator><![CDATA[Kyle X Swift]]></dc:creator>
            <pubDate>Mon, 17 Jan 2022 15:21:36 GMT</pubDate>
            <atom:updated>2022-02-12T09:23:59.085Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_dTV-A6p0XHI10PiE_IXZw.gif" /></figure><p>原本只打算利用iOS Clock來練習頁面間資料傳遞的功能，但發現其所有功能涵蓋了很多之前沒有練習過的技術，可作為交叉學習與練習的範例。</p><h4>實現功能</h4><ul><li>取得世界上主要的城市清單。</li><li>城市清單的分類排序和右邊的索引功能。</li><li>搜尋城市的功能</li><li>取得城市的時間。</li><li>城市時間的新增，刪除和儲存。</li><li>表格資料的刪除和順序調整功能(利用右邊的三條線調整順序)。</li><li>使用者設定的資料儲存</li></ul><h4>練習目地</h4><ul><li>清單的section分類與sectionIndexTitles 索引功能</li><li>UISearchBar搜尋功能與畫面控制</li><li>清單資料的選取與傳遞回前一頁</li><li>tableView cell的新增、刪除與調整順序</li><li>UserDefaults的使用者參數設定</li></ul><h3>時鐘顯示的資料</h3><p>由於後續需要建立可索引的時區城市Dictionary，針對每筆城市先建立所有需要顯示在畫面上的物件。以下是要顯示的資料說明：</p><ul><li>identifier : 從系統獲取的時區id，基本上顯示的格式如 “Asia/<em>Taipei</em>”</li><li>cityName：將id拆轉換成只有城市的名稱，如<em>Taipei</em></li><li>relativeHours：相對本地時區的時間差如 +8HRS，會需要特別處理正負跟複數顯示</li><li>relativeDate：相對本地的日期，顯示成Yesterday, Today, Tomorrow</li><li>localTime：當地時間</li></ul><pre>struct City {</pre><pre>    var identifier: String<br>    init(identifier: String) {<br>        self.identifier = identifier<br>    }<br><br>    var cityName: String {<br>        String(identifier.split(separator: &quot;/&quot;).last!).replacingOccurrences(of: &quot;_&quot;, with: &quot; &quot;)<br>    }</pre><pre>    var relativeHours: String {<br>        let timeInterval = TimeZone(identifier: identifier)!.secondsFromGMT() - TimeZone.current.secondsFromGMT()<br>        let hours = timeInterval / 3600<br>        return &quot;\(hours.signum() == 1 ? &quot;+&quot; : &quot;&quot;)\(String(format: &quot;%.1d&quot;, hours))\(abs(hours) == 1 ? &quot;HR&quot; : &quot;HRS&quot;)&quot;<br>    }</pre><pre>    var relativeDate: String {<br>        let dateFormater = DateFormatter()<br>        dateFormater.timeStyle = .none<br>        dateFormater.dateStyle = .medium<br>        dateFormater.timeZone = TimeZone(identifier: identifier)<br>        dateFormater.doesRelativeDateFormatting = true<br>        return dateFormater.string(from: .now)<br>    }</pre><pre>    var localTime: String {<br>        let dateFormater = DateFormatter()<br>        dateFormater.timeStyle = .short<br>        dateFormater.timeZone = TimeZone(identifier: identifier)<br>        dateFormater.dateFormat = &quot;HH:mm&quot;<br>        return dateFormater.string(from: .now)<br>    }<br>}</pre><h3>世界城市清單</h3><p>利用 TimeZone.knownTimeZoneIdentifiers 獲取系統所知道的所有時區，再存入cities 的時區資料裡面</p><pre><br>let timeZoneIdentifiers = TimeZone.knownTimeZoneIdentifiers</pre><pre>var cities = [City]()</pre><pre>override func viewDidLoad() {<br>        super.viewDidLoad()       <br>        <br>        for timeZoneIdentifier in timeZoneIdentifiers {<br>            let city = City(identifier: timeZoneIdentifier)<br>            cities.append(city)<br>        }</pre><p>利用 Dictionary 建立城市索引，再以索引key建立索引陣列。</p><pre>var cityDictionary = [String: [City]]()</pre><pre>var citySectionTitles = [String]()</pre><pre>override func viewDidLoad() {<br>        super.viewDidLoad()<br>        <br>        for city in cities {<br>            let cityKey = String(city.cityString.prefix(1))<br>            if var cityValues = cityDictionary[cityKey] {<br>                cityValues.append(city)<br>                cityDictionary[cityKey] = cityValues<br>            } else {<br>              cityDictionary[cityKey] = [city]<br>            }<br>        }<br>        <br>        citySectionTitles = [String](cityDictionary.keys)<br>        citySectionTitles = citySectionTitles.sorted(by: &lt; )</pre><p>世界城市清單，包含section header與section側邊索引</p><pre>extension CityViewController: UITableViewDataSource {<br>    func numberOfSections(in tableView: UITableView) -&gt; Int {<br>        if searching {<br>            return 1<br>        } else {<br>            return citySectionTitles.count<br>        }<br>    }<br>    <br>    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -&gt; Int {<br>        <br>        if searching {<br>            return searchedCities.count<br>            <br>        } else {<br>            let cityKey =  citySectionTitles[section]<br>            if let cityValues = cityDictionary[cityKey] {<br>                return cityValues.count<br>            }<br>            return 0<br>        }<br>    }<br>    <br>    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -&gt; UITableViewCell {<br>        let cell = tableView.dequeueReusableCell(withIdentifier: &quot;\(CityTableViewCell.self)&quot;, for: indexPath) as! CityTableViewCell<br>                <br>        var city: City?<br>        <br>        if searching {<br>            city = searchedCities[indexPath.row]<br>        } else {<br>            let cityKey = citySectionTitles[indexPath.section]<br>            if let cityValue = cityDictionary[cityKey] {<br>                city = cityValue[indexPath.row]<br>            }<br>        }<br>        cell.cityLabel.text = city?.cityName<br>        return cell<br>    }<br>    <br>    func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -&gt; String? {<br>        return searching ? nil : citySectionTitles[section]<br>    }<br>    <br>    func sectionIndexTitles(for tableView: UITableView) -&gt; [String]? {<br>        return searching ? nil : citySectionTitles<br>    }<br><br>}</pre><p><a href="https://medium.com/swlh/indexing-your-uitableviews-aad93948776c">Indexing your UITableViews</a></p><h3>使用者自選的世界時鐘清單</h3><p>設定資料的顯示。由於編輯模式時會縮窄畫面空間，當編輯時時間需要隱藏。</p><pre>extension WorldClockViewController: UITableViewDataSource {<br>    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -&gt; Int {<br>        cities.count<br>    }<br>    <br>    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -&gt; UITableViewCell {<br>        let cell = tableView.dequeueReusableCell(withIdentifier: &quot;\(WorldClockTableViewCell.self)&quot;, for: indexPath) as! WorldClockTableViewCell<br>        <br>        let city = cities[indexPath.row]<br>        cell.cityLabel.text = city.cityName<br>        cell.relativeDateLabel.text = city.relativeDate<br>        cell.relativeHoursLabel.text = city.relativeHours<br>        if tableView.isEditing {<br>            cell.timeLabel.isHidden = true<br>        } else {<br>            cell.timeLabel.text = city.localTime<br>            cell.timeLabel.isHidden = false<br>        }<br>        return cell<br>    }     </pre><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/%E7%95%B6-table-view-%E6%88%96-collection-view-%E9%80%B2%E5%85%A5%E7%B7%A8%E8%BC%AF%E6%A8%A1%E5%BC%8F%E6%99%82%E9%A1%AF%E7%A4%BA%E4%B8%8D%E5%90%8C%E6%A8%A3%E5%BC%8F%E7%9A%84-cell-92d66bb461a2">當 table view 或 collection view 進入編輯模式時顯示不同樣式的 cell</a></p><p>設定清單可編輯與移動的功能與資料處理</p><pre>//Editable<br>    func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -&gt; Bool {<br>        true<br>    }<br>    <br>    func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {<br>        <br>        <br>        switch editingStyle {<br>        case .delete:<br>            cities.remove(at: indexPath.row)<br>            tableView.deleteRows(at: [indexPath], with: .fade)<br>        case .insert: return<br>        case .none:<br>            tableView.allowsSelectionDuringEditing = true<br>        default: return<br>        }          <br>    }<br>    <br>    func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -&gt; UITableViewCell.EditingStyle {<br>        <br>        UITableViewCell.EditingStyle.delete<br>    }</pre><pre>//Movable<br>    func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -&gt; Bool {<br>        true<br>    }<br>    <br>    func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {<br>        let city = cities[sourceIndexPath.row]<br>        cities.remove(at: sourceIndexPath.row)<br>        cities.insert(city, at: destinationIndexPath.row)<br>    }    <br>   <br>}</pre><h4>使用者參數儲存</h4><p>將使用者新增的程式儲存在UserDefaults。在原struct City 定義讀取與儲存參數。</p><pre>struct City: Codable {</pre><pre>    static func loadCities() -&gt; [City]? {<br>        let userDefault = UserDefaults.standard<br>        guard let data = userDefault.data(forKey: &quot;cities&quot;) else { return nil }<br>        let decoder = JSONDecoder()<br>        return try? decoder.decode([City].self, from: data)<br>    }<br>    <br>    static func saveCities(_ cities: [City]) {<br>        let encoder = JSONEncoder()<br>        guard let data = try? encoder.encode(cities) else { return }<br>        UserDefaults.standard.set(data, forKey: &quot;cities&quot;)<br>    }</pre><p>viewDidLoad後讀取資料</p><pre>override func viewDidLoad() {<br>        super.viewDidLoad()<br>        <br>        if let cities = City.loadCities() {<br>            self .cities = cities<br>        }</pre><p>透過property observer 定義當資料有變動便儲存</p><pre>var cities = [City]() {<br>        didSet {          <br>            City.saveCities(cities)<br>        }<br>    }</pre><h3>成果展示</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b7IhQDZMwNI6_-W5-kW7Hg.png" /></figure><p><a href="https://github.com/kylekylei/iOSClock/releases/tag/1.0">Release 1.0 · kylekylei/iOSClock</a></p><h4>參考資料</h4><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/65-%E6%A8%A1%E4%BB%BF%E8%A3%BD%E4%BD%9C-ios-%E5%85%A7%E5%BB%BA%E7%9A%84-clock-app-29385a04bea">#65 模仿製作 iOS 內建的 Clock App</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e2b6f70cc2ca" width="1" height="1" alt=""><hr><p><a href="https://medium.com/peter-pan-swift-ios-class/27-%E6%A8%A1%E4%BB%BF-ios-clock-app-1-world-clock-e2b6f70cc2ca">#27 模仿 iOS Clock App - 1 ：World Clock</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[#26 使用 async & await 串接 TMDB API]]></title>
            <link>https://medium.com/peter-pan-swift-ios-class/26-%E4%BD%BF%E7%94%A8-async-await-%E4%B8%B2%E6%8E%A5-tmdb-api-99421776272f?source=rss-77011e3e0806------2</link>
            <guid isPermaLink="false">https://medium.com/p/99421776272f</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[uicollectionview]]></category>
            <category><![CDATA[tmdb-api]]></category>
            <category><![CDATA[uikit]]></category>
            <dc:creator><![CDATA[Kyle X Swift]]></dc:creator>
            <pubDate>Tue, 11 Jan 2022 14:15:56 GMT</pubDate>
            <atom:updated>2022-01-11T14:28:12.553Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*wATgwbDbb-a6Rof0jEgJzg.gif" /></figure><h4>練習要點</h4><ul><li>使用 async &amp; await抓取多筆API資料 / 圖片</li><li>將所有資料controller 定義在同一個檔案</li><li>以UICollectionView顯示電影資料的水平瀏覽</li><li>以UITableView或UITableViewController不同應用顯示電影資料的垂直瀏覽</li><li>將電影資料傳遞到下一頁細節頁面</li><li>針對不同畫面的圖片尺寸需求，抓取對應尺寸的圖片</li><li>URLCache增加cache大小的應用</li><li>搜尋電影關鍵字並回傳搜尋結果(此API功能不太穩定，無法完整實現功能)</li></ul><h3>TMDB 資料型別</h3><p>電影資料主要顯示在results的arry資料裡。有些API裡的property檔名稱很不Swift，所以利用CodingKey來改寫。</p><pre>struct MovieItem: Codable {<br>    <br>    let id: Int<br>    let title: String<br>    let description: String<br>    let backdropImage: String<br>    let posterImage: String<br>    let releaseDate: String<br>    <br>    <br>    enum CodingKeys: String, CodingKey {<br>        case backdropImage = &quot;backdrop_path&quot;<br>        case id<br>        case title<br>        case description = &quot;overview&quot;<br>        case posterImage = &quot;poster_path&quot;<br>        case releaseDate = &quot;release_date&quot;<br>    }<br>}</pre><pre>struct MovieResponse: Codable {<br>    let page: Int<br>    let results: [MovieItem]<br>}</pre><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-enum-codingkeys-%E5%AE%A2%E8%A3%BD-json-%E5%B0%8D%E6%87%89%E7%9A%84-property-1b27f29c0c32">利用 CodingKey 客製 JSON 對應的 property</a></p><h3>MovieService 串接網路的程式統一定義在一個檔案</h3><h4>透過 static 定義的 shared 常數建立單例 singleton 做一個全域變數</h4><ol><li>將所有抓取資料的程式統一寫在 MovieService的class裡</li><li>使用private init()強迫只用使用shared引用單一個物件</li></ol><pre>class MovieService {<br> <br>    static let shared = MovieService()<br>    private init() {}</pre><h4>利用 URLQueryItem 設定 queryItems</h4><p>由於後續會串接TMDB所提供不同抓取資料的內容，透過URLQueryItem容易管理。</p><pre>let apikey = &quot;xxxxxxxxx&quot;<br>let baseURL = URL(string: &quot;<a href="https://api.themoviedb.org/3/">https://api.themoviedb.org/3/</a>&quot;)!</pre><p>抓取年度最佳電影資料的程式</p><pre>    <br>func fetchBestMovie(in year: Int) async throws -&gt; MovieResponse {<br>        var urlComponent = URLComponents(string: &quot;\(baseURL)discover/movie&quot;)!<br>        urlComponent.queryItems = [<br>            URLQueryItem(name: &quot;with_genres&quot;, value: &quot;18&quot;),<br>            URLQueryItem(name: &quot;api_key&quot;, value: apikey),<br>            URLQueryItem(name: &quot;primary_release_year&quot;, value: &quot;\(year)&quot;)<br>        ]<br>        return try await movieResonse(urlComponent: urlComponent)<br>    }</pre><p>抓取最受歡迎電影資料的程式</p><pre>func fetchPopularMovie() async throws -&gt; MovieResponse {<br>        var urlComponent = URLComponents(string: &quot;\(baseURL)discover/movie&quot;)!<br>        urlComponent.queryItems = [<br>            URLQueryItem(name: &quot;sort_by&quot;, value: &quot;popularity.desc&quot;),<br>            URLQueryItem(name: &quot;api_key&quot;, value: apikey),<br>        ]<br>        return try await movieResonse(urlComponent: urlComponent)<br>    }</pre><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%BD%BF%E7%94%A8-baseurl-urlcomponents-urlqueryitem-%E7%94%A2%E7%94%9F-url-1e4539a33a89">使用 baseURL，URLComponents &amp; URLQueryItem 產生 URL</a></p><h4>串接 API 的 function 加上 async &amp; throws，成功時回傳抓到的資料，失敗時丟出錯誤，使用 try await 呼叫 URLSession.shared.data</h4><p>獨立寫成一個function，可以給不同抓取的程式呼叫。</p><pre>func movieResonse(urlComponent: URLComponents) async throws -&gt; MovieResponse {<br>        let url = urlComponent.url!<br>        <br>        let (data, response) = try await URLSession.shared.data(from: url)<br>        <br>        guard let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode == 200 else {<br>            throw MovieServiceError.movieListNotFound<br>        }<br>        <br>        print(httpResponse.statusCode)<br>        let decoder = JSONDecoder()<br>        let movieResponse = try decoder.decode(MovieResponse.self, from: data)<br>        return movieResponse<br>    }</pre><p>抓取圖片的程式</p><pre>func fetchImage(from urlStr: String, in size: ImageSize) async throws -&gt; UIImage {<br>        let baseUrl = URL(string: &quot;<a href="https://image.tmdb.org/t/p//(size)">https://image.tmdb.org/t/p/\(size)</a>&quot;)!<br>        let imageUrl = baseUrl.appendingPathComponent(&quot;\(urlStr)&quot;)<br>        <br>        let (data, reponse) = try await URLSession.shared.data(from: imageUrl)<br>        guard let httpResponse = reponse as? HTTPURLResponse, httpResponse.statusCode == 200, let image = UIImage(data: data) else {<br>            throw MovieServiceError.imageDataMissing<br>        }<br>    <br>        return image<br>        <br>    }</pre><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/%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-%E4%BD%BF%E7%94%A8-async-await-46c819579c83">模仿 Apple 官方範例串接 JSON API，使用 async &amp; await</a></p><h3>FeatureViewController</h3><h4>利用Task呼叫抓取資料的程式，並使用do-catch執行程式或拋出錯誤訊息</h4><p>透過asyn/await的結構，不用特別處理執行緒，程式碼結構相當簡潔。</p><pre>var bestMovieItems = [MovieItem]()</pre><pre>override func viewDidLoad() {<br>        super.viewDidLoad()</pre><pre>Task {<br>            do {<br>                let movieResponse = try await MovieService.shared.fetchBestMovie(in: 2021)<br>                bestMovieItems = movieResponse.results<br>                movieCollectionView.reloadData()<br>            } catch {<br>                displayError(error, title: &quot;Fail to fetch the Best Movie data&quot;)<br>            }<br>        }</pre><h4>將資料顯示在collectionView畫面上</h4><p>建立collectionView的IBOutlet</p><pre><a href="http://twitter.com/IBOutlet">@IBOutlet</a> weak var movieCollectionView: UICollectionView!</pre><p>用extension在原ViewController擴展UICollectionViewDataSource</p><pre>extension FeatureViewController: UICollectionViewDataSource {<br>    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -&gt; Int {<br>        bestMovieItems.count<br>    }<br>    <br>    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -&gt; UICollectionViewCell {<br>        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: &quot;\(BestCollectionViewCell.self)&quot;, for: indexPath) as! BestCollectionViewCell<br>        <br>        let item = bestMovieItems[indexPath.item]<br>        <br>        <br>        cell.titleLabel.text = item.title<br>        cell.dateLabel.text = item.releaseDate<br>        cell.movieImage.image = UIImage(systemName: &quot;photo&quot;)<br>        </pre><p>一樣透過Task內來執行async/await抓取圖片的程式</p><pre>Task {<br>            do {<br>                cell.movieImage.image = try await MovieService.shared.fetchImage(from: item.backdropImage, in: .w500)<br>            } catch {<br>                displayError(error, title: &quot;Fail to fetch image&quot;)<br>            }<br>        }</pre><pre>return cell<br>    }<br>}</pre><h4>IBSegueAction傳遞資料到下一個頁面</h4><pre>@IBSegueAction func showDetailfromItem(_ coder: NSCoder) -&gt; DetailViewController? {<br>        <br>        guard let item = movieCollectionView.indexPathsForSelectedItems?.first?.row else {return nil}<br>        return DetailViewController(coder: coder, movieItem: bestMovieItems[item])<br>    }</pre><h3>DetailViewController</h3><p>此畫面接收上一個畫面的資料並顯示在畫面上，直接貼上整個程式。</p><pre>import UIKit</pre><pre><a href="http://twitter.com/MainActor">@MainActor</a><br>class DetailViewController: UIViewController {<br>    <br>    let movieItem: MovieItem<br>    init?(coder: NSCoder, movieItem: MovieItem) {<br>        self.movieItem = movieItem<br>        super.init(coder: coder)<br>    }</pre><pre>required init?(coder: NSCoder) {<br>        fatalError(&quot;init(coder:) has not been implemented&quot;)<br>    }<br>    <br>    var backdropItems = [BackdropItem]()</pre><pre><a href="http://twitter.com/IBOutlet">    @IBOutlet</a> weak var titleLabel: UILabel!<br>    <a href="http://twitter.com/IBOutlet">@IBOutlet</a> weak var dateLabel: UILabel!<br>    <a href="http://twitter.com/IBOutlet">@IBOutlet</a> weak var descriptionLabel: UILabel!<br>    <a href="http://twitter.com/IBOutlet">@IBOutlet</a> weak var posterImage: UIImageView! {<br>        didSet {<br>            posterImage.layer.cornerRadius = 32<br>            posterImage.layer.maskedCorners = [.layerMinXMaxYCorner, .layerMaxXMaxYCorner]<br>            posterImage.clipsToBounds = true<br>        }<br>    }<br>    <br>    <a href="http://twitter.com/IBOutlet">@IBOutlet</a> weak var backDropCollectionView: UICollectionView!<br>    <br>    <br>    <br>    override func viewDidLoad() {<br>        super.viewDidLoad()</pre><pre>        // Detail<br>        Task {<br>            do {<br>                updateUI()<br>                self.posterImage.image = try await MovieService.shared.fetchImage(from: movieItem.posterImage, in: .original)<br>            } catch {<br>                displayError(error, title: &quot;Failed to fetch items&quot;)<br>            }<br>        }<br>        <br>        // Backdrop<br>        Task {<br>            do {<br>                let backgropResponse = try await MovieService.shared.fetchMovieBackdrops(movieID: &quot;\(movieItem.id)&quot;)<br>                backdropItems = backgropResponse.backdrops<br>                backDropCollectionView.reloadData()<br>            }catch {<br>                displayError(error, title: &quot;Failed to fetch backgrop&quot;)<br>            }<br>        }<br>   <br>    }<br>    <br>    func updateUI() {<br>        titleLabel.text = movieItem.title<br>        dateLabel.text = movieItem.releaseDate<br>        descriptionLabel.text = movieItem.description<br> <br>    }</pre><pre>}</pre><pre>extension DetailViewController: UICollectionViewDataSource {<br>    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -&gt; Int {<br>        backdropItems.count<br>    }<br>    <br>    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -&gt; UICollectionViewCell {<br>        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: &quot;\(BackDropCollectionViewCell.self)&quot;, for: indexPath) as! BackDropCollectionViewCell<br>        <br>        let item = backdropItems[indexPath.item]<br>        Task {<br>            do {<br>                cell.backgropImage.image = try await MovieService.shared.fetchImage(from: item.path, in: .w300)<br>            }catch {<br>                displayError(error, title: &quot;Fail to fetch image&quot;)<br>            }<br>            <br>        }        <br>        return cell<br>    }<br>  <br>}</pre><pre>extension DetailViewController {<br>    func configureCellSize() {<br>        let itemSpace: CGFloat = 2</pre><pre>let flowLayout = backDropCollectionView.collectionViewLayout as? UICollectionViewFlowLayout<br>        let height = backDropCollectionView.bounds.height<br>        flowLayout?.itemSize = CGSize(width: height, height: height)<br>        flowLayout?.estimatedItemSize = .zero<br>        flowLayout?.minimumLineSpacing = itemSpace<br>        flowLayout?.minimumInteritemSpacing = itemSpace<br>    }<br>    <br>    func displayError(_ error: Error, title: String) {<br>        guard let _ = viewIfLoaded?.window else {return}<br>        let alert = UIAlertController(title: title, message: error.localizedDescription, preferredStyle: .alert)<br>        alert.addAction(UIAlertAction(title: &quot;Dismiss&quot;, style: .default, handler: nil))<br>        self.present(alert, animated: true, completion: nil)<br>    }<br>}</pre><h4>增加cache大小</h4><p>主要是發現抓取大圖時，會一直重複抓圖並閃跳，於是研究一下解法，但也同時定義顯示小圖就抓取小圖，不要浪費資源。</p><pre>import UIKit</pre><pre><a href="http://twitter.com/main">@main</a><br>class AppDelegate: UIResponder, UIApplicationDelegate {</pre><pre>func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -&gt; Bool {<br>        <br>        let temporaryDirectory = NSTemporaryDirectory()<br>                <br>        let urlCache = URLCache(memoryCapacity: 25_000_000, diskCapacity: 50_000_000, diskPath: temporaryDirectory)<br>        URLCache.shared = urlCache<br>        <br>        return true<br>    }</pre><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/swift-ios-app-%E4%B8%8B%E8%BC%89%E5%9C%96%E7%89%87%E7%9A%84%E5%B9%BE%E7%A8%AE%E6%96%B9%E6%B3%95-c8f3592db66f">Swift iOS App 下載圖片的幾種方法</a></p><h4>成果展示</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tdm66KWcoUt-0lSfN1-iGQ.png" /></figure><p><a href="https://github.com/kylekylei/TMDB">GitHub - kylekylei/TMDB</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=99421776272f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/peter-pan-swift-ios-class/26-%E4%BD%BF%E7%94%A8-async-await-%E4%B8%B2%E6%8E%A5-tmdb-api-99421776272f">#26 使用 async &amp; await 串接 TMDB 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[#25 串接第三方 API-以SpaceX API與YouTube API實現解析 JSON 資料、與WKWebView資料傳遞]]></title>
            <link>https://medium.com/peter-pan-swift-ios-class/25-%E4%B8%B2%E6%8E%A5%E7%AC%AC%E4%B8%89%E6%96%B9-api-%E4%BB%A5spacex-api%E8%88%87youtube-api%E5%AF%A6%E7%8F%BE%E8%A7%A3%E6%9E%90-json-%E8%B3%87%E6%96%99-%E8%88%87wkwebview%E8%B3%87%E6%96%99%E5%82%B3%E9%81%9E-aff0131a6d34?source=rss-77011e3e0806------2</link>
            <guid isPermaLink="false">https://medium.com/p/aff0131a6d34</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[uikit]]></category>
            <dc:creator><![CDATA[Kyle X Swift]]></dc:creator>
            <pubDate>Sun, 26 Dec 2021 15:00:06 GMT</pubDate>
            <atom:updated>2021-12-27T06:28:36.534Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6eRv-Zuc-cG5-m9NTHUVpA.jpeg" /></figure><h4>實現功能</h4><ul><li>串接SpaceX API，解析回傳的 JSON 資料</li><li>自訂型別並顯示資訊於UI上</li><li>串接YouTube API以內嵌SpaceX所提供的YouTube影片</li><li>透過WKWebView傳遞SpaceX所提供的Reddit網頁</li><li>讀取資料時顯示UIActivityIndicatorView (目前使用固定秒數，還沒實現等資料讀取完才結束讀取)</li></ul><h4>SpaceX API</h4><p>此API將會顯示SpaceX最新的火箭發射資訊，有很細節的資料與介紹。比較感興趣的是每次發射行動都會有一個logo、YouTube直撥網址與Reddit討論網頁。原本範例內容有提供flickr的圖片，計畫顯示成collectionView但不是每次都有。</p><p><a href="https://github.com/r-spacex/SpaceX-API">GitHub - r-spacex/SpaceX-API: :rocket: Open Source REST API for SpaceX launch, rocket, core, capsule, starlink, launchpad, and landing pad data.</a></p><p>此API是從以下文章分享找到了，也有列出其他有趣的應用。有興趣的朋友可以參考看看。</p><p><a href="https://learn.vonage.com/blog/2021/03/15/the-ultimate-list-of-fun-apis-for-your-next-coding-project/">The Ultimate List of Fun APIs For Your Next Coding Project &quot; Developer Content from Vonage ♥</a></p><h4>自訂資料型別</h4><p>此資料結構比較多的連結包含在links裡，會宣告比較多層的物件。</p><pre>struct SearchResponse: Codable {<br>    let links: Link    <br>    let details: String<br>    let name: String<br>    let date_unix: Date    <br>       <br>    struct Link: Codable {<br>        let patch: Patch<br>        let reddit: Reddit<br>        let flickr: Flickr?<br>        let presskit: URL?<br>        let webcast: URL<br>        let youtube_id: String<br>        let article: URL?<br>                <br>        struct Patch: Codable {<br>            let small: URL<br>            let large: URL<br>        }<br>        struct Reddit: Codable {<br>            let launch: String<br>        }<br>        struct Flickr: Codable {<br>            let small: [URL]<br>            let original: [URL]<br>        }<br>    }<br>}</pre><h4>抓取網路資料</h4><pre>func fetchItems() {<br>        let urlStr = &quot;https://api.spacexdata.com/v4/launches/latest&quot;<br>        if let url = URL(string: urlStr) {<br>            URLSession.shared.dataTask(with: url) { data, response, error in<br>                if let data = data {<br>                    let decoder = JSONDecoder()<br>                    decoder.dateDecodingStrategy = .secondsSince1970<br>                    do {<br>                        self.searchResponse = try decoder.decode(SearchResponse.self, from: data)<br><br>                        DispatchQueue.main.async {<br>                            //待會處理UI相關資訊<br>        <br>                        }<br><br>                    }catch {<br>                        print(error)<br>                    }<br>                }else {<br>                    print(&quot;error&quot;)<br>                }<br>            }.resume()<br>        }<br>        <br>    }</pre><h4>Main thread的內容</h4><blockquote>實例化字串資料</blockquote><pre>self.nameLabel.text = self.searchResponse?.name<br>self.detail = self.searchResponse?.details<br>self.redditStr = self.searchResponse?.links.reddit.launch<br></pre><blockquote>抓取圖片的function</blockquote><pre>self.fetchImage(url: self.searchResponse!.links.patch.small)                            <br></pre><p>此寫法不是很完整與安全，之後專案會再優化</p><pre>func fetchImage(url: URL){<br>        URLSession.shared.dataTask(with: url ) { data, response, error in<br>            if let data = data {<br>                DispatchQueue.main.async {<br>                    self.petalImage.image = UIImage(data: data)<br>                }<br>            }<br>        }.resume()<br>    }</pre><blockquote>解析發射日期的Date資料</blockquote><pre>if let releaseDate = self.searchResponse?.date_unix {<br>  let dateFormatter = DateFormatter()<br>  dateFormatter.dateFormat = &quot;yyyy-MM-dd HH:mm&quot;<br>  let releaseDateStr = dateFormatter.string(from: releaseDate)<br>   elf.releaseDateLabel.text = releaseDateStr<br>}                           <br></pre><h4>安裝youtube api</h4><ul><li>需透過CocoaPods安裝youtube api</li><li>由於此專案只要內嵌播放器，沒使用到api key</li></ul><p><a href="https://developers.google.com/youtube/v3/guides/ios_youtube_helper?hl=zh-TW">Embed YouTube Videos in iOS Applications with the YouTube Helper Library | YouTube IFrame Player API | Google Developers</a></p><blockquote>import與宣告YTPlayerView()</blockquote><pre>import youtube_ios_player_helper<br>let playerView = YTPlayerView()</pre><p>將抓取的youtube_id賦值給playView</p><pre>if let videoID = self.searchResponse?.links.youtube_id {<br>   self.playerView.load(withVideoId: videoID)   <br>    }<br>}</pre><p>開啟頁面３秒後自動播放(之後實現讀取就播放)</p><pre>Timer.scheduledTimer(withTimeInterval: 3, repeats: false) { _ in<br>    self.playerView.playVideo()</pre><h3>WKWebView資料傳遞</h3><p>在顯示網頁viewController內</p><pre>import WebKit</pre><p>宣告接收網址的變數</p><pre>var urlStr: String<br>    init?(coder: NSCoder, urlStr: String){<br>        self.urlStr = urlStr<br>        super.init(coder: coder)<br>    }<br>    <br>    required init?(coder: NSCoder) {<br>        fatalError(&quot;init(coder:) has not been implemented&quot;)<br>    }<br>    <br>  </pre><p>宣告介面更新的函式</p><pre>func updateUI() {<br>        if let url = URL(string: urlStr) {<br>            let request = URLRequest(url: url)<br>            webview.load(request)<br>        }<br>    }</pre><h4>成果展現</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SHj-IzgZLWCaRcHn6Xklrg.gif" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TQGhjtSFN0_xcy_xFFIa2A.png" /></figure><p><a href="https://github.com/kylekylei/SpaceXLaunch">GitHub - kylekylei/SpaceXLaunch</a></p><h4>參考資料</h4><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/19-%E4%B8%B2%E6%8E%A5%E7%AC%AC%E4%B8%89%E6%96%B9-api-%E8%A7%A3%E6%9E%90-json-%E8%B3%87%E6%96%99%E9%A1%AF%E7%A4%BA-f1556e84daec">#19 串接第三方 API，解析 JSON 資料，轉換成自訂型別顯示</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aff0131a6d34" width="1" height="1" alt=""><hr><p><a href="https://medium.com/peter-pan-swift-ios-class/25-%E4%B8%B2%E6%8E%A5%E7%AC%AC%E4%B8%89%E6%96%B9-api-%E4%BB%A5spacex-api%E8%88%87youtube-api%E5%AF%A6%E7%8F%BE%E8%A7%A3%E6%9E%90-json-%E8%B3%87%E6%96%99-%E8%88%87wkwebview%E8%B3%87%E6%96%99%E5%82%B3%E9%81%9E-aff0131a6d34">#25 串接第三方 API-以SpaceX API與YouTube API實現解析 JSON 資料、與WKWebView資料傳遞</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>