<?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 Yong Shun on Medium]]></title>
        <description><![CDATA[Stories by Yong Shun on Medium]]></description>
        <link>https://medium.com/@a49980060?source=rss-f5db7d13265a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*v6V9e7flaDpa8qcxRKMBJA.jpeg</url>
            <title>Stories by Yong Shun on Medium</title>
            <link>https://medium.com/@a49980060?source=rss-f5db7d13265a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 00:27:13 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@a49980060/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[#19-實作IOS APP登入Facebook第三方登入平台]]></title>
            <link>https://medium.com/peter-pan-swift-ios-class/19-%E5%AF%A6%E4%BD%9Cios-app%E7%99%BB%E5%85%A5facebook%E7%AC%AC%E4%B8%89%E6%96%B9%E7%99%BB%E5%85%A5%E5%B9%B3%E5%8F%B0-b4968f3fbd9a?source=rss-f5db7d13265a------2</link>
            <guid isPermaLink="false">https://medium.com/p/b4968f3fbd9a</guid>
            <dc:creator><![CDATA[Yong Shun]]></dc:creator>
            <pubDate>Tue, 14 Jun 2022 10:57:00 GMT</pubDate>
            <atom:updated>2022-06-15T07:49:30.127Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7rFo5xFLMoPLqIZj1BlIxA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C_yUq6lJ2sAxHiFzpqJJBQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QqScaEtm9LNzlMJnpWtrQQ.png" /></figure><p>這篇要介紹登入facebook第三方登入平台，現在大部分的人都有facebook帳號，可以省去註冊帳號的麻煩，這當然要來好好研究如何使用囉😁</p><h4>功能介紹：</h4><ol><li>註冊facebook with developers</li><li>SPM 安裝 Facebook iOS SDK</li><li>啟動App時完成相關Facebook設定</li><li>Facebook Login Button</li><li>讓Firebase跟Facebook串連</li></ol><h4>一、連到Facebook開發網站建立應用程式</h4><p>首先連到Facebook開發網站</p><p><a href="https://developers.facebook.com/">Social technologies | Meta for Developers</a></p><p>● 點選右上角的『我的應用程式』</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jFJfeXbspeecE_Qf2ALrTw.png" /></figure><p>● 再來一樣點選右上角的『建立應用程式』</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aEo3fm6eSruoaMo4o7JbvA.png" /></figure><p>● 要實現登入功能，這邊點選『消費者』</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N5dqXrqbU3G_1xqRiDIEBw.png" /></figure><p>● 輸入『App名稱』及『信箱』</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NSvHYcMe2-1Z_dy3I-ggwQ.png" /></figure><p>● 點選『Facebook登入的設定』</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/668/1*AjKGLsOEphu0XS4qtpwxdQ.png" /></figure><p>● 點選『IOS』</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*THPrgRMJ4bKPTDrVCMjv3Q.png" /></figure><p>● 直接點選『繼續』</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OWAg9JLRRY8IilCuA5J44g.png" /></figure><p>● 輸入project的『bundle id』點選save後繼續</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MNDzY5Yvxtflad1huVFlwg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kwdh-EEP6SbcNcED6gg5mQ.png" /></figure><p>● 啟用單一登入為『是』</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z9Iz78ImwdunysYlWFTYxg.png" /></figure><p>● 設定『info.plist』</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bSyp12wYc_pVx5kVp7SbXg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y_hiaIdRL3QoCQbGj5rqpg.png" /></figure><p>FacebookAppID、FacebookDisplayName在開發網站左上角，URL Types的URL Schemes需要編號ID前面加上fb</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v61w_-QKOG1v3zbLkgSPWw.png" /></figure><p>FacebookClientToken在進階-&gt;用戶端權杖可以找到</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U2rzU7nEAmdtMRS2TwTJ3A.png" /></figure><p>● 新增『Keychain sharing』功能</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*apTyq7DY3c-BgdgWq831Iw.png" /></figure><h4>二、SPM安裝Facebook IOS SDK</h4><p>在Xcode內建SPM搜尋Facebook IOS SDK網址</p><pre><a href="https://github.com/facebook/facebook-ios-sdk">https://github.com/facebook/facebook-ios-sdk</a></pre><p>● 版本設定13.0.0點選Add Package，勾選FacebookLogin</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7LTBmQ0TUKq8bFBUPzBrtA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g4EH2NZNCzuNZ_8Yf0PXFg.png" /></figure><p>完成後Package Dependencies下面會出現Facebook表示安裝成功</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/486/1*66mHq7hdXhOv3No9HnP3Cg.png" /></figure><h4>三、啟動App時初始化Facebook的相關設定</h4><p>根據Facebook開發網站說明，需要在 AppDelegate加入以下程式碼，讓App啟動時初始化SDK，並在您執行「登入」或「分享」動作時，讓 SDK 處理原生 Facebook 應用程式的登入和分享。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u8dH7pnj-K04K43x2mdBCQ.png" /></figure><p>這邊我們可以直接複製網站給的code，第一次在import FacebookCore的時候，一直沒有辦法呼叫ApplicationDelegate使用，一直檢查到底哪裡出了問題😨，結果最後只要執行模擬器就解決了😑，我想應該是Xcode的BUG吧！程式有時候就是這麼有趣，code沒有錯、錯的竟然是編譯軟體😂。</p><pre>import UIKit<br>import Firebase<br><strong>import FacebookCore</strong></pre><pre><strong>@UIApplicationMain</strong><br>class AppDelegate: UIResponder, UIApplicationDelegate {<br>    <br>    <br>    <br>    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -&gt; Bool {<br>        // Override point for customization after application launch.<br>        <strong>ApplicationDelegate.shared.application(<br>            application,<br>            didFinishLaunchingWithOptions: launchOptions<br>        )</strong><br>        FirebaseApp.configure()<br>        <br>        return true<br>    }<br>    <br>    <strong>func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -&gt; Bool {<br>        ApplicationDelegate.shared.application(app, open: url, options: options)<br>    }</strong></pre><p>接著在SceneDelegate加入以下代碼，分享跟登入操作才可以正常運作</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ihFW1FgzWpSkbMt7FsuT2g.png" /></figure><p>一樣直接複製就可以😏</p><pre>import UIKit<br><strong>import FacebookCore</strong></pre><pre>class SceneDelegate: UIResponder, UIWindowSceneDelegate {<br>    <br>    var window: UIWindow?<br>    <br>    <br>    func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {<br>        guard let _ = (scene as? UIWindowScene) else { return }<br>    }<br>    <br>    <strong>func scene(_ scene: UIScene, openURLContexts URLContexts: Set&lt;UIOpenURLContext&gt;) {<br>        guard let url = URLContexts.first?.url else { return }<br>        <br>        ApplicationDelegate.shared.application(<br>            UIApplication.shared,<br>            open: url,<br>            sourceApplication: nil,<br>            annotation: [UIApplication.OpenURLOptionsKey.annotation]<br>        )<br>    }</strong></pre><h4>四、Facebook登入Button</h4><p>生成LoginManager的物件並呼叫function logIn，permissions權限輸入[.publicProfile, .email]，如果需要更多權限資料，則需要FB審核通過才可以，當closure裡參數loginResult是success表示登入成功。</p><pre><strong>@IBAction</strong> <strong>func</strong> fbLoginButtonClicked(_ sender: UIButton) {<br>        let manager = LoginManager()<br>        manager.logIn(permissions: [.publicProfile, .email], viewController: nil) { loginResult in<br>            switch loginResult {<br>            case .success(granted: let granted, declined: let declined, token: let token) :<br>                print(&quot;success&quot;)<br>            case .cancelled :<br>                print(&quot;cancelled&quot;)<br>            case .failed(_) :<br>                print(&quot;error&quot;)<br>            }<br>        }<br>   }</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v476cc5DeNES92a4-qab2Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mcSlK4sJPfOR0SfrdERfVA.png" /></figure><p>測試沒有問題，FB登入成功！</p><p>再來就是呼叫Profile.loadCurrentProfile讀取使用者的基本資料，print看看</p><pre>if let _ = AccessToken.current {<br>            Profile.loadCurrentProfile { profile, error in<br>                guard let profile = profile else { return }<br>                print(&quot;\(profile.userID)\n\(profile.name)\n\(profile.email)\n\(profile.imageURL(forMode: .square, size: CGSize(width: 300, height: 300)))&quot;)<br>            }<br>        }</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TSCaCaCsoqZnQcXqeii8DA.png" /></figure><p>OK~看起來沒有問題了！</p><h4>五、Firebase串連FB帳號</h4><p>在18–1有利用Firebase的電子郵件/密碼實作註冊功能，有興趣可以參考我的文章</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/18-1-%E5%88%A9%E7%94%A8firebase%E8%A3%BD%E4%BD%9C-ios-app-%E7%9A%84%E7%99%BB%E5%85%A5%E8%A8%BB%E5%86%8A%E5%8A%9F%E8%83%BD-%E6%8A%93%E5%8F%96lorem-picsum-api%E5%9C%96%E7%89%87%E8%A8%AD%E5%AE%9A%E4%BD%BF%E7%94%A8%E8%80%85%E7%85%A7%E7%89%87-%E4%B8%A6%E8%87%AA%E8%A3%BD%E7%B0%A1%E5%96%AE%E7%9A%84%E8%AE%80%E5%8F%96%E5%8B%95%E7%95%AB-8160a7764104">#18–1-利用Firebase製作 iOS App 的登入註冊功能，抓取Lorem Picsum API圖片設定使用者照片，並自製簡單的讀取動畫</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fw81QDgpqC3aDsmU9rzxZg.png" /></figure><p>這邊我們需要新增FB的帳號登入，點選Add new prvider</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*75k_pbHaM770URQx5ke0bg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Rj59_F840Qk8p19sUgySRQ.png" /></figure><p>這邊需要輸入App ID跟App secret，在Facebook開發網站的基本資料可以找到</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c39Fkh47coZx4uGtWsg0wA.png" /></figure><p>好了之後再來就是code的部分，manager.login登入success後，生成AccessToken.current!.tokenString 產生 Firebase 登入需要的 credential，然後以 Auth.auth().signIn 登入，最後呼叫Profile.loadCurrentProfile取得使用者的照片，讓Firebase帳號的photoURL使用。（以下完整程式碼）</p><pre><a href="http://twitter.com/IBAction">@IBAction</a> func fbLoginButtonClicked(_ sender: UIButton) {<br>        let manager = LoginManager()<br>        manager.logIn(permissions: [.publicProfile, .email], viewController: nil) { loginResult in<br>            switch loginResult {<br>            case .success(granted: _, declined: _, token: let token) :<br>                <strong>let credential = FacebookAuthProvider.credential(withAccessToken: token!.tokenString)</strong><br>                <strong>Auth.auth().signIn(with: credential)</strong> { [weak self] result, error in<br>                    guard let self = self else { return }<br>                    guard error == nil else {<br>                        print(error?.localizedDescription ?? &quot;&quot;)<br>                        return<br>                    }<br>                    if let _ = AccessToken.current {<br>                        Profile.loadCurrentProfile { profile, error in<br>                            guard let profile = profile,<br>                                  let imageURL = profile.imageURL(forMode: .square, size: CGSize(width: 300, height: 300))<br>                            else { return }<br>                            let changeResquest = Auth.auth().currentUser?.createProfileChangeRequest()<br>                           <strong> changeResquest?.photoURL = imageURL</strong><br>                            changeResquest?.commitChanges(completion: { error in<br>                                guard error != nil else { return }<br>                            })<br>                        }<br>                    }<br>                    self.loginAnimationView.isHidden = false<br>                    self.loginAnimationLabel.alpha = 1<br>                    self.animationAction(true)<br>                    Timer.scheduledTimer(withTimeInterval: 7, repeats: false) { timer in<br>                        self.goToLoginSuccessView()<br>                        self.loginAnimationView.isHidden = true<br>                    }<br>                }<br>            case .cancelled :<br>                print(&quot;cancelled&quot;)<br>            case .failed(_) :<br>                print(&quot;error&quot;)<br>            }<br>        }<br>    }</pre><p>最後完成一樣來試試看😁</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/296/1*9pIgUW2wqgKOic7qrlHfrg.gif" /></figure><p>看起來沒有問題🎉～繼續努力💪</p><p>完整專案，以下連結 (Tags 1.2)</p><p><a href="https://github.com/YongShunTu/LoginDemo/tree/1.2">GitHub - YongShunTu/LoginDemo at 1.2</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b4968f3fbd9a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/peter-pan-swift-ios-class/19-%E5%AF%A6%E4%BD%9Cios-app%E7%99%BB%E5%85%A5facebook%E7%AC%AC%E4%B8%89%E6%96%B9%E7%99%BB%E5%85%A5%E5%B9%B3%E5%8F%B0-b4968f3fbd9a">#19-實作IOS APP登入Facebook第三方登入平台</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[#18–2-利用Firebase套件 FirebaseFirestoreSwift製作 iOS App 的聊天功能]]></title>
            <link>https://medium.com/peter-pan-swift-ios-class/18-2-%E5%88%A9%E7%94%A8firebase%E5%A5%97%E4%BB%B6-firebasefirestoreswift%E8%A3%BD%E4%BD%9C-ios-app-%E7%9A%84%E8%81%8A%E5%A4%A9%E5%8A%9F%E8%83%BD-8e6d819a5d04?source=rss-f5db7d13265a------2</link>
            <guid isPermaLink="false">https://medium.com/p/8e6d819a5d04</guid>
            <dc:creator><![CDATA[Yong Shun]]></dc:creator>
            <pubDate>Thu, 12 May 2022 16:45:33 GMT</pubDate>
            <atom:updated>2022-06-14T10:57:33.397Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RVKNy679ZbCF5rmK3vmxWQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*49T4FHB-Hr9mNRU2efaJuw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P_kkSrv4LBt2VScgn_Cveg.png" /></figure><p><strong>FirebaseFirestoreSwift是一個強大的套件功能，可以</strong>幫我們將下載的資料變成自訂型別，也可以讓我們上傳自訂型別的資料。就來看看要怎麼創一個聊天室來聊天吧！</p><p>設定Firebase 專案的 Cloud Firestore 設定，相關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/firebase-%E5%B0%88%E6%A1%88%E7%9A%84-cloud-firestore-%E8%A8%AD%E5%AE%9A-39334f74b348">Firebase 專案的 Cloud Firestore 設定</a></p><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/18-1-%E5%88%A9%E7%94%A8firebase%E8%A3%BD%E4%BD%9C-ios-app-%E7%9A%84%E7%99%BB%E5%85%A5%E8%A8%BB%E5%86%8A%E5%8A%9F%E8%83%BD-%E6%8A%93%E5%8F%96lorem-picsum-api%E5%9C%96%E7%89%87%E8%A8%AD%E5%AE%9A%E4%BD%BF%E7%94%A8%E8%80%85%E7%85%A7%E7%89%87-%E4%B8%A6%E8%87%AA%E8%A3%BD%E7%B0%A1%E5%96%AE%E7%9A%84%E8%AE%80%E5%8F%96%E5%8B%95%E7%95%AB-8160a7764104">#18–1-利用Firebase製作 iOS App 的登入註冊功能，抓取Lorem Picsum API圖片設定使用者照片，並自製簡單的讀取動畫</a></p><h4>功能介紹：</h4><ol><li>定義 Firestore 資料對應的自訂型別</li><li>新增聊天室Document，並且用order(by: “”)時間排序</li><li>在聊天室Document下新增collection聊天內容</li><li>addSnapshotListener偵測collection 下的 document 是否有更新，並且用order(by: “”)時間排序</li></ol><h4>一、定義自訂型別</h4><p>為了讓資料有識別的 id &amp; 遵從 protocol Identifiable，我們另外加入 @DocumentID var id: String?，到時候抓到資料時，id 的內容將為資料的 document id。</p><p>這邊我定義兩個自訂型別，一個是chatroom，func顯示時間String</p><pre>import Foundation<br>import FirebaseFirestoreSwift</pre><pre>struct Rooms: Codable, Identifiable {<br>    <a href="http://twitter.com/DocumentID">@DocumentID</a> var id: String?<br>    let name: String<br>    let time: Date<br>    <br>    func getTimeString() -&gt; String {<br>        let dateForMatter = DateFormatter()<br>        dateForMatter.dateFormat = &quot;yyyy/MM/dd&quot;<br>        let timeString = dateForMatter.string(from: time)<br>        return timeString<br>    }<br>}</pre><p>一個是messages，func顯示時間String</p><pre>import Foundation<br>import FirebaseFirestoreSwift<br>import UIKit</pre><pre>struct Messages: Codable, Identifiable {<br>    <a href="http://twitter.com/DocumentID">@DocumentID</a> var id: String?<br>    let email: String<br>    let displayName: String<br>    let displayPhoto: Data<br>    let messages: String<br>    let time: Date<br>    <br>    func getTimeStyle() -&gt; String {<br>        let dateFormatter = DateFormatter()<br>        dateFormatter.dateFormat = &quot;HH:mm&quot;<br>        let timeString = dateFormatter.string(from: time)<br>        let dateComponents = Calendar.current.dateComponents(in: TimeZone.current, from: time)<br>        let hour = dateComponents.hour ?? 0<br>        if hour &gt;= 12 {<br>            return &quot;下午&quot; + timeString<br>        }else{<br>            return &quot;上午&quot; + timeString<br>        }<br>    }<br>}</pre><h4>二、上傳聊天室Document、抓取collection底下全部的聊天室Document</h4><p>這邊我是指定文件id建立chatroom的Document，其實用自動產生的id也可以，我的聊天內容Document就是用自動產生的，算是多多練習、有益身體健康😂</p><p>拉好@IBAction宣告要傳入資料的常數</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2NJVaOZyAPhhTeCFIa5t-Q.png" /></figure><pre><a href="http://twitter.com/IBAction">@IBAction</a> func createRooms(_ sender: UIButton) {<br>        let date = Date()<br>        let alter = UIAlertController(title: &quot;輸入聊天室名稱&quot;, message: nil, preferredStyle: .alert)<br>        alter.addTextField { textfield in<br>            textfield.keyboardType = .default<br>            textfield.placeholder = &quot;請輸入名稱&quot;<br>            textfield.addReturnButton()<br>        }<br>        let okAction = UIAlertAction(title: &quot;新增&quot;, style: .default) { action in<br>            let rooms = Rooms(name: alter.textFields?[0].text ?? &quot;&quot;, time: date)<br>            <strong>FirebaseController.shard.creatRooms(alter.textFields?[0].text ?? &quot;&quot;, rooms, self)</strong><br>        }<br>        let cancleAction = UIAlertAction(title: &quot;取消&quot;, style: .default)<br>        alter.addAction(cancleAction)<br>        alter.addAction(okAction)<br>        present(alter, animated: true)<br>        <br>    }</pre><p>執行func creatRooms上傳Document資料後，在執行func fetchRooms抓取collection底下全部的Document資料</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UTH-uvr6he0wE4Hx_JEKNw.png" /></figure><pre>let db = Firestore.firestore()</pre><pre>func creatRooms(_ roomsName: String, _ rooms: Rooms, _ chatroomViewController: ChatroomViewController) {<br>        do {<br>            try db.collection(&quot;rooms&quot;).document(roomsName).setData(from: rooms) <br><strong>// 新增指定id的Document資料，傳入自訂型別rooms</strong><br>            fetchRooms(chatroomViewController) <br><strong>// 建立好Document後執行func fetchRooms()</strong><br>        }catch{<br>            print(error)<br>        }<br>    }<br>    <br>    func fetchRooms(_ chatroomViewController: ChatroomViewController) {<br>        db.collection(&quot;rooms&quot;).order(by: &quot;time&quot;).getDocuments { snapshot, error in <br><strong>//  利用order讓時間time排序小到大，並呼叫getDocuments</strong>,<strong>snapshot是[QueryDocumentSnapshot] 的 documents</strong><br>            guard let snapshot = snapshot else { return }<br>            let rooms = snapshot.documents.compactMap { snapshot in<br>                try? snapshot.data(as: Rooms.self) <br><strong>// 生成rooms呼叫compacMap轉成型別[Rooms]</strong><br>            }<br>            chatroomViewController.rooms = rooms<br>        }<br>    }</pre><p>chatroomViewController.rooms接收到資料rooms就可以更新tableView了，並實際來建立聊天室rooms看看畫面如何</p><pre>var rooms = [Rooms]() {<br>        didSet {<br>            roomsTableView.reloadData()<br>        }<br>    }</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yvNtNY4gP2MDDa5PgttWCw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/296/1*NMgEusmcg7Z18IzlGEgiYw.gif" /></figure><p>恩～算是滿簡單的！</p><h4>三、在聊天室Document底下新增collection儲存聊天內容messages</h4><p>跟新增聊天室寫法差不多，只是要在聊天室Document的id底下新增collection才會對應到，所以我先把所需要的資料先利用prepare傳到messagesViewController</p><pre>override func prepare(for segue: UIStoryboardSegue, sender: Any?) {<br>        if let controller = segue.destination as? MessagesViewController,<br>           let row = roomsTableView.indexPathForSelectedRow?.row,<br>           let displayPhoto = userPhoto.image?.jpegData(compressionQuality: 0.5)<br>        {<br>            controller.roomsName = rooms[row].id ?? &quot;&quot; <br><strong>// 聊天室Document的ID</strong><br>            controller.displayName = userName.text ?? &quot;&quot; <strong>// 使用者名稱</strong><br>            controller.displayPhoto = displayPhoto <strong>// 使用者照片</strong><br>        }<br>    }</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/610/1*lCUHphH1a5jZpbH0KUCQ9g.png" /></figure><p>新增messages的@IBAction</p><pre><a href="http://twitter.com/IBAction">@IBAction</a> func addMessagesButtonClicked(_ sender: UIButton) {<br>        let time = Date()<br>        let messages = messagesTextView.text ?? &quot;&quot;<br>        let db = Firestore.firestore()<br>        if let displayPhoto = displayPhoto,<br>           let email = Auth.auth().currentUser?.email<br>        {<br>            if messagesTextView.text != &quot;&quot; {<br>                let messages = Messages(email: email, displayName: displayName, displayPhoto: displayPhoto, messages: messages, time: time)<br>                do {<br>                    try <strong>db.collection(&quot;rooms&quot;).document(roomsName).collection(&quot;messages&quot;).addDocument(from: messages) <br>// collection(&quot;messages&quot;)底下自動產生DocumentID</strong><br>                    messagesTextView.text = &quot;&quot;<br>                }catch{<br>                    print(error)<br>                }<br>            }<br>        }<br>    }</pre><p>document(<strong><em>roomsName</em></strong>)就是上一頁點擊傳送過來的document(ID)這樣才會對應到同一個資料庫做新增messages動作，如下圖</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RCMGOqS_SpIrwas9dLccjw.png" /></figure><h4>四、呼叫addSnapshotListener持續偵測</h4><p>新增好messages後，再來就是需要讀取資料顯示到tableView，但如果使用跟上面建立rooms只呼叫getDocuments一樣的話，只有在點擊時才會觸發一次，這樣就無法使聊天訊息隨時更新，這時候我們就需要在viewDidload時呼叫addSnapshotListener來實現持續偵測更新，寫法如下：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yIrd5MH0PuTjV9iVMCiMBw.png" /></figure><pre>func checkMessagesChange(_ roomsName: String, _ messagesViewController: MessagesViewController) {<br>        <strong>db.collection(&quot;rooms&quot;).document(roomsName).collection(&quot;messages&quot;).order(by: &quot;time&quot;).addSnapshotListener</strong> { [weak messagesViewController] snapshot, error in<br>            guard let messagesViewController = messagesViewController else { return }<br>            guard let snapshot = snapshot else { return }<br>            <strong>let messages = snapshot.documents.compactMap { snapshot in<br>                try? snapshot.data(as: Messages.self)</strong><br>            }<br>            messagesViewController.messages = messages<br>        }<br>    }</pre><p>一樣在collection(“messages”)後面加上order(by: “time”)利用時間來排序後呼叫addSnapshotListener。</p><p>一樣生成messages呼叫compacMap轉成型別[Messages]，讓messagesViewController.messages接收生成的messages即可達到持續偵測。</p><p>最後就是在顯示cell時，因需要判斷是不是由現在登入的email發送訊息或是其他使用者發出的訊息，所以這邊我利用tableView(Prototype Cells)2來分別設計自己的訊息、以及其他使用者的訊息。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/514/1*s23rjqOJtKXeoFwuebvzkg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/470/1*1qtERORzCMTo8AfQYiv_Zg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/1*4RTkR-7sIqtdiT5-_BFVmA.png" /></figure><p>顯示內容是使用textView，因為textView本身有可以滑動畫面的效果，所以必須關掉讓他依據文字多寡自動長高，並且關閉編輯</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/486/1*FFGafmERmN2QlQq9RVO0Gw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/470/1*ISixxN4SSAFK6fShaYLTHw.png" /></figure><p>判斷是否是自己發送的，因上面傳送messages的@IBAction時有把Auth.auth().currentUser?.email傳入自訂型別[Messages]裡面，就可以判斷message.email == Auth.auth().currentUser?.email是否一樣，true的話就是自己發出的訊息、false就是其他使用者發出的訊息。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x9acQLR48vaypqw7Y_bA1g.png" /></figure><p>最後來試試看聊天時效果如何（其他使用者是在手機上面操作）</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/296/1*EMc_owgHYA25xxzRlP7nSg.gif" /></figure><p>Yes！完成囉～效果看起來好像還可以😂</p><p>以上跟上一篇就是這次的Firebase介紹，感謝大家！我會繼續努力的💪</p><p>那麼就下次再見囉👋</p><p>完整專案，以下連結 (Tags 1.1)</p><p><a href="https://github.com/YongShunTu/LoginDemo/tree/1.1">GitHub - YongShunTu/LoginDemo at 1.1</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8e6d819a5d04" width="1" height="1" alt=""><hr><p><a href="https://medium.com/peter-pan-swift-ios-class/18-2-%E5%88%A9%E7%94%A8firebase%E5%A5%97%E4%BB%B6-firebasefirestoreswift%E8%A3%BD%E4%BD%9C-ios-app-%E7%9A%84%E8%81%8A%E5%A4%A9%E5%8A%9F%E8%83%BD-8e6d819a5d04">#18–2-利用Firebase套件 FirebaseFirestoreSwift製作 iOS 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[#18–1-利用Firebase製作 iOS App 的登入註冊功能，抓取Lorem Picsum API圖片設定使用者照片，並自製簡單的讀取動畫]]></title>
            <link>https://medium.com/peter-pan-swift-ios-class/18-1-%E5%88%A9%E7%94%A8firebase%E8%A3%BD%E4%BD%9C-ios-app-%E7%9A%84%E7%99%BB%E5%85%A5%E8%A8%BB%E5%86%8A%E5%8A%9F%E8%83%BD-%E6%8A%93%E5%8F%96lorem-picsum-api%E5%9C%96%E7%89%87%E8%A8%AD%E5%AE%9A%E4%BD%BF%E7%94%A8%E8%80%85%E7%85%A7%E7%89%87-%E4%B8%A6%E8%87%AA%E8%A3%BD%E7%B0%A1%E5%96%AE%E7%9A%84%E8%AE%80%E5%8F%96%E5%8B%95%E7%95%AB-8160a7764104?source=rss-f5db7d13265a------2</link>
            <guid isPermaLink="false">https://medium.com/p/8160a7764104</guid>
            <dc:creator><![CDATA[Yong Shun]]></dc:creator>
            <pubDate>Sat, 07 May 2022 13:56:13 GMT</pubDate>
            <atom:updated>2022-06-14T11:03:29.160Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>這邊主要會分成兩篇來寫，第一篇介紹FirebaseAuth實作帳號註冊＆畫面牆跟動畫，第二篇會介紹FirebaseFirestoreSwift實作聊天室</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KzuKxOChrRlBH48fxDPYOw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TzWYqHhBZ9iFxd-6xfYE6g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IeWTnnLxErDfhZY8UyyIYA.png" /></figure><h4>功能介紹：</h4><ol><li>利用FirebaseAuth實現帳號申請、以及設定使用者的名稱及照片</li><li>抓取Lorem Picsum API圖片的URL</li><li>利用animate、Timer.scheduledTimer製作簡單的讀取動畫</li></ol><h4>一、註冊Firebase專案、安裝套件、新增（電子郵件/密碼）功能</h4><p>首先要使用FirebaseAuth當然就要先註冊囉(廢話😂)！相關註冊教學可以參考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%BB%BA%E7%AB%8B-firebase-%E5%B0%88%E6%A1%88-fbd6d19808c3">建立 Firebase 專案</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/%E8%A8%AD%E5%AE%9A-ios-app-%E7%9A%84-firebase-%E5%8A%9F%E8%83%BD-afcaaabe00f2">設定 iOS App 的 Firebase 功能和安裝 Firebase 套件</a></li></ul><p>註冊以及套件裝好後，再來就是新增（電子郵件/密碼）功能後，允許使用者帳密登入的開關打開後按 Save即可。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l5x1BfNHS5K_SLsP7hXBIw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wpdvtNXTovWThUbQg8_5xQ.png" /></figure><h4>二、Firebase帳密申請、設定使用者名稱及照片</h4><p>首先要呼叫 Auth 物件的 createUser來新增帳號密碼</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TYUxh39AGTIJObYP_mSufg.png" /></figure><p>在判斷物件createUser判斷是否註冊成功，成功後就可以呼叫currentUser?.createProfileChangeRequest()來設定使用者的名稱及照片</p><pre>guard let user = result?.user, error == nil else {<br>                return complection(.failure(error!))<br>            }<br>            complection(.success(user))<br>            let changeRequest = Auth.auth().currentUser?.createProfileChangeRequest()<br>            changeRequest?.photoURL = imageURL <strong>//建立使用者照片</strong><br>            changeRequest?.displayName = userID <strong>//建立使用者名稱</strong><br>            changeRequest?.commitChanges(completion: { error in<br>                guard error != nil else { return }<br>            })</pre><p>這樣就可以完成帳密註冊的功能了，很快就能理解，滿簡單的！但在設定使用者圖片時候因為需要的是URL，所以決定使用Lorem Picsum API來抓圖，也剛好練習之前都沒有做過的圖片牆作業😂，</p><h4>二、抓取Lorem Picsum API圖片的URL</h4><p>這邊我是用collectionView來製作，先設定好collectionView的一些設定</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_0nLxKhWAlaJOPAHOP2aYw.png" /></figure><pre>func configureCellSize(_ collectionView: UICollectionView, _ collectionViewWidth: CGFloat) {<br>        let itemSpace: CGFloat = 8 <strong>//每個圖檔的間距</strong><br>        let columCount: CGFloat = 4 <strong>//每行要顯示幾個圖檔</strong><br>        let flowLayout = collectionView.collectionViewLayout as? UICollectionViewFlowLayout <strong>//生成flowLayout</strong><br>        flowLayout?.sectionInset = UIEdgeInsets(top: 0, left: 8, bottom: 0, right: 8) <strong>//設定collectionView上下左右距離</strong><br>        let width = floor((collectionViewWidth - itemSpace * (columCount - 1) - 16) / columCount) <br>        flowLayout?.itemSize = CGSize(width: width, height: width) <strong>//設定每個item寬高</strong><br>        flowLayout?.estimatedItemSize = .zero <strong>//設定.zero後由itemsSize決定items寬高</strong><br>        flowLayout?.minimumLineSpacing = itemSpace <strong>//設定line間距</strong><br>        flowLayout?.minimumInteritemSpacing = itemSpace <strong>//設定Inter間距</strong><br>    }</pre><p>我的collection view 對齊螢幕的左右兩側，在viewDidload時需傳入UIScreen.main.bounds.width螢幕的寬度，才會正確。不然他會用原本在storboard設計時ipohne螢幕width去做計算。</p><p>這邊的let width = floor((collectionViewWidth — itemSpace * (columCount — 1)) / columCount)主要是一列要有4個圖所以中間會有三個間距，把collectionView的寬-減去itemSpace * (columCount — 1)= 8*(4–1)再減去collectionView的左右間距8 * 2=16，最後再除以每列4個就可以取得每個item的寬高了。</p><p>再來是抓取Lorem Picsum API圖片的URL</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EVDUUhzTRDEsuV-FDPW8cg.png" /></figure><pre><a href="https://picsum.photos/id/237/200/300">https://picsum.photos/id/237/200/300</a> <strong>//隨著id輸入的數字不一樣，會有不一樣的圖片</strong></pre><p>建立好Model好後，這邊我只抓80張圖就好(😂夠了)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/434/1*rBvvpKQg_2IFxF_2pEGIdA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mDVs4mLtMaQGhFBa-fc2Yw.png" /></figure><p>再來就是建立抓取圖檔的func，並顯示在collectionView</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t2lAnbiPtKaEV5wE8GukAw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GujAYaNGkm2jil-PpEdKMg.png" /></figure><p>一樣會有thread(執行緒)的問題記得要DispatchQueue.main.async，並在還沒抓到圖檔前，先讓imageView顯示另外放在Assets的圖檔“camera”</p><p>來看看實際畫面如何</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/296/1*_xxnNk4IjnZvBQc6c7YsHQ.gif" /></figure><p>沒有問題👍！！</p><p>最後在註冊頁面利用@IBSegueAction讀取到畫面牆的自制delegate，來傳遞資料。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wpLAoz5cUHqjdKAtpEYCSw.png" /><figcaption>@IBSegueAction讀取到畫面牆的自制delegate</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Se_X4xDYVvTDIrtTS61pDw.png" /><figcaption>自製delegate</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W-sT8EV5Ugs5Pgs20DRfjw.png" /><figcaption>點擊collectionView執行資料傳遞</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GC6XC4mazhFj9Z4i1XKoeg.png" /><figcaption>註冊頁面接收資料並更新大頭照</figcaption></figure><p>來看看畫面如何</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/296/1*7P4KhgoRvEEO73RBESu7xQ.gif" /></figure><p>沒有問題👌</p><p>生成var displayPhotoURL: URL? 接收，在呼叫createUser創立帳密時候就可以把URL傳進去，就可以成功新增使用者的圖片囉🎉</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Xn0hQVCvB80iW3lL6XFUxA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W-ryntkINs0ygnmWlvfzag.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-MuXvk_Xv5Cuzql6Vm1StA.png" /></figure><h4>三、讀取畫面動畫（新增一個viewController畫面來測試）</h4><ol><li><em>讓文字會有閃爍的效果，這邊需要用到UIView.animate，寫法如下：</em></li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OHR1iofRaf13NfGHUBH9QQ.png" /></figure><pre>options: [.autoreverse, .repeat]</pre><p>options裡的參數UIView.AnimationOptions = []，所以只要參入.autoreverse(自動反轉)、.repeat(重複)，就可以達到文字alpha0~alpha1每一秒一直重複這個動作</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/296/1*lMRkNXfW5kBY4OYTUW6XSw.gif" /></figure><p>2. <em>讓label慢慢增加文字的效果，這邊需要用到Timer.scheduledTimer，寫法如下：</em></p><p>這邊我另外寫一個AnimationEffectController來控制，這樣一來程式碼較乾淨不雜，二來其他畫面也需要的話呼叫方便。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RcjYnYCfMlG6fAvtAdnfyQ.png" /></figure><p>這邊因為timer的repeats: true可能會有記憶體的問題，所以在closure裡面加上[weak viewController]，雖然這樣可以解決頁面消失後立即死掉，但timer還是會繼續執行，所以必須多判斷在viewController == nil時執行timer.invalidate()，即可順利停止timer執行</p><p>再來把想要顯示的文字，利用labelText.enumerated()的方法可以讀取到index,value，在withTimeInterval裡輸入Double(index) / Double(labelText.count)，讓每段文字都可以在一秒內顯示完畢</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CQw35jMYfubInSbymo2fLw.png" /></figure><p>讀取畫面的文字可能會有兩段要顯示，所以這邊再另外加一個Timer.scheduledTimer來決定結束的時間。</p><p>好了之後新增兩段文字來測試看看效果如何😎</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F5G9F9zuhAa3UAIgAdsG5w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/296/1*h6Cp3fYxA2gwhZQ4ItV_Hw.gif" /></figure><h4>四、帳號密碼登入、自動判斷是否已經登入、搭配動畫實現帳號註冊登入畫面</h4><p><strong><em>帳號密碼登入：</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*itpSOWVQcurjYc5BH5QgHA.png" /></figure><p>呼叫Auth.auth().signIn傳入email, password即可登入</p><p><strong><em>viewDidLoad時自動判斷是否已經登入過：</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/618/1*MtnC8mXDZOzmUyfZu9NRyw.png" /></figure><p>呼叫Auth.auth().currentUser，如果已經登入過就會有資料(“success”)，如果登入過就會是nil(“fail”)</p><p><strong><em>讀取使用者的基本資料：</em></strong></p><pre>if let user = Auth.auth().currentUser {<br>   print(user.uid, user.email, user.displayName, user.photoURL)<br>}</pre><p>最後把這些功能集合起來看看效果如何🧐</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/296/1*dzZm-Ll1ZV9F13bd5y-kyQ.gif" /></figure><p>OK🎉~完成囉！看起來比較有feel了😂</p><p>這篇就介紹到這邊～下一篇開始介紹『<strong>FirebaseFirestoreSwift實作聊天室』</strong></p><p><a href="https://medium.com/@a49980060/18-2-%E5%88%A9%E7%94%A8firebase%E5%A5%97%E4%BB%B6-firebasefirestoreswift%E8%A3%BD%E4%BD%9C-ios-app-%E7%9A%84%E8%81%8A%E5%A4%A9%E5%8A%9F%E8%83%BD-8e6d819a5d04">#18–2-利用Firebase套件 FirebaseFirestoreSwift製作 iOS App 的聊天功能</a></p><p>完整專案，以下連結 (Tags 1.0)</p><p><a href="https://github.com/YongShunTu/LoginDemo/tree/1.0">GitHub - YongShunTu/LoginDemo at 1.0</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8160a7764104" width="1" height="1" alt=""><hr><p><a href="https://medium.com/peter-pan-swift-ios-class/18-1-%E5%88%A9%E7%94%A8firebase%E8%A3%BD%E4%BD%9C-ios-app-%E7%9A%84%E7%99%BB%E5%85%A5%E8%A8%BB%E5%86%8A%E5%8A%9F%E8%83%BD-%E6%8A%93%E5%8F%96lorem-picsum-api%E5%9C%96%E7%89%87%E8%A8%AD%E5%AE%9A%E4%BD%BF%E7%94%A8%E8%80%85%E7%85%A7%E7%89%87-%E4%B8%A6%E8%87%AA%E8%A3%BD%E7%B0%A1%E5%96%AE%E7%9A%84%E8%AE%80%E5%8F%96%E5%8B%95%E7%95%AB-8160a7764104">#18–1-利用Firebase製作 iOS App 的登入註冊功能，抓取Lorem Picsum 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[#17–10-客製化『來吃波奇』專用記帳APP，計算收入及支出，換算成百分比在UIBezierPath()圓餅圖顯示]]></title>
            <link>https://medium.com/peter-pan-swift-ios-class/17-10-%E5%AE%A2%E8%A3%BD%E5%8C%96-%E4%BE%86%E5%90%83%E6%B3%A2%E5%A5%87-%E5%B0%88%E7%94%A8%E8%A8%98%E5%B8%B3app-%E8%A8%88%E7%AE%97%E6%94%B6%E5%85%A5%E5%8F%8A%E6%94%AF%E5%87%BA-%E6%8F%9B%E7%AE%97%E6%88%90%E7%99%BE%E5%88%86%E6%AF%94%E5%9C%A8uibezierpath-%E5%9C%93%E9%A4%85%E5%9C%96%E9%A1%AF%E7%A4%BA-b44601e3c33a?source=rss-f5db7d13265a------2</link>
            <guid isPermaLink="false">https://medium.com/p/b44601e3c33a</guid>
            <dc:creator><![CDATA[Yong Shun]]></dc:creator>
            <pubDate>Thu, 31 Mar 2022 10:29:57 GMT</pubDate>
            <atom:updated>2022-04-01T03:15:17.450Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5YlFM-fXz-uHOw36u26o5A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1yzBvTAEzLlXwiQFoRiV7Q.png" /></figure><h4>功能介紹：</h4><ol><li>UIBezierPath()繪製圓餅圖</li><li>reduce計算出收入及各類支出金額百分比</li></ol><h4>上一篇：</h4><p><a href="https://medium.com/@a49980060/17-9-%E5%AE%A2%E8%A3%BD%E5%8C%96-%E4%BE%86%E5%90%83%E6%B3%A2%E5%A5%87-%E5%B0%88%E7%94%A8%E8%A8%98%E5%B8%B3app-%E8%87%AA%E8%A3%BDpickerview%E5%B9%B4%E6%9C%88%E4%BB%BD%E9%81%B8%E6%93%87-serchbar%E6%90%9C%E5%B0%8B%E9%97%9C%E9%8D%B5%E5%AD%97%E5%B8%B3%E5%8B%99-4b5b0b703f68">#17–9-客製化『來吃波奇』專用記帳APP，自製pickerView年月份選擇、serchBar搜尋關鍵字帳務</a></p><h4>一、UIBezierPath()圓餅圖</h4><p>對另一半來說，這整個APP最重要的就是這個圓餅圖功能了，因為每個月她都會算收入跟各項支出的百分比，每次算這個都絞盡腦汁的在算（數學不好？😂），所以就幫他直接整個換算好後顯示在圓餅圖上，讓她可以一目瞭然。</p><p>先來說說怎麼用UIBezierPath()來繪製，先來看看完整的程式碼。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Iid_-IOhfuJCu62yxSEPpQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5xXMt9-4nc8EziYbaY8MpQ.png" /></figure><p>以下程式圓餅圖，pi（aDegree）半徑（radius）起點（startDegree）設定好後，之後用for迴圈跑percentages每跑完一次讓起點（startDegree）等於終點（endDegree）就可以讓整個圓完成，另外也要特別注意生成pathView的中心點（pathViewBoundsCenter）必須用bounds.center不能用frame.center（frame是看superView的對應位子）位子會跑掉</p><pre>func showPathView() {<br>        <br><strong>        let aDegree = CGFloat.pi / 180<br>        let radius: CGFloat = pathView.bounds.width / 2<br>        var startDegree: CGFloat = 270</strong><br>        var layerColorIndex = 0<br>        <br>        for percentage in percentagesTest {<br>            <strong>let endDegree = startDegree + 360 * percentage.value / 100</strong><br>            <strong>let pathViewBoundsCenter = CGPoint(x: pathView.bounds.maxX / 2, y: pathView.bounds.maxY / 2)</strong><br>            let percentagePath = UIBezierPath()<br>            percentagePath.move(to: pathViewBoundsCenter)<br>            percentagePath.addArc(withCenter: pathViewBoundsCenter, radius: radius, startAngle: aDegree * startDegree, endAngle: aDegree * endDegree, clockwise: true)<br>            <br>            let percentageLayer = CAShapeLayer()<br>            percentageLayer.path = percentagePath.cgPath<br>            percentageLayer.fillColor = layerColor[layerColorIndex].cgColor<br>            layerColorIndex += 1<br>            pathView.layer.addSublayer(percentageLayer)<br>            pathView.addSubview(self.createLabel(percentage: percentage.value, percentageText: percentage.key, starDegree: startDegree, radius: radius, aDegree: aDegree, center: pathViewBoundsCenter))<br>            <strong>startDegree = endDegree</strong><br>            <br>        }<br>    }</pre><p>以下程式圓餅圖上的文字，文字想要在圓餅圖的外面所以在UIBezierPath(radius: radius + 15)半徑在多15，並生成UILabel()設定好樣式以及顯示</p><pre>func createLabel(percentage: CGFloat, percentageText: String, starDegree: CGFloat, radius: CGFloat, aDegree: CGFloat, center: CGPoint) -&gt; UILabel {<br>        let textCenterDegree = starDegree + 360 * percentage / 2 / 100<br>        let textPath = UIBezierPath(arcCenter: center, <strong>radius: radius + 15</strong>, startAngle: aDegree * textCenterDegree, endAngle: aDegree * textCenterDegree, clockwise: true)<br>        <br>        let label = UILabel()<br>        label.backgroundColor = .clear<br>        label.font = UIFont.systemFont(ofSize: 9)<br>        label.numberOfLines = 2<br>        label.textAlignment = .center<br>        if percentage &gt;= 3 {<br>            label.text = &quot;\(percentageText)\n\(String(format: &quot;%.2f&quot;, percentage))%&quot;<br>        }<br>        label.sizeToFit()<br>        label.center = textPath.currentPoint<br>        return label<br>    }</pre><p>完成後，先來測試看看，假如我的percentages = [“收入”:25, “食材”: 25, “人力”: 30, “雜費”: 20]</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/678/1*PWksGhPoV08qxZopsALixQ.png" /></figure><p>看起來還不錯！</p><h4>二、計算specificMonthInAccounts所有收入（其他收入）、支出的金額</h4><p>這邊跟前幾篇一樣，利用pickerView自製做好選擇年月份之後，利用filer生成特定月份條件的specificMonthInAccounts，忘記可以再看一下以下連結</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/17-7-%E5%AE%A2%E8%A3%BD%E5%8C%96-%E4%BE%86%E5%90%83%E6%B3%A2%E5%A5%87-%E5%B0%88%E7%94%A8%E8%A8%98%E5%B8%B3app-%E9%AB%98%E9%9A%8E%E5%87%BD%E6%95%B8sorted-filter-reduce%E6%87%89%E7%94%A8-%E8%AE%93%E4%B8%BB%E9%A0%81%E9%A1%AF%E7%A4%BA%E7%89%B9%E5%AE%9A%E6%97%A5%E6%9C%9F%E5%B8%B3%E5%8B%99-numberformatter%E9%87%91%E9%A1%8D%E9%A1%AF%E7%A4%BA-7deb5f4fe70d">#17–7-客製化『來吃波奇』專用記帳APP，高階函數sorted、filter、reduce應用，讓主頁顯示特定日期帳務，NumberFormatter金額顯示</a></p><p>再來就是我的圓餅圖是用percentages迴圈去跑，以上面範例percentages = [“收入”:25, “食材”: 25, “人力”: 30, “雜費”: 20]，可以知道裡面數字加起來就是剛好100也就是圓餅圖的整個圓100%，但要怎麼讓我的specificMonthInAccounts可以變成像範例percentages這樣呢，以下是我的計算方法程式。</p><p>計算出總Income收入（但是我的當天營收個別計算）下面會說明</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EyBvRfax0oMne5_uuoRAzg.png" /></figure><p>計算出總支出Expenses</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DQfCBB1eVn0zE4raezCkzQ.png" /></figure><p>利用reduce幫我生成percentageReport（dictionary[String: Double]），在讓我的percentages = percentageReport用sorted依序大到小</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8Gu1VfVaJufP5VstPF19sg.png" /></figure><p>這邊主要 func calculatePercentage()裡面我個別計算income的當天營收，用以下範例來看</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/283/1*KdN_GdEJqlPvZzwFCFjXnA.png" /></figure><p>以範例來說我的總營收（當天營收＋其他收入）=10000</p><pre>let percentageReport = self.specificMonthInAccounts.reduce(into: [String: Double]()) { counts, accounts in<br>            var money = accounts.money<br>            let incomeTotal = self.calculateMonthlyIncome(.income)<br>            let expensesTotal = self.calulateMothlyExpenses()<br>            let percentage = (incomeTotal - expensesTotal) / incomeTotal<br>            switch ExpenditureOrIncome.init(rawValue: accounts.expenditureOrIncome) {<br>            case .income:<br>                if accounts.category == &quot;收入&quot; {<br>                    money *= percentage<br>                }<br>                counts[accounts.category, default: 0] += money<br>            case .expenditure:<br>                counts[accounts.category, default: 0] += money<br>            case .none:<br>                break<br>            }<br>        }</pre><p>這邊我先算出當天營收的部分incomeTotal = 9000</p><p>再來算總支出expensesTotal = 6000</p><p>純收入百分比percentage =（9000–6000）/ 9000 = 33.3333333….</p><p>如果accounts.category == “收入” ，讓每一次的收入（當天營收 ）* percentage</p><p>2500 * 0.33… + 3500 * 0.33… + 3000 * 0.33… ＝ 4000</p><p>最後其他部分計算好後，再讓我的percentages=percentageReport的value去做大～小排序，最後print(“\(percentages)”)出來的結果，這也是為什麼我的收入要另外計算當天營收（因為他有包含成本的％數），而其他收入雖然也算總營收但不受成本的影響（就把它想成是多賺的）</p><pre>self.percentages = percentageReport.sorted(by: { firstDictionary, secondDictionary in<br>            return firstDictionary.value &gt; secondDictionary.value</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2VBFtelyy1RHgRmVC6q4oQ.png" /></figure><p>最後percentages出來的結果就是我需要的！再來就把圓餅圖的程式func showPathView()稍微改一下就可以了</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FaU77WRTRUTtClP4mrJ-8A.png" /></figure><pre><strong>let</strong> incomeTotal = calculateMonthlyIncome(.allIncome)</pre><pre><strong>let</strong> value = percentage.value / incomeTotal * 100</pre><p>計算incomeTotal全部營收 = 10000</p><p>for迴圈percentages裡的value （4000 / 10000 * 100 = 40、3000 / 10000 * 100 = 30、….），這樣就可以取得每個項目在圓餅圖裡個別佔比是多少了👍</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/730/1*E4JQA7JW-aS8Mf3ruR0J6Q.png" /></figure><p>當然也要來實際測試金額不一樣，是不是沒有問題。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/296/1*Rnj16I4nLkJIeOEwsDS_kg.gif" /></figure><p>Yes~實際操作上沒有問題🎉，之前的每一篇也都是持續優化，基本上都是測試好幾遍😂也讓另一伴在實機上操作，讓我抓到非常多的問題去修正，測試期間也發現還需要多一些功能，最後才完成這個作品。</p><p>客製化『來吃波奇』專用記帳APP，應該就介紹到這邊全部結束了～後面帳戶功能的部分在前面基本上都有說明到，所以就沒打算在寫了（懶了😏？）</p><p>謝謝大家耐心看完，下次見囉👋</p><p>有興趣的可以下載我的完整專案，以下連結</p><p><a href="https://github.com/YongShunTu/AccountingAPP">GitHub - YongShunTu/AccountingAPP</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b44601e3c33a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/peter-pan-swift-ios-class/17-10-%E5%AE%A2%E8%A3%BD%E5%8C%96-%E4%BE%86%E5%90%83%E6%B3%A2%E5%A5%87-%E5%B0%88%E7%94%A8%E8%A8%98%E5%B8%B3app-%E8%A8%88%E7%AE%97%E6%94%B6%E5%85%A5%E5%8F%8A%E6%94%AF%E5%87%BA-%E6%8F%9B%E7%AE%97%E6%88%90%E7%99%BE%E5%88%86%E6%AF%94%E5%9C%A8uibezierpath-%E5%9C%93%E9%A4%85%E5%9C%96%E9%A1%AF%E7%A4%BA-b44601e3c33a">#17–10-客製化『來吃波奇』專用記帳APP，計算收入及支出，換算成百分比在UIBezierPath()圓餅圖顯示</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[#17–9-客製化『來吃波奇』專用記帳APP，自製pickerView年月份選擇、serchBar搜尋關鍵字帳務]]></title>
            <link>https://medium.com/peter-pan-swift-ios-class/17-9-%E5%AE%A2%E8%A3%BD%E5%8C%96-%E4%BE%86%E5%90%83%E6%B3%A2%E5%A5%87-%E5%B0%88%E7%94%A8%E8%A8%98%E5%B8%B3app-%E8%87%AA%E8%A3%BDpickerview%E5%B9%B4%E6%9C%88%E4%BB%BD%E9%81%B8%E6%93%87-serchbar%E6%90%9C%E5%B0%8B%E9%97%9C%E9%8D%B5%E5%AD%97%E5%B8%B3%E5%8B%99-4b5b0b703f68?source=rss-f5db7d13265a------2</link>
            <guid isPermaLink="false">https://medium.com/p/4b5b0b703f68</guid>
            <dc:creator><![CDATA[Yong Shun]]></dc:creator>
            <pubDate>Tue, 29 Mar 2022 12:04:36 GMT</pubDate>
            <atom:updated>2022-03-31T10:32:34.325Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KnhPKOSZiZq1PT6hkuwgPg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nuu1uA1kjKe9yhNQ0V83GQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FR3FxB7mwXNnOelch__4Lw.png" /></figure><h4>功能介紹：</h4><ol><li>高階函數reduce(into:_:)找出目前有資料的年份</li><li>自製pickerView選單（年份、月份）</li><li>searchBar搜尋關鍵字帳務（localizedStandardContains）</li></ol><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/17-8-%E5%AE%A2%E8%A3%BD%E5%8C%96-%E4%BE%86%E5%90%83%E6%B3%A2%E5%A5%87-%E5%B0%88%E7%94%A8%E8%A8%98%E5%B8%B3app-prepare%E5%82%B3%E9%81%9E%E4%B8%BB%E9%A0%81%E6%9B%B4%E6%94%B9%E7%9A%84%E8%B3%87%E6%96%99-%E8%87%AA%E8%A8%82delegate%E5%9B%9E%E5%82%B3%E6%9B%B4%E6%94%B9%E5%BE%8C%E7%9A%84%E8%B3%87%E6%96%99-%E4%B8%A6%E5%88%A9%E7%94%A8enumerated-%E4%BF%AE%E6%94%B9%E5%B0%8D%E6%87%89%E8%B3%87%E6%96%99index-f2bb1157e9b1">#17–8-客製化『來吃波奇』專用記帳APP，prepare傳遞主頁更改的資料，自訂delegate回傳更改後的資料＆並利用enumerated()修改對應資料index</a></p><h4>一、高階函數另一種用法reduce(into:_:)</h4><p>當初在製作選擇年月份的時候，是可以直接用datePicker來製作就可以，但另一伴說之前的年份不需要只要從今年開始讓我選擇就好，所以我就想說那用另一種方式用pickerView來呈現，最後討論結果。</p><blockquote><strong>年份就以現有的帳務年份為基礎（2022年有帳務就顯示1個2022年選項就好、2022~2023有帳務就顯示2022＆2023選項就好）</strong></blockquote><blockquote><strong>月份就固定1月～12月</strong></blockquote><p>年份用變數years從Accounts資料抓取，月份就用常數months固定</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EeIobSN54RH7Ssm7tNDEVw.png" /></figure><p>至於年份要怎麼抓資料，這邊我使用reduce另一種寫法reduce(into:_:)，至於要怎麼使用，讓我們來看官網怎麼說</p><p><a href="https://developer.apple.com/documentation/swift/array/3126956-reduce">Apple Developer Documentation</a></p><pre><strong>func reduce&lt;Result&gt;(into initialResult: Result, _ updateAccumulatingResult: (inout Result, Element) throws -&gt; ()) rethrows -&gt; Result</strong></pre><pre>let letters = &quot;abracadabra&quot;</pre><pre>let letterCount = letters.reduce(into: [:]) { counts, letter in    </pre><pre>counts[letter, default: 0] += 1}</pre><pre>// letterCount == [&quot;a&quot;: 5, &quot;b&quot;: 2, &quot;r&quot;: 2, &quot;c&quot;: 1, &quot;d&quot;: 1]</pre><p>可以看到官網生成一個letterCount（型別是 into: [:] dictionary），計算出[“a”: 5, “b”: 2, “r”: 2, “c”: 1, “d”: 1] 裡面個別英文在letters裡面有幾個。</p><p>但我要抓的年份固定都是1，只是要抓總共有幾個年份而已，所以我的寫法是以下，差別在default: 1（初始值）+= 0（不管有幾筆都不管所以+=0）</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cYTS0q1luyCAIVzNdoygFQ.png" /></figure><p>以下圖例（我的Accounts有5筆資料，2021一筆、2022三筆、2023一筆）</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H0sniGc0sGPhhPlL2-xnUQ.png" /></figure><p>所以我生成的year（dictionary），print出來的結果是</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/674/1*3qKqpGbaE6ZE6GKQidIi5Q.png" /></figure><p>變數years = year.keys.sorted(by: &gt;)因為year是dictionary所以可以直接用keys.sorted(by: &gt;)大～小，這時我的years就變成下圖</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/674/1*_vSe63IiMeREHD5_j87wsQ.png" /></figure><h4>二、自製pickerView選單</h4><p>這邊我在storyboard歷史紀錄頁面最外層放了一個Select Picker View Blocking View在裡面把所有的所有的介面拉好，如下圖</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qFKuaMX7KadIRPpRuPaHcg.png" /></figure><p>剛剛上面年份＆月份已經寫好，所以先把顯示picker的Components、RowsInComponent、titleForRow寫好一樣要遵從UIPickerViewDelegate, UIPickerViewDataSource</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Rlq1dvMFNBm7xh-9fLJcaA.png" /></figure><p>再來就是把裡面的程式碼功能寫出來，主要解說func selectYearAndMonthButtonClicked、func showYearAndMonthPickerView</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9kQ4prHe6rNchlld7KWd5Q.png" /></figure><blockquote><strong>點擊確定執行func selectYearAndMonthButtonClicked</strong></blockquote><pre>@IBAction func selectYearAndMonthButtonClicked(_ sender: UIButton) {</pre><pre>let yearIndex = selectYearAndMonthPickerView.selectedRow(inComponent: 0) <strong>// 生成目前點選component0的index</strong></pre><pre>let monthIndex = selectYearAndMonthPickerView.selectedRow(inComponent: 1) <strong>// 生成目前點選component1的index</strong></pre><pre>currentYearString = years[yearIndex] <strong>// 目前年份的string</strong></pre><pre>currentMonthString = months[monthIndex] <strong>// 目前月份的string</strong></pre><pre>yearAndMonthString = currentYearString + currentMonthString <strong>// 目前年月份的string</strong></pre><pre>closeYearAndMonthPickerView()</pre><pre>}</pre><p>抓到yearAndMonthString後，更新button.setTitle跟findSearchTextInSpecificMonthInAccounts顯示到tableView（跟之前第7篇二、利用filter生成符合特定條件的Accounts一樣，只是有多searchBar功能，等下第三點會說到）</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OsS2-hJ5laGT5I-yurSmIQ.png" /></figure><blockquote><strong>點擊選擇年月份執行func showYearAndMonthPickerViewButtonClicked，如果years == []跳出alter目前無資料，有資料的話執行func showYearAndMonthPickerView()</strong></blockquote><pre>func showYearAndMonthPickerView() {</pre><pre>if let yearIndex = years.firstIndex(of: currentYearString), <br><strong>// 目前currentYearString在years的index</strong></pre><pre>let monthIndex = months.firstIndex(of: currentMonthString)<br><strong>// 目前currentMonthString在months的index</strong><br> {</pre><pre>self.selectYearAndMonthPickerView.selectRow(yearIndex, inComponent: 0, animated: false) <br><strong>// pickerView(component0)目前在第yearIndex</strong></pre><pre>self.selectYearAndMonthPickerView.selectRow(monthIndex, inComponent: 1, animated: true) <br><strong>// pickerView(component1)目前在第monthIndexIndex</strong></pre><pre>}</pre><p>這邊主要是點擊選擇年月份的時候pickerView會顯示上次選擇的結果，並我在showPickerView跟closePickerView都有用UIViewPropertyAnimator.runningPropertyAnimator讓整個最外層的Select PickerViewBlockingView.alpha（0~1 or 1~0 都讓他0.3秒完成）讓他有動畫的效果。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a2FKzSnvkonXssT-sanEKg.png" /></figure><p>來看看實際操作效果如何～</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/296/1*7IWjK7PF1tY4EuHELARS3w.gif" /></figure><p>恩～還不錯👍！</p><h4>三、遵從UISearchBarDelegate實現searchText變更時利用filter生成特殊條件的specificMonthInAccounts</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rZ297Pn3Q129niPBEGuyew.png" /></figure><p>這邊func findSearchTextInSpecificMonthInAccounts我另外寫，在searchBar變更text時或searchBarSearchButton（keyboard點擊search時）傳入searchBar.text</p><pre>func findSearchTextInSpecificMonthInAccounts(_ searchText: String) {<br>        if searchText.isEmpty == false { // 如果searchText不是空直執行<br>            self.specificMonthInAccounts = fetchSpecificMonthInAccounts(self.accounts, yearAndMonthString).filter ({ accounts in<br>                accounts.subtype.localizedStandardContains(searchText) || accounts.project.localizedStandardContains(searchText) || accounts.note.localizedStandardContains(searchText)<br>// 找尋accounts.subtype,project,not相關字</pre><pre>            })<br>        }else{ // 如果searchText是空直執行<br>            self.specificMonthInAccounts = fetchSpecificMonthInAccounts(self.accounts, yearAndMonthString)<br>        }<br>    }</pre><p>這樣我的specificMonthInAccounts就可以達到searchBar相關字顯示特定資料了，並且我的accounts跟yearAndMonthString都使用此func，這樣不管是點擊編輯修改刪除資料，或是選到其他月份，都還是會以searchBarText顯示相關字的資料。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*slreQCMnSxVbAmnUYAHesw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*23_RdjWFinueepAFLQU0wA.png" /></figure><p>當然specificMonthInAccounts有變動時要記得reloadData（還有顯示總金額，跟historicalAccountsTableViewBlockingView.alpha（1,0）顯示隱藏就不多說明）</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3byQne8En9HYoqgcX-Eutg.png" /></figure><p>來看看實際搜尋起來的感覺如何～</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/296/1*9a83S8XsHrxeEZ70ugvlYg.gif" /></figure><p>OK~沒有問題！畫面也很順暢🎉</p><p>這篇就介紹到這邊，下一篇開始介紹『報表頁面，UIBezierPath()繪製圓餅圖顯示收入＆成本百分比』</p><p><a href="https://medium.com/@a49980060/17-10-%E5%AE%A2%E8%A3%BD%E5%8C%96-%E4%BE%86%E5%90%83%E6%B3%A2%E5%A5%87-%E5%B0%88%E7%94%A8%E8%A8%98%E5%B8%B3app-%E8%A8%88%E7%AE%97%E6%94%B6%E5%85%A5%E5%8F%8A%E6%94%AF%E5%87%BA-%E6%8F%9B%E7%AE%97%E6%88%90%E7%99%BE%E5%88%86%E6%AF%94%E5%9C%A8uibezierpath-%E5%9C%93%E9%A4%85%E5%9C%96%E9%A1%AF%E7%A4%BA-b44601e3c33a">#17–10-客製化『來吃波奇』專用記帳APP，計算收入及支出，換算成百分比在UIBezierPath()圓餅圖顯示</a></p><p>有興趣的可以下載我的完整專案，以下連結</p><p><a href="https://github.com/YongShunTu/AccountingAPP">GitHub - YongShunTu/AccountingAPP</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4b5b0b703f68" width="1" height="1" alt=""><hr><p><a href="https://medium.com/peter-pan-swift-ios-class/17-9-%E5%AE%A2%E8%A3%BD%E5%8C%96-%E4%BE%86%E5%90%83%E6%B3%A2%E5%A5%87-%E5%B0%88%E7%94%A8%E8%A8%98%E5%B8%B3app-%E8%87%AA%E8%A3%BDpickerview%E5%B9%B4%E6%9C%88%E4%BB%BD%E9%81%B8%E6%93%87-serchbar%E6%90%9C%E5%B0%8B%E9%97%9C%E9%8D%B5%E5%AD%97%E5%B8%B3%E5%8B%99-4b5b0b703f68">#17–9-客製化『來吃波奇』專用記帳APP，自製pickerView年月份選擇、serchBar搜尋關鍵字帳務</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[#17–8-客製化『來吃波奇』專用記帳APP，prepare傳遞主頁更改的資料，自訂delegate回傳更改後的資料＆並利用enumerated()修改對應資料index]]></title>
            <link>https://medium.com/peter-pan-swift-ios-class/17-8-%E5%AE%A2%E8%A3%BD%E5%8C%96-%E4%BE%86%E5%90%83%E6%B3%A2%E5%A5%87-%E5%B0%88%E7%94%A8%E8%A8%98%E5%B8%B3app-prepare%E5%82%B3%E9%81%9E%E4%B8%BB%E9%A0%81%E6%9B%B4%E6%94%B9%E7%9A%84%E8%B3%87%E6%96%99-%E8%87%AA%E8%A8%82delegate%E5%9B%9E%E5%82%B3%E6%9B%B4%E6%94%B9%E5%BE%8C%E7%9A%84%E8%B3%87%E6%96%99-%E4%B8%A6%E5%88%A9%E7%94%A8enumerated-%E4%BF%AE%E6%94%B9%E5%B0%8D%E6%87%89%E8%B3%87%E6%96%99index-f2bb1157e9b1?source=rss-f5db7d13265a------2</link>
            <guid isPermaLink="false">https://medium.com/p/f2bb1157e9b1</guid>
            <dc:creator><![CDATA[Yong Shun]]></dc:creator>
            <pubDate>Mon, 28 Mar 2022 11:53:49 GMT</pubDate>
            <atom:updated>2022-03-29T12:05:13.223Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t2dgrrRYp-NOoybujbTEbg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GbF9Wh0FG3vkJ6q8G27CFA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bVlhl5mqkMDtJ3XES9CyMQ.png" /></figure><h4>功能介紹：</h4><ol><li>prepare傳遞資料</li><li>利用自訂delegate回傳更改後的資料回主頁</li><li>enumerated()找到對應的資料index</li></ol><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/17-7-%E5%AE%A2%E8%A3%BD%E5%8C%96-%E4%BE%86%E5%90%83%E6%B3%A2%E5%A5%87-%E5%B0%88%E7%94%A8%E8%A8%98%E5%B8%B3app-%E9%AB%98%E9%9A%8E%E5%87%BD%E6%95%B8sorted-filter-reduce%E6%87%89%E7%94%A8-%E8%AE%93%E4%B8%BB%E9%A0%81%E9%A1%AF%E7%A4%BA%E7%89%B9%E5%AE%9A%E6%97%A5%E6%9C%9F%E5%B8%B3%E5%8B%99-numberformatter%E9%87%91%E9%A1%8D%E9%A1%AF%E7%A4%BA-7deb5f4fe70d">#17–7-客製化『來吃波奇』專用記帳APP，高階函數sorted、filter、reduce應用，讓主頁顯示特定日期帳務，NumberFormatter金額顯示</a></p><h4>一、prepare傳遞資料</h4><p>這邊的主頁（mainViewController）有連segue到編輯頁面（EditAccountViewController），所以一樣用prepare傳遞要修改的資料，而EditAccountViewController有自訂delegate，一樣要設定</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/972/1*Zrx-fmtdHFoYAFHX-ABijw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mMvGHkZzZzPDAm9XSwDZzg.png" /></figure><pre>override func prepare(for segue: UIStoryboardSegue, sender: Any?) {</pre><pre>if let controller = segue.destination as? EditAccountViewController, // 生成controller目的地(EditAccountViewController)</pre><pre>let row = mainTableView.indexPathForSelectedRow?.row { // 判斷點選的row是第幾個</pre><pre>controller.delegate = self // 設定delegate</pre><pre>controller.account = self.specificDateInAccounts[row] // 傳遞specificDateInAccounts[row]資料</pre><pre>}</pre><p>在updateEditAccount()</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rd7Odm0A-mIqDd9MCgS7ew.png" /></figure><p>if let imageName = account.imageName當初新增帳務如果有圖片，那我的account.imageName就會有資料，再取出imageURL跟讀取檔案一樣（Accounts.documentDirectory.appendingPathComponent(imageName).appendingPathExtension(“jpeg”)，在生成image = UIImage(contentsOfFile: imageURL.path) 『imageURL.path是imageURL的資料夾路徑』</p><p>這邊我有特別把money.text如果是（Foodpanda，account.money / 0.7）（Uber，account.money / 0.66），主要是當初在新增帳務的時候，會直接把金額計算好（平台的成本）顯示在主頁上，所以在編輯時候也該先把金額計算回來，如果一開始在新增帳務時候按錯到有平台費，那這樣要改回沒有平台費的時候才知道原本金額多少。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/296/1*yBLO6MwbkUS6hE5aLtgk-A.gif" /></figure><h4>二、自訂delegate（func editAccount、func deleteAccount）修改＆刪除資料</h4><p>這邊跟之前新增帳務的時候一樣，我一樣自訂了delegate使用（傳遞資料真的滿方便的）</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/846/1*wqLNZO_R5Qd60ZERFq_7lw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T9HTSYcvTCH9u_wtRA1-xA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vWqGekTp_1VHdp7z5VIMyQ.png" /></figure><p>這邊特別要注意的是，雖然上面<strong>一、prepare</strong>傳遞到editAccountViewController修改的是specificDateInAccounts[row]（前一篇有說到specificDateInAccounts是特定條件日期的accounts），但傳回主頁main的時候要修改的需要是accounts，從下圖（以2022/3/26資料來看）可以明顯看到資料在specificDateInAccounts[0]、account[1]，如果直接修改accounts[row]那資料就會錯了，所以必須找到accountIndex。但要怎麼找到呢？</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BcM-Lja5Pve8uQl-dU_7sw.png" /></figure><h4>三、利用enumerated()找到對應的index</h4><p>這時就可以利用enumerated()來幫我們找到，如下圖</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eZXi1GoxSpIFlw8UXi0H3Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GitUwrRCzV98WVBq2P-suQ.png" /></figure><p>只要把specificDateInAccounts[row]參數丟進findIndexInAccounts，在條件判斷accountsIndex是否相等，如果true就會回傳index生成accountIndex，再讓self.accounts[accountIndex] = account 就可以順利更改＆刪除資料了，這也是為什麼我要幫每一筆資料都新增accountsIndex（用UUID()）這樣才有辦法找到對應的資料做修改＆刪除！</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*caNbNfIZSfsdKGyEBT2Eeg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/296/1*lJZRYUPrMJ11PIks0q35xw.gif" /></figure><p>太棒了！成功🎉👍</p><p>這篇就介紹到這邊，下篇開始會介紹『歷史紀錄頁面、客制pickerView選擇、searchBar關鍵字搜尋』</p><p><a href="https://medium.com/@a49980060/17-9-%E5%AE%A2%E8%A3%BD%E5%8C%96-%E4%BE%86%E5%90%83%E6%B3%A2%E5%A5%87-%E5%B0%88%E7%94%A8%E8%A8%98%E5%B8%B3app-%E8%87%AA%E8%A3%BDpickerview%E5%B9%B4%E6%9C%88%E4%BB%BD%E9%81%B8%E6%93%87-serchbar%E6%90%9C%E5%B0%8B%E9%97%9C%E9%8D%B5%E5%AD%97%E5%B8%B3%E5%8B%99-4b5b0b703f68">#17–9-客製化『來吃波奇』專用記帳APP，自製pickerView年月份選擇、serchBar搜尋關鍵字帳務</a></p><p>有興趣的可以下載我的完整專案，以下連結</p><p>GitHub：</p><p><a href="https://github.com/YongShunTu/AccountingAPP">GitHub - YongShunTu/AccountingAPP</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f2bb1157e9b1" width="1" height="1" alt=""><hr><p><a href="https://medium.com/peter-pan-swift-ios-class/17-8-%E5%AE%A2%E8%A3%BD%E5%8C%96-%E4%BE%86%E5%90%83%E6%B3%A2%E5%A5%87-%E5%B0%88%E7%94%A8%E8%A8%98%E5%B8%B3app-prepare%E5%82%B3%E9%81%9E%E4%B8%BB%E9%A0%81%E6%9B%B4%E6%94%B9%E7%9A%84%E8%B3%87%E6%96%99-%E8%87%AA%E8%A8%82delegate%E5%9B%9E%E5%82%B3%E6%9B%B4%E6%94%B9%E5%BE%8C%E7%9A%84%E8%B3%87%E6%96%99-%E4%B8%A6%E5%88%A9%E7%94%A8enumerated-%E4%BF%AE%E6%94%B9%E5%B0%8D%E6%87%89%E8%B3%87%E6%96%99index-f2bb1157e9b1">#17–8-客製化『來吃波奇』專用記帳APP，prepare傳遞主頁更改的資料，自訂delegate回傳更改後的資料＆並利用enumerated()修改對應資料index</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[#17–7-客製化『來吃波奇』專用記帳APP，高階函數sorted、filter、reduce應用，讓主頁顯示特定日期帳務，NumberFormatter金額顯示]]></title>
            <link>https://medium.com/peter-pan-swift-ios-class/17-7-%E5%AE%A2%E8%A3%BD%E5%8C%96-%E4%BE%86%E5%90%83%E6%B3%A2%E5%A5%87-%E5%B0%88%E7%94%A8%E8%A8%98%E5%B8%B3app-%E9%AB%98%E9%9A%8E%E5%87%BD%E6%95%B8sorted-filter-reduce%E6%87%89%E7%94%A8-%E8%AE%93%E4%B8%BB%E9%A0%81%E9%A1%AF%E7%A4%BA%E7%89%B9%E5%AE%9A%E6%97%A5%E6%9C%9F%E5%B8%B3%E5%8B%99-numberformatter%E9%87%91%E9%A1%8D%E9%A1%AF%E7%A4%BA-7deb5f4fe70d?source=rss-f5db7d13265a------2</link>
            <guid isPermaLink="false">https://medium.com/p/7deb5f4fe70d</guid>
            <dc:creator><![CDATA[Yong Shun]]></dc:creator>
            <pubDate>Mon, 28 Mar 2022 04:51:58 GMT</pubDate>
            <atom:updated>2022-03-28T11:55:41.778Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l76c5sjgW147TUdolDsi7g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Sdqk8qhxyP9DM5xliAMUJg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5tAzZQDNrOuOVubMWXd97A.png" /></figure><h4>功能介紹：</h4><ol><li>利用sorted排列Accounts的date由大到小</li><li>利用filter判斷符合特定條件並回傳新的specificDateInAccounts顯示在tableView</li><li>利用reduce計算Account的money總金額</li><li>利用NumberFormatter讓金額顯示更漂亮</li></ol><h4>上一篇：</h4><p><a href="https://medium.com/@a49980060/17-6-%E5%AE%A2%E8%A3%BD%E5%8C%96-%E4%BE%86%E5%90%83%E6%B3%A2%E5%A5%87-%E5%B0%88%E7%94%A8%E8%A8%98%E5%B8%B3app-keyboardnotification%E7%9F%A5%E9%81%93%E9%8D%B5%E7%9B%A4%E9%AB%98%E5%BA%A6-%E8%AA%BF%E6%95%B4view%E7%9A%84y%E8%BB%B8%E8%AE%93%E6%95%B4%E5%80%8B%E7%95%AB%E9%9D%A2%E5%BE%80%E4%B8%8A%E7%A7%BB%E5%8B%95-be760453805">#17–6-客製化『來吃波奇』專用記帳APP，keyboardNotification知道鍵盤高度，調整view的y軸讓整個畫面往上移動</a></p><h4>一、利用sorted排序Accounts（由大到小＆由小到大）</h4><p>在新增帳務頁面全部完成後，再來就是要把新增的帳務顯示在我的主頁上，因為新增的帳務都是建立到Accounts除了常用＆轉帳＆提款不是（轉帳手續費、提款手續費例外），並且會是一個[Accounts]，每增加一筆資料都會是在（Accounts[0]）產生，但我想要讓他的順序是按照日期排序，在之後切換歷史紀錄頁面時候，能夠照日期大到小的順序顯示。</p><p>這時候就可以利用到高階函數sorted來實現</p><pre><strong><em>func sorted(by areInIncreasingOrder: (Element, Element) throws -&gt; Bool) rethrows -&gt; [Element]</em></strong></pre><pre>func updateAccountsSequence() { // 建立func來執行</pre><pre>  self.accounts = accounts.sorted { lhs, rhs in // lhs最左邊的資料 rhs最右邊資料</pre><pre>     let lhsTime = lhs.date // 生成最左邊資料的date</pre><pre>     let rhsTime = rhs.date // 生成最右邊資料的date</pre><pre>     return lhsTime &gt; rhsTime // 最左邊資料date＞最右邊資料date 由大到小排序 （如果想要小到大改成lhsTime ＜ rhsTime即可）</pre><pre>  }</pre><pre>}</pre><p>先照2022/3/26、2022/3/24、2022/3/28、2022/3/25這順序新增帳務並且print看看沒有排序的</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TfYIZTBPbXBppBcoIKM-Kg.png" /></figure><p>再來使用 func updateAccountsSequence() 來幫我排序後，print看看排序好的</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iIuQIe3RO2ZQ_BK1xwHY0Q.png" /></figure><p>恩～沒有問題！有按照我想的日期由大到小排序。</p><h4><strong>二、利用filter生成符合特定條件的Accounts（specificDateInAccounts），並顯示在tableView上</strong></h4><p>再來我的主頁上面有放一個datePicker來選擇日期，但要怎麼在選擇日期時顯示特定日期的Accounts是一個問題！</p><p>我的accounts有使用到didSet （Accounts.saveAccount(accounts)），在每次accounts有改變時就會儲存到資料夾，所以不能使用accounts去顯示tableView，因為就算成功抓取特定日期，同時也改變了accounts，再去執行（Accounts.saveAccount(accounts)），就會把其他日期的accounts資料刪除，所以這邊利用新生成的specificDateInAccounts來顯示，就不會影響到原資料。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GU2zUUi6UvqkYl39hZb9vA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/858/1*1adEJAvVE2Wyc1H_16Q-uw.png" /></figure><p>再來就可以使用filter來幫我生成特定條件的specificDateInAccounts，這邊先拉好UIDatePicker的@IBAction func selectDate之後，在每次選擇日期時就會執行一次<strong>specificDateInAccounts = fetchSpecificDateInAccounts(self.accounts, sender.date)</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*99yuINl3PN0oTyagztxWrQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q8aOQharZ_1g6VXsA406Rw.png" /></figure><p><strong>func fetchSpecificDateInAccounts(_ accounts: [Accounts], _ date: Date) -&gt; [Accounts] 這邊我要傳入兩個資料分別 self.accounts(所有[Accounts]資料)、sender.date(點選UIDatePicker的日期)，再來就看filter可以幫我做什麼事情</strong></p><pre>func filter(_ isIncluded: (Element) throws -&gt; Bool) rethrows -&gt; [Element]</pre><pre>(Element) throws -&gt; Bool // 傳入個別元素並判斷是否符合true或false<br>rethrows -&gt; [Element] // true的話會回傳元素的array</pre><p>以我的來看我傳入的self.accounts裡面有4筆資料</p><pre>let newArray = accounts.filter { account in <strong>// accounts每次丟入一筆資料總共4筆，所以會跑4次</strong></pre><pre>let dateForMatter = DateFormatter() <strong>// 生成dateForMatter</strong></pre><pre>dateForMatter.dateFormat = &quot;yyyy/MM/dd&quot; <strong>// 顯示日期的樣式</strong></pre><pre>let day = dateForMatter.string(from: account.date) <strong>// 生成account裡面的date轉成string</strong></pre><pre>let today = dateForMatter.string(from: date) <strong>// 生成UIDatePicker選擇的date轉乘string</strong></pre><pre>if day == today { <strong>//</strong> <strong>判斷如果day跟today兩個string相等就回傳true 如果沒回傳false</strong></pre><pre>return true <strong>// true的話就回傳次筆資料到newArray</strong></pre><pre>}else{</pre><pre>return false <strong>// false的話就不執行</strong></pre><pre>}</pre><pre>}</pre><pre>return newArray // <strong>回傳資料給specificDateInAccounts</strong></pre><p>簡單來說我今天如果UIDatePicker是選擇2022/03/26，filter就會幫我把所有的accounts每一筆資料丟進去，判斷accounts裡的date是否跟UIDatePicker的date是否一樣，一樣的話就把資料抓出來。</p><p>來print看看每次點選UIDatePicker時候specificDateInAccounts的資料是如何</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0VGEMWpxU1qX_BPG4cbH4Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J6SJWqYPaL2zbKIq5y9RxA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UTE6kLGXTlABHnAOXkPRgg.png" /></figure><p>太好了～沒有問題！再來就是把specificDateInAccounts的資料顯示在tableView就好了，來看看實際頁面操作如何😀</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/296/1*VI6OUAgEEEN3ol7oEwCkSQ.gif" /></figure><p>完成！！👍</p><h4>三、利用reduce計算總金額</h4><p>記帳當然也要有總共收入金額＆總共支出金額囉～這樣方便知道本月份的收入支出如何！這邊建立<strong>func calculateThisMonthMoney(_ expenditureOrIncome: ExpenditureOrIncome, date: Date) -&gt; Double 來回傳計算出的金額</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7hiCniwnpKpack_lwnrSGg.png" /></figure><p>這邊一樣先用filter幫我生成特定條件資料newArray，差別在於dateFormat = “yyyy/mm”因為我是要抓整個月份的資料，跟expenditureOrIncome: ExpenditureOrIncome來判斷是要抓取支出還是收入，接著來看reduce要如何幫我計算</p><pre>func reduce&lt;Result&gt;(_ initialResult: Result, _ nextPartialResult: (Result, Element) throws -&gt; Result) rethrows -&gt; Result</pre><pre>initialResult: Result <strong>// 設定初始金額</strong></pre><pre>nextPartialResult: (Result, Element) throws -&gt; Result <strong>// Result金額＋Element傳入的元素金額＝throws -&gt; Result回傳新金額給Rseult</strong></pre><pre>rethrows -&gt; Result <strong>// 回傳總金額</strong></pre><p>以我的來看，設定初始金額0.0，我的newArray資料裡面有我剛剛新增4筆資料，個別金額100,200,300,400，在reduce裡面就會跑4次</p><pre><strong>let</strong> total = newArray.reduce(0.0) { partialResult, account <strong>in</strong></pre><pre><strong>return</strong> partialResult + account.money</pre><pre>}</pre><pre><strong>return</strong> total</pre><p>第一次return 0.0 + 100 回傳 100</p><p>第二次return 100 + 200 回傳 300</p><p>第三次return 300 + 300 回傳 600</p><p>第四次return 600 + 400 回傳1000</p><p>最後四次跑完回傳最後結果是1000，total這時金額就是1000了</p><p>再來我就可以把計算出的金額回傳存在我預設金額是0的變數，顯示在主頁上。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/572/1*18aMQfGpogliOoFGsCIllA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_EtWUnH10vu_APpY9HdbJA.png" /></figure><h4>四、NumberFormatter顯示金額格式</h4><p>在顯示金額上面我想要有$字號跟千分符，這時候就需要使用到NumberFormatter，其實沒有太大困難，很簡單可以理解。這邊我是建立一個空白Swift.Files去寫，這樣之後我只要有顯示金額的就可以快速使用。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1014/1*hpyPAqmcPiV8nYTwJjl3sg.png" /></figure><pre><strong>class</strong> NumberStyle {</pre><pre><strong>static</strong> <strong>func</strong> currencyStyle() -&gt; NumberFormatter {</pre><pre><strong>let</strong> numberFormatter = NumberFormatter() // 生成numberFormatter</pre><pre>numberFormatter.locale = Locale(identifier: &quot;Zh_TW&quot;) // 設定地區</pre><pre>numberFormatter.numberStyle = .currency // 樣式</pre><pre>numberFormatter.maximumFractionDigits = 0 // 小數點後0位</pre><pre><strong>return</strong> numberFormatter</pre><pre>}</pre><p>其實一般是不用設定地區，會依據手機使用者的設定，台灣使用一般就是新台幣的樣式了。</p><p>最後需要把樣式轉換成String</p><pre>string(from number: NSNumber) -&gt; String?</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U6Dpnm2vaJbcKNznWiDo-w.png" /></figure><p>傳入的from number是NSNumber，只需NSNumber(value: income)轉換即可，來看看最後顯示的樣式😀</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*bqxpdzTMB3Rx6ofkAzBs_Q.png" /></figure><p>OK~完美完成！</p><p>這篇就介紹到這邊，下一篇開始介紹『編輯頁面』</p><p><a href="https://medium.com/@a49980060/17-8-%E5%AE%A2%E8%A3%BD%E5%8C%96-%E4%BE%86%E5%90%83%E6%B3%A2%E5%A5%87-%E5%B0%88%E7%94%A8%E8%A8%98%E5%B8%B3app-prepare%E5%82%B3%E9%81%9E%E4%B8%BB%E9%A0%81%E6%9B%B4%E6%94%B9%E7%9A%84%E8%B3%87%E6%96%99-%E8%87%AA%E8%A8%82delegate%E5%9B%9E%E5%82%B3%E6%9B%B4%E6%94%B9%E5%BE%8C%E7%9A%84%E8%B3%87%E6%96%99-%E4%B8%A6%E5%88%A9%E7%94%A8enumerated-%E4%BF%AE%E6%94%B9%E5%B0%8D%E6%87%89%E8%B3%87%E6%96%99index-f2bb1157e9b1">#17–8-客製化『來吃波奇』專用記帳APP，prepare傳遞主頁更改的資料，自訂delegate回傳更改後的資料＆並利用enumerated()修改對應資料index</a></p><p>有興趣的可以下載我的完整專案，以下連結</p><p>GitHub：</p><p><a href="https://github.com/YongShunTu/AccountingAPP">GitHub - YongShunTu/AccountingAPP</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7deb5f4fe70d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/peter-pan-swift-ios-class/17-7-%E5%AE%A2%E8%A3%BD%E5%8C%96-%E4%BE%86%E5%90%83%E6%B3%A2%E5%A5%87-%E5%B0%88%E7%94%A8%E8%A8%98%E5%B8%B3app-%E9%AB%98%E9%9A%8E%E5%87%BD%E6%95%B8sorted-filter-reduce%E6%87%89%E7%94%A8-%E8%AE%93%E4%B8%BB%E9%A0%81%E9%A1%AF%E7%A4%BA%E7%89%B9%E5%AE%9A%E6%97%A5%E6%9C%9F%E5%B8%B3%E5%8B%99-numberformatter%E9%87%91%E9%A1%8D%E9%A1%AF%E7%A4%BA-7deb5f4fe70d">#17–7-客製化『來吃波奇』專用記帳APP，高階函數sorted、filter、reduce應用，讓主頁顯示特定日期帳務，NumberFormatter金額顯示</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[#17–6-客製化『來吃波奇』專用記帳APP，keyboardNotification知道鍵盤高度，調整view的y軸讓整個畫面往上移動]]></title>
            <link>https://medium.com/peter-pan-swift-ios-class/17-6-%E5%AE%A2%E8%A3%BD%E5%8C%96-%E4%BE%86%E5%90%83%E6%B3%A2%E5%A5%87-%E5%B0%88%E7%94%A8%E8%A8%98%E5%B8%B3app-keyboardnotification%E7%9F%A5%E9%81%93%E9%8D%B5%E7%9B%A4%E9%AB%98%E5%BA%A6-%E8%AA%BF%E6%95%B4view%E7%9A%84y%E8%BB%B8%E8%AE%93%E6%95%B4%E5%80%8B%E7%95%AB%E9%9D%A2%E5%BE%80%E4%B8%8A%E7%A7%BB%E5%8B%95-be760453805?source=rss-f5db7d13265a------2</link>
            <guid isPermaLink="false">https://medium.com/p/be760453805</guid>
            <dc:creator><![CDATA[Yong Shun]]></dc:creator>
            <pubDate>Mon, 28 Mar 2022 04:36:19 GMT</pubDate>
            <atom:updated>2022-03-28T07:14:23.654Z</atom:updated>
            <content:encoded><![CDATA[<p>這篇主要在補充再畫面textView輸入文字時候，keyboard會擋住畫面，這樣根本不知道自己到底有沒有打錯字，那真的是非常的麻煩🙁，所以這個問題是一定要解決的囉！</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AmOKrIX8Ohk0YfmUa6Gvfg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pXGmEfb9I6c5p8F2AOZi0Q.png" /></figure><h4>功能介紹：</h4><ol><li>利用UIResponder.keyboardWillShowNotification鍵盤將出現時接收通知</li><li>利用UIResponder.keyboardWillHideNotification鍵盤將消失時時接收通知</li><li>利用UIResponder.keyboardFrameEndUserInfoKey找到鍵盤size.heigh高度</li><li>利用UIViewPropertyAnimator.runningPropertyAnimator動畫效果，讓畫面更順暢</li></ol><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/17-5-%E5%AE%A2%E8%A3%BD%E5%8C%96-%E4%BE%86%E5%90%83%E6%B3%A2%E5%A5%87-%E5%B0%88%E7%94%A8%E8%A8%98%E5%B8%B3app-%E6%96%B0%E5%A2%9E-%E8%BD%89%E5%B8%B3-%E6%8F%90%E6%AC%BE-%E9%A0%81%E9%9D%A2-keyboard-uitoolbar-uibarbuttonitem-done%E9%8D%B5-uitapgesturerecognizer%E6%89%8B%E5%8B%A2-a61e6bafd8ed">#17–5-客製化『來吃波奇』專用記帳APP，新增『轉帳、提款』頁面，Keyboard(UIToolbar＆UIBarButtonItem)Done鍵，UITapGestureRecognizer手勢…</a></p><h4>一、UIResponder.keyboardWillShowNotification鍵盤將出現時執行keyboardWasShown讓view往上移動</h4><p>如果沒有讓畫面整個上移的話就會整個卡住textView，真的就不知道自己在打什麼內容🙁會像下面這樣</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/296/1*e_DRNxmgm2NUE98MSWzzBA.gif" /></figure><p>這時候就要使用到UIResponder.keyboardWillShowNotification來接收通知，這樣就可以知道keyboayd的高度如何</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DYqzUuVfKeCnl06yoJHruw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*se7nu3VzejLZJ23kYC9UWQ.png" /></figure><pre>guard let info = notification.userInfo,</pre><pre>let keyboardFrameValue = info[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue else { return } <strong>// 抓取keyboardFrameEndUserInfoKey並轉型NSValue</strong></pre><pre>let keyboardFrame = keyboardFrameValue.cgRectValue <strong>// 生成keyboard的frame</strong></pre><pre>let keyboardSize = keyboardFrame.size <strong>// 生成keyboard的size</strong></pre><p>這時就可以呼叫keyboardSize.heigh知道keyboard的高度是多少了，但是知道高度後要怎麼移動View讓textView的底部剛好切平keyboard呢？這邊我的解法是，整個view的高度（−減掉）view的最上部～textView最底部，keyboard的高度再去扣掉兩個相減的數值，就是view要上移的數值，用以下圖片來解說可能比較好理解。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nP7FB2LHdP5vAiI0S7JueA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PsD6Lerbm060mHzDRfb3GA.png" /></figure><p>從圖片可以清楚知道鍵盤的高度（−減掉）相減後剩下的數值，就是我們view要往上移動的數值，寫法如下</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Aa1N1WN2uqqYu_SREw-Idg.png" /></figure><p>裡面要再多判斷noteTextView.isFirstResponder（true）時view.bounds.origin.y = contentInsets才往上移動，（false）時view.bounds.origin.y = 0（回復原本位子），這邊我有在多加UIViewPropertyAnimator.runningPropertyAnimator(withDuration: 0.3, delay: 0)，時間0.3秒、重複0次，這樣看起來會比較順暢。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/296/1*fFZItwHzivRXg5Kk3Z9OaA.gif" /></figure><p>Ya~看起來還不錯👍！</p><h4><strong>二、UIResponder.keyboardWillShowNotification鍵盤將消失時執行</strong>keyboardWillBeHidden<strong>讓view回復原來的位子</strong></h4><p>這邊就是簡單的keyboard在收回Done的時候，讓view.bounds.origin.y = 0即可</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wFeSxk4FUrK2caSlzl7-Yw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/296/1*byIMwiCwJRkgWNS_9Jpf-A.gif" /></figure><p>下篇開始會介紹主頁『顯示特定日期的帳務、高階函式應用』</p><p><a href="https://medium.com/@a49980060/17-7-%E5%AE%A2%E8%A3%BD%E5%8C%96-%E4%BE%86%E5%90%83%E6%B3%A2%E5%A5%87-%E5%B0%88%E7%94%A8%E8%A8%98%E5%B8%B3app-%E9%AB%98%E9%9A%8E%E5%87%BD%E6%95%B8sorted-filter-reduce%E6%87%89%E7%94%A8-%E8%AE%93%E4%B8%BB%E9%A0%81%E9%A1%AF%E7%A4%BA%E7%89%B9%E5%AE%9A%E6%97%A5%E6%9C%9F%E5%B8%B3%E5%8B%99-numberformatter%E9%87%91%E9%A1%8D%E9%A1%AF%E7%A4%BA-7deb5f4fe70d">#17–7-客製化『來吃波奇』專用記帳APP，高階函數sorted、filter、reduce應用，讓主頁顯示特定日期帳務，NumberFormatter金額顯示</a></p><p>有興趣的可以下載我的完整專案，以下連結</p><p>GitHub：</p><p><a href="https://github.com/YongShunTu/AccountingAPP">GitHub - YongShunTu/AccountingAPP</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=be760453805" width="1" height="1" alt=""><hr><p><a href="https://medium.com/peter-pan-swift-ios-class/17-6-%E5%AE%A2%E8%A3%BD%E5%8C%96-%E4%BE%86%E5%90%83%E6%B3%A2%E5%A5%87-%E5%B0%88%E7%94%A8%E8%A8%98%E5%B8%B3app-keyboardnotification%E7%9F%A5%E9%81%93%E9%8D%B5%E7%9B%A4%E9%AB%98%E5%BA%A6-%E8%AA%BF%E6%95%B4view%E7%9A%84y%E8%BB%B8%E8%AE%93%E6%95%B4%E5%80%8B%E7%95%AB%E9%9D%A2%E5%BE%80%E4%B8%8A%E7%A7%BB%E5%8B%95-be760453805">#17–6-客製化『來吃波奇』專用記帳APP，keyboardNotification知道鍵盤高度，調整view的y軸讓整個畫面往上移動</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[#17–5-客製化『來吃波奇』專用記帳APP，新增『轉帳、提款』頁面，Keyboard(UIToolbar＆UIBarButtonItem)Done鍵，UITapGestureRecognizer手勢…]]></title>
            <link>https://medium.com/peter-pan-swift-ios-class/17-5-%E5%AE%A2%E8%A3%BD%E5%8C%96-%E4%BE%86%E5%90%83%E6%B3%A2%E5%A5%87-%E5%B0%88%E7%94%A8%E8%A8%98%E5%B8%B3app-%E6%96%B0%E5%A2%9E-%E8%BD%89%E5%B8%B3-%E6%8F%90%E6%AC%BE-%E9%A0%81%E9%9D%A2-keyboard-uitoolbar-uibarbuttonitem-done%E9%8D%B5-uitapgesturerecognizer%E6%89%8B%E5%8B%A2-a61e6bafd8ed?source=rss-f5db7d13265a------2</link>
            <guid isPermaLink="false">https://medium.com/p/a61e6bafd8ed</guid>
            <dc:creator><![CDATA[Yong Shun]]></dc:creator>
            <pubDate>Fri, 25 Mar 2022 17:23:47 GMT</pubDate>
            <atom:updated>2022-03-28T04:38:24.702Z</atom:updated>
            <content:encoded><![CDATA[<h3>#17–5-客製化『來吃波奇』專用記帳APP，新增『轉帳、提款』頁面，Keyboard(UIToolbar＆UIBarButtonItem)Done鍵，UITapGestureRecognizer手勢偵測</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_05oqpG-5t-77sxtrd2UyA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bY89dH0SHMaL5Crqq-Jn1Q.png" /></figure><h4>功能介紹：</h4><ol><li>新增Models『BankAccounts、WithdrawalBanks』個別儲存</li><li>自訂Delegate傳遞資料（轉帳、轉帳手續費）（提款、提款手續費）</li><li>新增之後所有頁面共用的Keyboard(UIToolbar、UIBarButtonItem)Done鍵</li><li>UITapGestureRecognizer手勢偵測，點擊空白處收鍵盤</li></ol><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/17-4-%E5%AE%A2%E8%A3%BD%E5%8C%96-%E4%BE%86%E5%90%83%E6%B3%A2%E5%A5%87-%E5%B0%88%E7%94%A8%E8%A8%98%E5%B8%B3app-%E5%88%A9%E7%94%A8notification%E5%82%B3%E9%81%9E%E8%B3%87%E6%96%99%E6%96%B0%E5%A2%9E%E5%B8%B8%E7%94%A8%E5%8A%9F%E8%83%BD-%E7%B7%A8%E8%BC%AF%E5%88%AA%E9%99%A4%E5%B8%B8%E7%94%A8-86157d1f3b30">#17–4-客製化『來吃波奇』專用記帳APP，利用Notification傳遞資料新增常用功能＆編輯刪除常用</a></p><h4><strong>一、新增轉帳＆提款Models</strong></h4><p>跟前面一樣，因為轉帳以及提款的內容跟其他的都不同，所以一樣個別建立Models來儲存資料，並之前的Models Accounts以及現在的轉帳＆提款有新增型別Index: String用UUID()去儲存，主要是因為之後再更改資料＆刪除資料，可以非常精確的抓取。</p><p><strong>UUID()可以參考第三篇文章：三、獨一無二的照片命名UUID()</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/17-3-%E5%AE%A2%E8%A3%BD%E5%8C%96-%E4%BE%86%E5%90%83%E6%B3%A2%E5%A5%87-%E5%B0%88%E7%94%A8%E8%A8%98%E5%B8%B3app-%E4%B8%B2%E9%80%A3google-maps-%E7%9A%84-places-api%E9%A1%AF%E7%A4%BA%E5%BA%97%E5%AE%B6%E5%90%8D%E7%A8%B1-%E5%9C%B0%E5%9D%80-%E5%9C%96%E7%89%87%E6%8B%8D%E7%85%A7-%E5%9C%96%E7%89%87%E5%BA%AB%E9%81%B8%E6%93%87-%E5%82%B3%E9%81%9E%E8%B3%87%E6%96%99%E5%88%B0%E4%B8%BB%E7%95%AB%E9%9D%A2%E5%91%88%E7%8F%BE-72ed4c3de669">#17–3-客製化『來吃波奇』專用記帳APP，串連Google Maps 的 Places API顯示店家名稱＆地址、圖片拍照＆圖片庫選擇、傳遞資料到主畫面呈現</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fyMgfKZVUf3r3ODZXO3gwA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_F_F-DBSz5JvCU9hUJdokg.png" /></figure><h4>二、自訂Delegate傳遞資料</h4><p>這邊的轉帳＆提款主要是影響帳戶頁面，跟主頁比較沒關係，有差別的就是轉帳＆提款時可能會產生手續費的問題，因手續費也算是支出所以如果有手續費那我也必須新增在主頁面。</p><p>方法跟第三篇一樣：四、自訂delegate利用static存取，並傳遞到主畫面呈現</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/17-3-%E5%AE%A2%E8%A3%BD%E5%8C%96-%E4%BE%86%E5%90%83%E6%B3%A2%E5%A5%87-%E5%B0%88%E7%94%A8%E8%A8%98%E5%B8%B3app-%E4%B8%B2%E9%80%A3google-maps-%E7%9A%84-places-api%E9%A1%AF%E7%A4%BA%E5%BA%97%E5%AE%B6%E5%90%8D%E7%A8%B1-%E5%9C%B0%E5%9D%80-%E5%9C%96%E7%89%87%E6%8B%8D%E7%85%A7-%E5%9C%96%E7%89%87%E5%BA%AB%E9%81%B8%E6%93%87-%E5%82%B3%E9%81%9E%E8%B3%87%E6%96%99%E5%88%B0%E4%B8%BB%E7%95%AB%E9%9D%A2%E5%91%88%E7%8F%BE-72ed4c3de669">#17–3-客製化『來吃波奇』專用記帳APP，串連Google Maps 的 Places API顯示店家名稱＆地址、圖片拍照＆圖片庫選擇、傳遞資料到主畫面呈現</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oozypMObD4amEyABNuCHTA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DHHcLM8EtiIFxuiYPpe58Q.png" /></figure><p>新增的Accounts因為手續費是固定，所以在category: “雜費”、subtype: “轉帳手續費”直接打上即可（一樣的提款新增的Accounts是category: “雜費”、subtype: “提款手續費”）</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FB8NlvkNXIPnwH7sGLy7Hg.png" /></figure><p>再來MainViewController新增資料時候，要在多一個條件判斷，if handlingFee != 0.0 （如果手續費不是0的話）就要新增accounts在tableView顯示手續費，至於withdrawalBanks、bankAccounts雖然沒有要在MainViewController顯示，但我這邊一樣會先在mainViewController把資料先儲存，這樣之後再帳戶頁面就可以直接讀取。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/1*43qDTxY4OBwoSfKYnYcfKw.png" /></figure><p>讓我們來看看實際主頁面如何🧐</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/296/1*KqPjUbDaBzRnwkicXN_iDQ.gif" /></figure><p>恩～沒有問題🎉</p><h4>三、新增Keyboard的Done鍵、UITapGestureRecognizer點擊空白處收鍵盤</h4><p>因為我所有的頁面很多都是可以點擊的，所以我覺得讓每個鍵盤都有個Done鍵會比較方便，這邊是直接新增一個空白Swift File用extenion新增，這樣之後所有viewController都可以直接呼叫。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yKRNMwPa6ntLX0ZJeFPV3A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/856/1*wj_GFkTijt1vVKUXyLf2xQ.png" /></figure><pre><strong>func</strong> addKeyboardReturn() {</pre><pre><strong>let</strong> weigh = Float(UIScreen.main.bounds.width) // 寬度=main的寬</pre><pre><strong>let</strong> accessoryView = UIToolbar(frame: CGRect(x: 0, y: 0, width: CGFloat(weigh), height: CGFloat(0.1 * weigh))) // 顯示的位子跟寬高</pre><pre><strong>let</strong> space = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: <strong>nil</strong>, action: <strong>nil</strong>) // 空白按鈕</pre><pre><strong>let</strong> done = UIBarButtonItem(barButtonSystemItem: .done, target: <strong>self</strong>, action: <strong>#selector</strong>(doneButton)) // Done按鈕 #selector執行func doneButton</pre><pre>accessoryView.items = [space,space,done] // 可以照自己喜歡排列</pre><pre><strong>self</strong>.inputAccessoryView = accessoryView</pre><pre>}</pre><pre><strong>@objc</strong> <strong>func</strong> doneButton() {</pre><pre><strong>self</strong>.resignFirstResponder() // 點擊Done鈕時收鍵盤</pre><pre>}</pre><p>而UITapGestureRecognizer我是用程式加入</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aYdrbGSd7jzXjVBIh11cng.png" /></figure><pre><strong>func</strong> addTapGesture(){</pre><pre><strong>let</strong> tap = UITapGestureRecognizer(target: <strong>self</strong>, action: <strong>#selector</strong>(hideKeyboard)) // 生成UITapGestureRecognizer #selector執行func hideKeyboard</pre><pre>tap.cancelsTouchesInView = <strong>false // 點選其他button事件可以收鍵盤＆點選cell不會無法執行動作</strong></pre><pre>view.addGestureRecognizer(tap)</pre><pre>}</pre><pre><strong>@objc</strong> <strong>private</strong> <strong>func</strong> hideKeyboard(){</pre><pre><strong>self</strong>.view.endEditing(<strong>true</strong>) // 收鍵盤</pre><pre>}</pre><p>也可直接Storyboard加入，在拉@IBAction執行view.endEditing(ture)即可</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/516/1*8h-Krbu_6kPJoUF0tGztkg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AVY3IWIdYPmSktdbhFD1ig.png" /></figure><p>來看看實際操作頁面</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/296/1*3-VzwyQwO2561MrsZRMS9Q.gif" /></figure><p>OK~沒有問題👍</p><p>下篇開始多補充『keyboardNotification知道鍵盤高度，調整view的y軸讓整個畫面往上移動』</p><p><a href="https://medium.com/@a49980060/17-6-%E5%AE%A2%E8%A3%BD%E5%8C%96-%E4%BE%86%E5%90%83%E6%B3%A2%E5%A5%87-%E5%B0%88%E7%94%A8%E8%A8%98%E5%B8%B3app-keyboardnotification%E7%9F%A5%E9%81%93%E9%8D%B5%E7%9B%A4%E9%AB%98%E5%BA%A6-%E8%AA%BF%E6%95%B4view%E7%9A%84y%E8%BB%B8%E8%AE%93%E6%95%B4%E5%80%8B%E7%95%AB%E9%9D%A2%E5%BE%80%E4%B8%8A%E7%A7%BB%E5%8B%95-be760453805">#17–6-客製化『來吃波奇』專用記帳APP，keyboardNotification知道鍵盤高度，調整view的y軸讓整個畫面往上移動</a></p><p>有興趣的可以下載我的完整專案，以下連結</p><p>GitHub：</p><p><a href="https://github.com/YongShunTu/AccountingAPP">GitHub - YongShunTu/AccountingAPP</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a61e6bafd8ed" width="1" height="1" alt=""><hr><p><a href="https://medium.com/peter-pan-swift-ios-class/17-5-%E5%AE%A2%E8%A3%BD%E5%8C%96-%E4%BE%86%E5%90%83%E6%B3%A2%E5%A5%87-%E5%B0%88%E7%94%A8%E8%A8%98%E5%B8%B3app-%E6%96%B0%E5%A2%9E-%E8%BD%89%E5%B8%B3-%E6%8F%90%E6%AC%BE-%E9%A0%81%E9%9D%A2-keyboard-uitoolbar-uibarbuttonitem-done%E9%8D%B5-uitapgesturerecognizer%E6%89%8B%E5%8B%A2-a61e6bafd8ed">#17–5-客製化『來吃波奇』專用記帳APP，新增『轉帳、提款』頁面，Keyboard(UIToolbar＆UIBarButtonItem)Done鍵，UITapGestureRecognizer手勢…</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[#17–4-客製化『來吃波奇』專用記帳APP，利用Notification傳遞資料新增常用功能＆編輯刪除常用]]></title>
            <link>https://medium.com/peter-pan-swift-ios-class/17-4-%E5%AE%A2%E8%A3%BD%E5%8C%96-%E4%BE%86%E5%90%83%E6%B3%A2%E5%A5%87-%E5%B0%88%E7%94%A8%E8%A8%98%E5%B8%B3app-%E5%88%A9%E7%94%A8notification%E5%82%B3%E9%81%9E%E8%B3%87%E6%96%99%E6%96%B0%E5%A2%9E%E5%B8%B8%E7%94%A8%E5%8A%9F%E8%83%BD-%E7%B7%A8%E8%BC%AF%E5%88%AA%E9%99%A4%E5%B8%B8%E7%94%A8-86157d1f3b30?source=rss-f5db7d13265a------2</link>
            <guid isPermaLink="false">https://medium.com/p/86157d1f3b30</guid>
            <dc:creator><![CDATA[Yong Shun]]></dc:creator>
            <pubDate>Wed, 23 Mar 2022 07:18:19 GMT</pubDate>
            <atom:updated>2022-03-25T17:24:36.332Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HozYqNH-9Aacs10W79A_tA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z1Vz-a5SIgPMpEDA9xCbxA.png" /></figure><h4>功能介紹：</h4><ol><li>新增models『FrequentlyUsedIncome、FrequentlyUsedExpenditure』個別儲存</li><li>Notification傳遞資料新增常用</li><li>點選常用頁面cell跳回對應的收入＆支出</li></ol><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/17-3-%E5%AE%A2%E8%A3%BD%E5%8C%96-%E4%BE%86%E5%90%83%E6%B3%A2%E5%A5%87-%E5%B0%88%E7%94%A8%E8%A8%98%E5%B8%B3app-%E4%B8%B2%E9%80%A3google-maps-%E7%9A%84-places-api%E9%A1%AF%E7%A4%BA%E5%BA%97%E5%AE%B6%E5%90%8D%E7%A8%B1-%E5%9C%B0%E5%9D%80-%E5%9C%96%E7%89%87%E6%8B%8D%E7%85%A7-%E5%9C%96%E7%89%87%E5%BA%AB%E9%81%B8%E6%93%87-%E5%82%B3%E9%81%9E%E8%B3%87%E6%96%99%E5%88%B0%E4%B8%BB%E7%95%AB%E9%9D%A2%E5%91%88%E7%8F%BE-72ed4c3de669">#17–3-客製化『來吃波奇』專用記帳APP，串連Google Maps 的 Places API顯示店家名稱＆地址、圖片拍照＆圖片庫選擇、傳遞資料到主畫面呈現</a></p><h4>一、新增常用支出＆收入models</h4><p>我的帳務是用Accounts去儲存資料，跟常用的資料是不一樣的，所以我覺得應該要區分開來，並且我是用兩個cell去區分為收入＆支出，所以我的常用也就分為兩個『FrequentlyUsedIncome、FrequentlyUsedExpenditure』去儲存資料，會比較直覺單純</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fHTYAl-0GOuh6EIN2kU6uw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gyaSE15xeUYN7Q0r8Pw93w.png" /></figure><p>關於儲存資料的DocumentDirectory可以參考我第二篇的第二點</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/17-2-%E5%AE%A2%E8%A3%BD%E5%8C%96-%E4%BE%86%E5%90%83%E6%B3%A2%E5%A5%87-%E5%B0%88%E7%94%A8%E8%A8%98%E5%B8%B3app-storyboard%E8%A3%BD%E4%BD%9C-%E5%B8%B3%E5%8B%99%E6%94%B6%E5%85%A5-%E6%94%AF%E5%87%BA%E7%9A%84%E9%81%B8%E5%96%AE%E5%8A%9F%E8%83%BD-%E8%B3%87%E6%96%99%E5%84%B2%E5%AD%98documentdirectory-8bbd0cccc26f">#17–2-客製化『來吃波奇』專用記帳APP，Storyboard製作、帳務收入＆支出的選單功能、資料儲存DocumentDirectory</a></p><h4>二、Notification傳遞資料新增常用</h4><p>這邊要利用Notification來實現資料的傳遞，首先需要用<strong>NotificationCenter.default.post(name: &lt;NSNotification.Name&gt;, object: &lt;Any?&gt;, userInfo: &lt;[AnyHashable : Any]?&gt;)</strong>來傳送通知</p><p><strong>name: &lt;NSNotification.Name&gt;</strong> 傳Notification的name</p><p><strong>object: &lt;Any?&gt;</strong> 傳nil就好</p><p><strong>userInfo: &lt;[AnyHashable : Any]?&gt;</strong> “AnyHashable”對應的名稱、“Any”要傳遞的資料</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Qeni_wXD34ETvC8NINGz8Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sLBjglssgB3dGo-DI2OZpA.png" /></figure><p>&lt;NSNotification.Name&gt;我是直接用static，之後Notification在接收通知時候也需要，就可以直接使用不怕打錯🧐（自己很常打錯），至於我的userInfo裡面AnyHashable對應的名稱我是建立一個ExpenditureOrIncome的enum這樣就可以準確的知道傳遞過去對應的名稱是收入＆支出，也才又不會打錯字😏？，之後把addFrequentlyUsedIncome資料帶進去，這樣發送通知的步驟就ＯＫ了。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/598/1*fit7uTX9v_SDVqHTTvn66Q.png" /></figure><p>再來是接收通知 <strong>NotificationCenter.default.addObserver(&lt;observer: Any&gt;, selector: &lt;Selector&gt;, name: &lt;NSNotification.Name?&gt;, object: &lt;Any?&gt;)</strong>，在一開始的FrequentlyUsedViewController的viewDidLoad寫入</p><p><strong>&lt;observer: Any&gt;</strong> self</p><p><strong>selector: &lt;Selector&gt;</strong> 另外寫@objc func來執行</p><p><strong>name:&lt;NSNotification.Name&gt;</strong> Notification的name</p><p><strong>object:&lt;Any?&gt;</strong> 傳nil</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JtYudgqp086dXsqiopA2bw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6SGBI9zZImZ6MuAjxbEkKA.png" /></figure><p>@objc func 裡面要帶Notification參數進去，主要需要讀取前面的Notification.default.post裡面userInfo[對應的名稱]裡面的資料，這邊記得要as?轉型，轉型成功後就可以新增常用資料顯示到tableView上面了。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/296/1*QSjqhPd1lVi21IvQAX4EeA.gif" /></figure><h4>三、編輯刪除常用</h4><p>這邊需要使用<strong>tableView.setEditing(&lt;editing: Bool&gt;, animated: &lt;Bool&gt;)，來實現目前是否是編輯模式。</strong></p><p><strong>&lt;editing: Bool&gt; 傳入tableView.isEditing現在是否正在編輯，前面！是反向的意思，每點選一次Button就會觸發一次，true -&gt; false -&gt; true -&gt; false</strong></p><p><strong>animated: &lt;Bool&gt;) 傳入true要有動畫，false不要有動畫</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IdjNzxQ4egA-6Y4cQdcaWg.png" /></figure><p>呼叫<strong>func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath)</strong>來判斷如果editingStyle == .delete 的話要刪除資料</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eU7Z2eogD1L-Ubq84ppgKg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/296/1*CreA_jz1EEnlthMr9jWTVA.gif" /></figure><h4>四、點選常用Cell跳回對應收入＆支出並更新資料</h4><p>這邊一樣是會需要用到Notification來實作，這邊再點選cell裡面的button時，我利用 <strong>cell.incomeButton.addTarget(&lt;target: Any?&gt;, action: &lt;Selector&gt;, for: &lt;UIControl.Event&gt;)</strong>，來觸發點選button時要做什麼事情</p><p><strong>&lt;target: Any?&gt; </strong>self</p><p><strong>&lt;Selector&gt; </strong>另外寫 @objc func 來執行</p><p><strong>&lt;UIControl.Event&gt; </strong>.touchUpInside 觸碰效果</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gd29xeywRoIvaXyVaXBwlg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oyR7zVnNRPvkN9k5P7ADoA.png" /></figure><p>這邊cell.incomeButton.tag = indexPath.row＆cell.expenditureButton.tag = indexPath.row主要是要判斷目前是點選第幾個，在@objc裡面一樣把選取到的資料post發送通知給AddAccountViewController，收到通知後一樣執行@objc裡面的事情，1.在post一次給對應的收入＆支出更新頁面資料2.畫面移動到對應的頁面</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HC4nWgD0VSRtGYliE70NJQ.png" /></figure><p>最後在對應的viewController Update資料即可更新畫面資料</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y1JDjIGQx37_znp8Mu4ggA.png" /></figure><p>整個畫面的步驟過程</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/808/1*3_fKNdQjcLzgOhJ7Akgk5w.png" /></figure><p>來看一下實際操作頁面如何🧐～</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/296/1*7vI3oT92M45Dk3EqftrL2w.gif" /></figure><p>Yes成功囉🎉！這樣就完成新增常用，並點選常用cell自動跳回對應的頁面囉👍！</p><p>這篇就介紹到這邊～下一篇開始會介紹『轉帳、提款』功能</p><p><a href="https://medium.com/@a49980060/17-5-%E5%AE%A2%E8%A3%BD%E5%8C%96-%E4%BE%86%E5%90%83%E6%B3%A2%E5%A5%87-%E5%B0%88%E7%94%A8%E8%A8%98%E5%B8%B3app-%E6%96%B0%E5%A2%9E-%E8%BD%89%E5%B8%B3-%E6%8F%90%E6%AC%BE-%E9%A0%81%E9%9D%A2-keyboard-uitoolbar-uibarbuttonitem-done%E9%8D%B5-uitapgesturerecognizer%E6%89%8B%E5%8B%A2-a61e6bafd8ed">#17–5-客製化『來吃波奇』專用記帳APP，新增『轉帳、提款』頁面，Keyboard(UIToolbar＆UIBarButtonItem)Done鍵，UITapGestureRecognizer手勢…</a></p><p>有興趣的可以下載我的完整專案，以下連結</p><p>GitHub：</p><p><a href="https://github.com/YongShunTu/AccountingAPP">GitHub - YongShunTu/AccountingAPP</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=86157d1f3b30" width="1" height="1" alt=""><hr><p><a href="https://medium.com/peter-pan-swift-ios-class/17-4-%E5%AE%A2%E8%A3%BD%E5%8C%96-%E4%BE%86%E5%90%83%E6%B3%A2%E5%A5%87-%E5%B0%88%E7%94%A8%E8%A8%98%E5%B8%B3app-%E5%88%A9%E7%94%A8notification%E5%82%B3%E9%81%9E%E8%B3%87%E6%96%99%E6%96%B0%E5%A2%9E%E5%B8%B8%E7%94%A8%E5%8A%9F%E8%83%BD-%E7%B7%A8%E8%BC%AF%E5%88%AA%E9%99%A4%E5%B8%B8%E7%94%A8-86157d1f3b30">#17–4-客製化『來吃波奇』專用記帳APP，利用Notification傳遞資料新增常用功能＆編輯刪除常用</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>