<?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 兔子 on Medium]]></title>
        <description><![CDATA[Stories by 兔子 on Medium]]></description>
        <link>https://medium.com/@tuzaiz?source=rss-34810ec544d3------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*145Gs-xtfEHBLE-b.jpeg</url>
            <title>Stories by 兔子 on Medium</title>
            <link>https://medium.com/@tuzaiz?source=rss-34810ec544d3------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 12:17:04 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@tuzaiz/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[如何整合 Sign in with Apple 到自己的 iOS App 上 (iOS & Backend)]]></title>
            <link>https://medium.com/@tuzaiz/%E5%A6%82%E4%BD%95%E6%95%B4%E5%90%88-sign-in-with-apple-%E5%88%B0%E8%87%AA%E5%B7%B1%E7%9A%84-ios-app-%E4%B8%8A-ios-backend-e64d9de15410?source=rss-34810ec544d3------2</link>
            <guid isPermaLink="false">https://medium.com/p/e64d9de15410</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[apple]]></category>
            <category><![CDATA[sign-in-with-apple]]></category>
            <dc:creator><![CDATA[兔子]]></dc:creator>
            <pubDate>Tue, 10 Dec 2019 12:42:22 GMT</pubDate>
            <atom:updated>2019-12-10T12:42:22.680Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JDqzpuqo8wHt-wRnzSwAmA.png" /></figure><p>根據<a href="https://developer.apple.com/app-store/review/guidelines/#sign-in-with-apple">蘋果的規定</a>，明年四月之後只要你的 App 中有包含<strong>任一第三方登入</strong>就必須支援 Sign in with Apple，要不然就無法通過審核上架。</p><p>因此稍微花了點時間去研究該如何整合 Sign in with Apple 到 iOS App 裡面，同時為了跟 Backend 說明這個流程也就一併理解 Backend 這邊該怎麼處理，在這邊就分成 App 端與 Server 端來分別說明。</p><blockquote>這邊講到的只有要讓 iOS App 支援 Sign in with Apple 部分，如果你的服務是跨平臺，希望讓 Web、Android 也能支援的話，需要在 Apple Developer 上再新建一個 Services ID，然後利用官方提供的 JS Library 或自己串接官方的 API Endpoints</blockquote><h3>iOS App 端</h3><p>App 端串接 Sign in with Apple 相當簡單，大致分成五個步驟</p><h4>Apple Developer 後臺啓用 Sign in with Apple</h4><p>請先前往 <a href="https://developer.apple.com/account/resources/identifiers/list">https://developer.apple.com/account/resources/identifiers/list</a></p><p>然後點開自己的 App ID 找到 Sign in with Apple 並啓用它</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fNLpqaskQeESyQdRmoT-tQ.png" /></figure><blockquote>咳… App ID 有更新所以記得 Provision profiles 也要更新一下</blockquote><h4>新增 Entitlement</h4><p>打開 Xcode 11，點開 Project 切換到 App 的 Target，選擇上排的 Signing &amp; Capabilities</p><p>點下左上角 <strong>+ Capability</strong> 按鈕，新增 Sign in with Apple</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/684/1*qr5O1DuRM9uwhoITPJICmw.png" /></figure><h4>加入 Sign in with Apple Button</h4><p>Apple 在 iOS 13 上有提供預設的按鈕，可以經由實作 <strong>ASAuthorizationAppleIDButton</strong> 來加到自己的 UI 上，不過沒有規定一定要使用這個按鈕，如果要符合自己 App 的設計風格可以自己實作一個 UIButton</p><p>ASAuthorizationAppleIDButton 主要有三個參數可以選擇外觀</p><ul><li>ASAuthorizationAppleIDButton.ButtonType<br>決定按鈕的內容文字，有四種值可以使用： signIn, signUp (iOS 13.2 以上支援), continue, default</li><li>ASAuthorizationAppleIDButton.Style<br>決定按鈕的風格，有三種值可以設定： white, whiteOutline, black</li><li>cornerRadius<br>圓角</li></ul><blockquote>樣式可以參考 <a href="https://developer.apple.com/design/human-interface-guidelines/sign-in-with-apple/overview/">Design Guidelines</a></blockquote><pre>let button = ASAuthorizationAppleIDButton(authorizationButtonType: .default, authorizationButtonStyle: .black)<br>button.cornerRadius = 8.0<br>button.addTarget(self, action: #selector(appleLoginButtonTapped), for: .touchUpInside)</pre><h4>請求登入動作</h4><p>在處理點擊按鈕的 Method 中加上下面的 Code，<strong>requestedScopes</strong> 可以根據需求選擇要使用者提供的個人資料</p><blockquote>注意： 使用者是可以建立一個假的 email，寄到這的信件會轉發到原本的 email address，因此請不要把這裡的 email 拿來當做使用者的 ID，請使用它提供的 UID</blockquote><pre>let provider = ASAuthorizationAppleIDProvider()<br>let request = provider.createRequest()<br>request.requestedScopes = [.email, .fullName]<br>let controller = ASAuthorizationController(authorizationRequests: [request])<br>controller.delegate = self<br>controller.presentationContextProvider = self<br>controller.performRequests()</pre><h4>取得 Credential 後上傳到伺服器</h4><p>加入 <strong>ASAuthorizationControllerDelegate</strong> 和 <strong>ASAuthorizationControllerPresentationContextProviding</strong> 的實作，當登入成功後就會經由 Delegate 取得登入的 Credential</p><p>Credential 裡面會包含以下的資料：</p><ul><li>Authorization Code</li><li>Identity Token</li><li>Email (Optional)</li><li>User Identifier</li><li>Name (Family Name / Given Name…) (Optional)</li></ul><pre>extension LoginViewController: ASAuthorizationControllerDelegate {<br>    func authorizationController(controller: ASAuthorizationController, didCompleteWithAuthorization authorization: ASAuthorization) {<br>        guard let credential = authorization.credential as? ASAuthorizationAppleIDCredential else {<br>            return<br>        }<br>        // upload credential to api<br>    }</pre><pre>    func authorizationController(controller: ASAuthorizationController, didCompleteWithError error: Error) {<br>        // Show error<br>    }<br>}</pre><pre>extension LoginViewController: ASAuthorizationControllerPresentationContextProviding {<br>    func presentationAnchor(for controller: ASAuthorizationController) -&gt; ASPresentationAnchor {<br>        return self.view.window!<br>    }<br>}</pre><p>收到 Credential 後就可以把裡面的 Authorization Code、Identity Token、UID 跟其他資料上傳到 API 做驗證，如果你的 App 不需要伺服器驗證的話那你已經成功支援 Sign in with Apple 了。</p><p>接下來就可以測試了，點下按鈕後如果 iCloud 有登入且有開啓二階段認證的話，就會跳出以下的畫面：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/997/1*uK3utq5XRCbi6g7qxagrXg.jpeg" /></figure><p>到此，App 端就準備好了，接著換 Server 端的實作</p><h3>Server 端</h3><p>Apple 的登入是採用 JWT 的認證方式，在 Client 端登入成功後會取得一組 Identity Code 與 Authorization Token，當 App 成功後就把 Identity Code 與 Authorization Token 與註冊資料一併上傳到 Server api</p><blockquote>以下的範例使用的是 <strong>Node.js + Express，並使用 </strong><a href="https://github.com/request/request">request</a>、<a href="https://github.com/auth0/node-jsonwebtoken">jsonwebtoken</a> 與 <a href="https://github.com/panva/jose">jose</a></blockquote><h4>事前準備</h4><p><strong>Auth Key &amp; Key ID</strong></p><p>請先到 <a href="https://developer.apple.com/account/resources/authkeys/list">https://developer.apple.com/account/resources/authkeys/list</a> 建立一組支援 Sign in with Apple 的 Key</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iS_8qCA6V5L2DLos0ssiHg.png" /></figure><p>建立完成並下載，這組 Key 會是 p8 格式，同時請記住網頁上顯示的 Key ID</p><blockquote>這組 Key 只能下載一次，請保存在安全的地方</blockquote><p><strong>Team ID</strong></p><p>App 所在 Team 的 ID，可由 Apple Developer 後臺的 Membership 取得</p><h4>下載 Apple Public Key</h4><p>Apple 有提供一組 API 以下載 JWKS 格式的 Public Key，在 API 一開始先到它提供的 URL 去下載這組 Public Key</p><p>URL: <a href="https://appleid.apple.com/auth/keys">https://appleid.apple.com/auth/keys</a></p><p><a href="https://developer.apple.com/documentation/signinwithapplerestapi/fetch_apple_s_public_key_for_verifying_token_signature">API 文件連結</a></p><pre>// Fetch public key from Apple</pre><pre>request(&quot;https://appleid.apple.com/auth/keys&quot;, function(error, response, body) {<br>    // verify identity token</pre><pre>}</pre><h4>檢查 Identity Token</h4><p>Identity Token 是由 Apple 建立的 JWS 簽名，利用剛剛下載的 Public Key (JWKS 格式) 去做 JWS 驗證，確認這是由 Apple 所簽發的</p><pre>let jwks = jose.JWKS.asKeyStore(JSON.parse(body))</pre><pre>// JWS Verify</pre><pre>if (jose.JWS.verify(token, jwks)) {</pre><pre>    // Verified<br>}</pre><p>同時最好檢查這個 JWS 的 Payload 中包括</p><ul><li>iss 是不是來自 <a href="https://appleid.apple.com/">https://appleid.apple.com</a></li><li>aud 跟自己的 client_id 有沒有相同</li><li>確認時間是否沒有超過 exp 的時間</li></ul><h4>用 Authorization Code 跟 Apple 交換 Access Token</h4><p>將取得的 Authorization Token 送到 Apple 的 Verify API，如果 token 是合法的就會收到一組 Access Token 與 Refresh Token</p><p><strong>首先要建立 client_secret</strong></p><p>先拿出剛剛下載的 Auth Key，可以放到伺服器上或是把裡面的內容利用字串的方式放到 Environment 裡面</p><p>然後跟 Team ID, Key ID 和 App Bundle ID 一起建立一個 JWT 當做 Client Secret</p><pre>let private_key = &quot;-----BEGIN PRIVATE KEY-----\n......\n-----END PRIVATE KEY-----&quot; // Should store in a safe place on server side</pre><pre>// Generate client secret</pre><pre>let client_secret = jwt.sign({</pre><pre>    iss: &quot;YourTeamID&quot;, // Team ID, should store in server side</pre><pre>    sub: &quot;AppBundleID&quot;, // Bundle ID, should store in server side</pre><pre>    aud: &quot;https://appleid.apple.com&quot;, // Fix value</pre><pre>    iat: Math.floor(Date.now() / 1000),</pre><pre>    exp: Math.floor(Date.now() / 1000) + (60 * 60)</pre><pre>}, private_key, {</pre><pre>    algorithm: &#39;ES256&#39;,</pre><pre>header: {</pre><pre>    alg: &#39;ES256&#39;,</pre><pre>    kid: &quot;KeyID&quot; // Key ID, should store in a safe place on server side</pre><pre>}<br>})</pre><p><strong>API 驗證</strong></p><p>利用上面建立的 client_secret 、 client_id（App Bundle ID）與 Authorization Code 去跟 Apple 交換 Access Token 與 Refresh Token</p><p>API 文件： <a href="https://developer.apple.com/documentation/signinwithapplerestapi/generate_and_validate_tokens">https://developer.apple.com/documentation/signinwithapplerestapi/generate_and_validate_tokens</a></p><pre>// Request verification for apple api</pre><pre>request.post({url: &quot;https://appleid.apple.com/auth/token&quot;, form: {</pre><pre>    client_id: client_id,</pre><pre>    client_secret: client_secret,</pre><pre>    code: code,</pre><pre>    grant_type: &quot;authorization_code&quot;</pre><pre>}}, function(err, response, body) {</pre><pre>    // Handle response</pre><pre>})</pre><h4>建立使用者帳號並回傳成功</h4><p>確認這個帳號是正確的之後就可以把 UID, Refresh Token 寫入資料庫並完成回傳，這樣就完成了註冊/登入的動作</p><h4>確認登入狀態</h4><p>如果某些時候需要知道使用者是否依然有授權給 App 登入的話，可以拿之前儲存的 Refresh Token 再去跟 Apple Server 確認一次，如果正常回傳就是使用者仍然有授權，如果已經取消授權的話會回覆錯誤</p><pre>request.post({</pre><pre>    url: &quot;https://appleid.apple.com/auth/token&quot;, form: {</pre><pre>        client_id: client_id,</pre><pre>        client_secret: client_secret,</pre><pre>        grant_type: &quot;refresh_token&quot;,</pre><pre>        refresh_token: refreshToken</pre><pre>    }</pre><pre>}, function(err, response, body) {</pre><pre>    // Handle response</pre><pre>})</pre><p>以上的範例可以在此 <a href="https://gist.github.com/tuzaiz/76794a0db9e8b2b9e08fe2375d8d3ddd">參考完整版本</a></p><h3>參考文件</h3><ol><li><a href="https://developer.apple.com/documentation/signinwithapplerestapi/authenticating_users_with_sign_in_with_apple">https://developer.apple.com/documentation/signinwithapplerestapi/authenticating_users_with_sign_in_with_apple</a></li><li><a href="https://developer.apple.com/documentation/signinwithapplerestapi/verifying_a_user">https://developer.apple.com/documentation/signinwithapplerestapi/verifying_a_user</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e64d9de15410" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[利用 Swift Playground 撰寫精美又可互動的技術文件]]></title>
            <link>https://medium.com/@tuzaiz/%E5%88%A9%E7%94%A8-swift-playground-%E6%92%B0%E5%AF%AB%E7%B2%BE%E7%BE%8E%E5%8F%88%E5%8F%AF%E4%BA%92%E5%8B%95%E7%9A%84%E6%8A%80%E8%A1%93%E6%96%87%E4%BB%B6-9e3253a4d90f?source=rss-34810ec544d3------2</link>
            <guid isPermaLink="false">https://medium.com/p/9e3253a4d90f</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[swift-programming]]></category>
            <category><![CDATA[swift-playgrounds]]></category>
            <category><![CDATA[xcode]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <dc:creator><![CDATA[兔子]]></dc:creator>
            <pubDate>Fri, 19 Oct 2018 15:35:55 GMT</pubDate>
            <atom:updated>2018-10-19T15:43:34.450Z</atom:updated>
            <content:encoded><![CDATA[<p>今天利用時間把一直沒時間只好放在待學期清單裡的 Playground 好好的摸了一遍，剛好可以致敬明天要舉辦的 <a href="http://iplayground.io/">iPlayground</a> （硬要扯）</p><p>當 Swift 公開時，同時也開放了一個很強大的工具，那就是 Swift Playground 。利用 Playground 可以即時的看到自己寫的一些程式執行的結果是否正確，而不用不斷的重新 Build &amp; Run 。而隨著 Swift 版本已經來到了 4.2 的今日，Playground 的功能也越來越強大，不但可以即時顯示結果，甚至可以直接在上面做 UI 、寫文件。</p><h3>主要目標</h3><p>今天一開始先設定好我想要理解的幾個目標：</p><ul><li>建立 Playground</li><li>在 Playground 中設計 UI</li><li>整合第三方 Framework</li><li>在實際維護的專案中加入 Playground</li><li>利用 Playground 撰寫文件</li></ul><h3>建立 Playground</h3><p>首先是建立 Playground ，跟一般的檔案一樣，從 Xcode 裡面選擇 File -&gt; New -&gt; Playground 就可以建立一個基本的 Playground</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oUV6WFlnb2PIC-HLReiLMQ.png" /></figure><p>此時可以選擇樣板，基本上就是看你要拿來試做什麼，預先幫你準備好基本需要用到的原始碼。</p><p>選擇了 Blank 就會建立一個最基本的 Playground</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jDuQPwKy4sF93VTjwJeLDQ.png" /></figure><p>此時按左邊行數列上面的執行按鈕就可以讓 Playground 執行到那一行，也可以選擇 Editor -&gt; Run Playground 或按 ⌘⇧↩︎ 執行全部，運算出的值會顯示在右邊側邊列。</p><h3>在 Playground 中設計 UI</h3><p>在建立 Playground 選擇樣板時選擇 View 的話就會建立一個有個基本 UIView 的 Playground ，也可以在既有的 Playground 中先</p><pre>import PlaygroundSupport<br>import UIKit</pre><p>然後在 Playground 中把自己設計的 UIViewController 或 UIView 指定到</p><p>PlaygroundPage.current.liveView</p><p>然後切換 Xcode 到 Assistant Editor 模式，再 Run 就可以看到右邊出現剛剛設計好的 UI （要做互動、動畫都可以）</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/366/1*83WbS4M4JKdhvMfLT74Qqw.png" /><figcaption>Assistant Editor 在 Xcode 右上角可以切換 （快捷鍵： ⌥⌘, ）</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zm0GhHQtl015jffyM7YFzg.png" /></figure><h3>整合第三方 Framework 到 Playground</h3><p>現在大家都習慣使用 CocoaPods 或 Carthage 之類的工具去管理 Framework 的版本，不過不管是用套件管理工具還是自己建立好的 Framework 都沒辦法直接拖進 Playground 中使用，為了要在 Playground 裡面使用這些 Framework 的功能，首先我們要建立一個 Project</p><p>然後利用一般習慣的方法給這個 Project 裡面的 Target 新增 Framework</p><p>最後再把 Playground 加入這個 Project 裡面，在測試 Playground 之前記得先 Build 一次這個 Target ，然後在 Playground 中就可以使用這個 Framework 中的功能了。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FEnvfvHGAA7Yp48EEp6NKg.png" /><figcaption>連 HTTP Request 也可以取得結果</figcaption></figure><h3>在實際維護的專案中加入 Playground</h3><p>會想要使用 Playground 的情境中，其中一種就是想在 Playground 中先驗證自己所寫的函式或是演算法是否正確，但如果架構稍大要移入 Playground 中就有點麻煩，如果可以直接在 Playground 中存取到自己寫好的 Class 的話就會方便很多。</p><p>為了要將自己寫好的 Source code 引入 Playground 中，首先要先在既有的專案中新增 一個 Target （ New -&gt; Target ），然後 Target 的類型要選擇 Cocoa Touch Framework</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RQWTI2AOyMukgZvIp8erlg.png" /></figure><p>然後將自己要使用到的 Class 其相關的所有檔案加入到這個 Target 之中，然後 Build 一次後再到 Playground 中 import 這個 Framework</p><blockquote>請記住，這樣實際上是 Playground 利用 Framework 來引用你寫好的程式，因為是外部的 Module 所以記得要在用到的 Class 前方加上 <em>open</em> 還有函式跟變數的前面加上 <em>public</em></blockquote><p>這樣就可以在 Playground 中使用自己寫好的那些 Class。</p><h3>利用 Playground 來撰寫文件</h3><p>這件事其實是我今天最大的目的，因為我想利用 Playground 來撰寫一個可直接在裡面看到執行結果與用法的技術文件，而 Playground 支援使用 Markup 語法來撰寫 Rich Text 的文件。</p><p>Playground 有兩種顯示模式 Raw Markup 跟 Rendered Markup ，可以在 Editor -&gt; Show xxx Markup 切換，先讓我們切換到 Raw Markup 模式</p><p>在要寫說明文字的地方加上</p><p>單行： //: <br>多行： /*: 與 */</p><p>對，就是註解的後面加上一個 :</p><p>然後在裡面就可以利用 Markup 語法去對文字設定格式，以下列出一些基本的語法：</p><ul><li>第一階標題： #</li><li>第二階標題： ##</li><li>斜體： 用 * 或 _ 包住文字</li><li>粗體： 用 ** 或 __ 包住文字</li><li>分隔線： ----</li><li>連結： [文字](URL)</li></ul><p>其他還有許多的 Markup 用法可以參考 <a href="https://developer.apple.com/library/archive/documentation/Xcode/Reference/xcode_markup_formatting_ref/index.html#//apple_ref/doc/uid/TP40016497-CH2-SW1">Apple 官網的文件</a></p><p>結合以上的用法，就可以在自己的專案中寫出精美且可以直接修改看結果的技術文件出來，我簡單地試寫了一個使用 RxSwift 去開發 MVVM 的簡單說明，效果如下：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fy0bsnFG_9aw6J4J0InMfg.png" /></figure><p>看上去是不是很不錯，而且這個文件可以即時的執行，並且將結果顯示在右方，如果看到文件的人想要試試看修改裡面的原始碼會產生什麼效果只要直接修改並執行就可以，可以讓看的人更加了解實際的效果。</p><p>這樣的技術文件相信會讓第一次看到的人能更加快速的掌握到文件想要描述的內容，而且可以把程式碼架構跟流程更加清晰的描述出來，對團隊內的技術同步溝通也會更加順暢。</p><p>如果最近剛好有要寫文件的人如果看到這篇可以試著自己也寫一個這樣的文件試試，也歡迎將自己撰寫的文件或是心得留言跟我分享一下。</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9e3253a4d90f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[利用Generic Type跟Extension來優化Storyboard取得UIViewController的動作]]></title>
            <link>https://medium.com/@tuzaiz/%E5%88%A9%E7%94%A8generic-type%E8%B7%9Fextension%E4%BE%86%E5%84%AA%E5%8C%96storyboard%E5%8F%96%E5%BE%97uiviewcontroller%E7%9A%84%E5%8B%95%E4%BD%9C-581d503a0314?source=rss-34810ec544d3------2</link>
            <guid isPermaLink="false">https://medium.com/p/581d503a0314</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[兔子]]></dc:creator>
            <pubDate>Mon, 22 Jan 2018 16:00:31 GMT</pubDate>
            <atom:updated>2018-01-22T16:00:31.966Z</atom:updated>
            <content:encoded><![CDATA[<p>每次在處理從Storyboard中取出ViewController的動作時，大多都會用到類似下面這樣的程式碼：</p><pre>let viewController = storyboard.instantiateViewController(withIdentifier: &quot;SomeViewController&quot;) as! SomeViewController</pre><p>而今天我在做第N次這樣的動作時心想，不知道有沒有辦法讓這一段變得更加的直覺。</p><p>簡單地分析了一下，主要我想解決的問題是：</p><ol><li>使用字串作爲Identifier容易因爲錯字而導致錯誤</li><li>必須要強制轉型成正確的Type</li></ol><p>在確定了想改善的方向之後我就開始規劃。首先我先建立一個Struct去存放原本需要的Identifier字串，然後利用Generic Type來將我們想要轉換的Type給存放起來，所以就產生像下面這樣的Struct：</p><pre>struct StoryboardIdentifier&lt;T: UIViewController&gt; {<br>    var identifier: String<br>    var type: T.Type<br>    <br>    init(identifier: String, type: T.Type) {<br>        self.identifier = identifier<br>        self.type = type<br>    }<br>}</pre><p>建立好架構後，就用Extension將前面舉例的SomeViewController的Type跟Identifier定義爲一個static variable：</p><pre>extension StoryboardIdentifier {<br>    static var some: StoryboardIdentifier&lt;SomeViewController&gt; {<br>        return StoryboardIdentifier&lt;SomeViewController&gt;(identifier: &quot;SomeViewController&quot;, type: SomeViewController.self)<br>    }<br>}</pre><p>這樣，就可以直接用 StorybosardIdentifier.some 這樣的方式去取得那個我們定義好的Identifier。</p><p>但因爲原本的UIStoryboard並不認識StoryboardIdentifier這個Struct，所以我利用Extension去給它增加一個Method，將帶入的StoryboardIdentifier給轉換成對應的UIViewController：</p><pre>extension UIStoryboard {<br>    func instantiateViewController&lt;T&gt;(withIdentifier identifier: StoryboardIdentifier&lt;T&gt;) -&gt; T {<br>        return self.instantiateViewController(withIdentifier: identifier.identifier) as! T<br>    }<br>}</pre><p>到此剩下的我們就可以利用下面這樣的寫法從Storyboard中取得ViewController。</p><pre>let vc = storyboard.instantiateViewController(withIdentifier: .some) // Type就會是SomeViewController</pre><p>這是今天的一個小嘗試，往後就只需要用Extension給StoryboardIdentifier增加定義其他的ViewController就可以用相同的方法，既避免了打錯字造成的錯誤，又減少需要轉型的動作。</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=581d503a0314" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[使用類似Notification.Name的方法處理UserDefaults與其他當作Key的字串]]></title>
            <link>https://medium.com/@tuzaiz/%E4%BD%BF%E7%94%A8%E9%A1%9E%E4%BC%BCnotification-name%E7%9A%84%E6%96%B9%E6%B3%95%E8%99%95%E7%90%86userdefaults%E8%88%87%E5%85%B6%E4%BB%96%E7%95%B6%E4%BD%9Ckey%E7%9A%84%E5%AD%97%E4%B8%B2-87bccfb8c95e?source=rss-34810ec544d3------2</link>
            <guid isPermaLink="false">https://medium.com/p/87bccfb8c95e</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[兔子]]></dc:creator>
            <pubDate>Wed, 20 Sep 2017 10:08:55 GMT</pubDate>
            <atom:updated>2017-12-06T13:42:33.737Z</atom:updated>
            <content:encoded><![CDATA[<p>在Swift 3之前，我們需要使用字串去作為發送或監聽NotificationCenter的事件名稱，而從Swift 3之後，我們可以使用Notification.Name來作為NotificationCenter的名稱。</p><p>使用這方法我們就可以事先定義好，不用擔心在不同的地方打錯字串而造成事件無法收到的問題，只需要先像這樣宣告好Name：</p><pre>extension NSNotification.Name {<br>  static var userLogin = NSNotification.Name(rawValue: &quot;UserLogin&quot;)<br>}</pre><p>之後就可以用這個Name去處理NotificationCenter的事件</p><pre>// 發送<br>NotificationCenter.default.post(name: .userLogin, object: user)</pre><pre>// 監聽<br>NotificationCenter.default.addObserver(forName: .userLogin, object: nil, queue: nil) {(notification) in<br>  // Handle<br>}</pre><p>這方法的好處是，在name的位置我們只需要打 . Xcode就會跳出所有定義好的Name，從而避免字串打錯字而發生行為錯誤的問題。</p><p>那這引起我的另一個想法，我們是否可以用類似的方法去處理UserDefaults或Keychain等等的Keys呢？</p><p>嘗試之後，發現可以用一個extension就做到類似的行為，以下以UserDefaults為例</p><p>首先貼上以下這段</p><pre>extension UserDefaults {<br>    enum Key {<br>        case `default`(key: String)<br>        init(key: String) {<br>            self = .default(key: key)<br>        }<br>    }<br>}</pre><p>這裡我們使用extension去建立一個enum在UserDefaults下面，並放一個default的case去儲存字串</p><p>然後用extension給UserDefaults新增一些使用UserDefaults.Key而非String的方法：</p><pre>extension UserDefaults {<br>    func set(_ value: Any?, forKey key: UserDefaults.Key) {<br>        if case UserDefaults.Key.default(let k) = key {<br>            self.set(value, forKey: k)<br>        }<br>    }<br>    <br>    func removeObject(forKey key: UserDefaults.Key) {<br>        if case UserDefaults.Key.default(let k) = key {<br>            self.removeObject(forKey: k)<br>        }<br>    }<br>    <br>    func value(forKey key: UserDefaults.Key) -&gt; Any? {<br>        if case UserDefaults.Key.default(let k) = key {<br>            return self.value(forKey: k)<br>        }<br>        return nil<br>    }<br>    <br>    func string(forKey key: UserDefaults.Key) -&gt; String? {<br>        if case UserDefaults.Key.default(let k) = key {<br>            return self.string(forKey: k)<br>        }<br>        return nil<br>    }<br>    <br>    func dictionary(forKey key: UserDefaults.Key) -&gt; Dictionary&lt;String, Any&gt;? {<br>        if case UserDefaults.Key.default(let k) = key {<br>            return self.dictionary(forKey: k)<br>        }<br>        return nil<br>    }<br>    <br>    func integer(forKey key: UserDefaults.Key) -&gt; Int {<br>        if case UserDefaults.Key.default(let k) = key {<br>            return self.integer(forKey: k)<br>        }<br>        return 0<br>    }<br>    <br>    func float(forKey key: UserDefaults.Key) -&gt; Float {<br>        if case UserDefaults.Key.default(let k) = key {<br>            return self.float(forKey: k)<br>        }<br>        return 0.0<br>    }<br>    <br>    func double(forKey key: UserDefaults.Key) -&gt; Double {<br>        if case UserDefaults.Key.default(let k) = key {<br>            return self.double(forKey: k)<br>        }<br>        return 0.0<br>    }<br>    <br>    func bool(forKey key: UserDefaults.Key) -&gt; Bool {<br>        if case UserDefaults.Key.default(let k) = key {<br>            return self.bool(forKey: k)<br>        }<br>        return false<br>    }<br>}</pre><p>最後再如同Notification.Name那般，建立UserDefaults.Key</p><pre>extension UserDefaults.Key {<br>    static var user = UserDefaults.Key(key: &quot;User&quot;)<br>    static var token = UserDefaults.Key(key: &quot;Token&quot;)<br>}</pre><p>這樣之後我們就可以用下面這種方法去設定、刪除或取得UserDefaults中的值了</p><pre>UserDefaults.standard.set(userData, forKey: .user)</pre><pre>UserDefaults.standard.removeObject(forKey: .user)</pre><pre>let userData = userDefaults.dictionary(forKey: .user)</pre><p>相同的方法也可以用在其他需要輸入字串當Key的方法上，這樣將可以避免打錯字的問題，也可以直接看到所有目前存在著的Key，並使用Auto Completion</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=87bccfb8c95e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[用Alamofire做HTTP Basic Authentication]]></title>
            <link>https://medium.com/@tuzaiz/%E7%94%A8alamofire%E5%81%9Ahttp-basic-authentication-1fa6e21531be?source=rss-34810ec544d3------2</link>
            <guid isPermaLink="false">https://medium.com/p/1fa6e21531be</guid>
            <category><![CDATA[alamofire]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[兔子]]></dc:creator>
            <pubDate>Sun, 08 Mar 2015 09:31:10 GMT</pubDate>
            <atom:updated>2015-03-08T09:31:10.071Z</atom:updated>
            <content:encoded><![CDATA[<p>這週末有個機會要做個小Sample給別人，這個Sample Project需要用到HTTP API Request且這個Request需要做HTTP Basic Authentication。</p><p>想說有這個機會，也不是正式產品，因此就試著完全用Swift來寫，那HTTP Request當然就交給<strong>AFNetworking</strong>的作者 <strong>Mattt Thompson</strong> 所製作的另一個套件 <a href="https://github.com/Alamofire/Alamofire"><strong>Alamofire</strong></a></p><p>Alamofire是完全基於Swift所撰寫的HTTP Request套件，整個語法都有著濃濃的Functional Programming特性在其中。</p><p>以下範例是直接將Alamofire.swift Copy到Bundle中的作法，如果是用CocoaPods或其他方法安裝的話，請先 <em>import Alamofire</em> ，然後在每個Method call前加上 <em>Alamofire</em>。如 <em>request() 要改成 Alamofire.request()</em></p><p>要發送一個GET方法的要求出去只要這樣：</p><pre>request(.GET, “http://this.is.url/path”)</pre><p>而要處理回傳的內容則只要接著：</p><pre>request(.GET, “http://this.is.url/path”).response {(req, res, data, error) in<br>  // Handle in here</pre><pre>}</pre><p>相當簡單易懂，但對寫Objective-C久了的人來說一定很不習慣。</p><p>不過這次的要求不單只是要送一個Request出去而已，還需要做HTTP Basic Authentication，查了一下官方Repo上的說明，要做Authentication只需要：</p><pre>request(.GET, “http://this.is.url/path”).authenticate(user: &quot;username&quot;, password: &quot;password&quot;).response {(req, res, data, error) in<br>  // Handle in here</pre><pre>}</pre><p>即可，我很興奮地照著實作，然後就一直接到<strong>401 Unauthorized</strong>的錯誤…</p><p>把發送出去的Request攔下來看，結果發現雖然有帶Authentication，但是Header中卻沒有Authentication的欄位。HTTP Basic Authentication除了要求User跟Password之外，還要求要帶一個值</p><blockquote><em>“Authorization” = “Basic MTIzNDo1Njc4&quot;</em></blockquote><p>後面那串亂碼是由字串 “Username:Password” 經由Base64轉換出來的字串，但是Alamofire並沒有實作這個，因此要正常運作，我們必須自行給它加上這個Header。</p><p>首先我們要產生這個Hash字串：</p><pre>let originString = “username:password”</pre><pre>let originStringData = originString.dataUsingEncoding(NSUTF8StringEncoding) // String -&gt; NSData?</pre><pre>let hashString = originStringData!.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(0)) // NSData! -&gt; String</pre><p>然後把產生出來的Hash加到HTTP Request Header中：</p><pre>Manager.sharedInstance.session.configuration.HTTPAdditionalHeaders = [&quot;Authorization&quot;: &quot;Basic \(hashString)&quot;]</pre><p>這樣就可以通過HTTP Basic Authentication的認證了。</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1fa6e21531be" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Swift 的 String 操作]]></title>
            <link>https://medium.com/@tuzaiz/swift-string-9d65aea7b11d?source=rss-34810ec544d3------2</link>
            <guid isPermaLink="false">https://medium.com/p/9d65aea7b11d</guid>
            <dc:creator><![CDATA[兔子]]></dc:creator>
            <pubDate>Thu, 12 Feb 2015 10:23:08 GMT</pubDate>
            <atom:updated>2015-02-12T10:23:08.008Z</atom:updated>
            <content:encoded><![CDATA[<p>在Swift中有自己獨立的字串格式 <strong>String</strong>，操作的方法與NSString類似，將各種的操作方式整理在這邊方便大家查找。</p><p>大概是為了跟Objective-C能夠相容，部分String methods依舊是跟NSString相同，但又多了些新的用法，所以整個用法很不統一，因此在寫這篇文章的同時，順手寫了一個Extension將這些方法整理在一起，可以用比較統一的方法去做字串操作。</p><p>如果有人有興趣，可以參考： <a href="https://github.com/tuzaiz/RacoonString">https://github.com/tuzaiz/RacoonString</a></p><h3>取得字串長度</h3><pre>countElements(string) // Swift 1.0</pre><pre>count(string) // Swift 1.2</pre><h4>RacoonString</h4><pre>string.length() // RacoonString</pre><h3>尋找字串</h3><pre>var string = “Swift is awesome”</pre><pre>let range = string.rangeOfString(“awesome”)</pre><pre>if let range = range {</pre><pre>    // 尋找字串開始位置</pre><pre>    println(“Start with: \(range.startIndex)”)</pre><pre>    println(“End with: \(range.endIndex)”)</pre><pre>    // 取出要查詢的字串</pre><pre>    println(string[range])</pre><pre>}</pre><h4>RacoonString</h4><pre>string.match(&quot;awesome&quot;)<br>if let regex = &quot;awe(some)&quot; {<br>  string.match(regex)</pre><pre>}</pre><h3>抓出特定範圍的字串</h3><pre>let r = 3..&lt;5</pre><pre>let startIndex = advance(string.startIndex, r.startIndex)</pre><pre>let endIndex = advance(startIndex, r.endIndex — r.startIndex)</pre><pre>string[Range(start: startIndex, end: endIndex)]</pre><h4>RacoonString</h4><pre>string[3..&lt;5]</pre><h3>切開字串</h3><pre>split(string, {$0==” ”}, maxSplit: Int.max, allowEmptySlices: false)</pre><p>或是</p><pre>string.componentsSeparatedByString(“ “)</pre><h4>RacoonString</h4><pre>string.splitBy(&quot; &quot;)</pre><h3>連接字串</h3><pre>let joiner = “,”</pre><pre>joiner.join(matches)</pre><h3>取代字串</h3><pre>string.stringByReplacingOccurrencesOfString(“Swift”, withString: “Apple”, options: .LiteralSearch, range: nil)</pre><h4>RacoonString</h4><pre>string.sub(&quot;Swift&quot;, &quot;Apple&quot;)<br>string.sub(0..&lt;5, &quot;Apple&quot;)</pre><h3>大小寫轉換</h3><pre>string.uppercaseString // 全部轉為大寫</pre><pre>string.capitalizedString // 每個單字第一個字大寫</pre><pre>string.lowercaseString // 全部轉為小寫</pre><h3>去除前後空白與換行</h3><pre>string.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())</pre><h4>RacoonString</h4><pre>string.trim()</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9d65aea7b11d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Swift下將NSData轉換成String]]></title>
            <link>https://medium.com/@tuzaiz/swift-nsdata-string-323ed8a7e3cc?source=rss-34810ec544d3------2</link>
            <guid isPermaLink="false">https://medium.com/p/323ed8a7e3cc</guid>
            <dc:creator><![CDATA[兔子]]></dc:creator>
            <pubDate>Sun, 19 Oct 2014 14:58:58 GMT</pubDate>
            <atom:updated>2014-10-19T14:58:58.623Z</atom:updated>
            <content:encoded><![CDATA[<p>Swift中跟Foundation之間的恩怨情仇實在剪不斷理還亂。</p><p>在Foundation中大部份I/O時都會取得NSData格式的資料，而以前在Objective-C時取得NSData要轉成NSString需要經過</p><pre>NSString *string = [[NSString alloc] initWithData:data encoding:NSUTF8Encoding];</pre><p>將NSData轉換成NSString，但是在Swift下對於字串有自己專用的Type <strong>String</strong></p><p>我原本以為應該會有 <strong>String.stringWithData(data, encoding=.UTF8)</strong> 或是 <strong>String(data, encoding=.UTF8)</strong> 之類的方法可以用，結果找了半天都找不到。</p><p>查了半天，結果終於找到解法：</p><pre>var string : String = NSString(data: data, encoding: NSUTF8StringEncoding)</pre><p>原來因為在Swift下的String基本上背後還是NSString，所以可以直接轉換來使用。</p><p>Swift是個好語言，不過為了與既有的Foundation架構還有Objective-C相容實在要花太多的力氣，這是目前學習Swift的一個很大的障礙，接下來就看蘋果會怎麼去發展這個潛力無窮的新語言囉。</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=323ed8a7e3cc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[用Swift寫Core Data會遇到的Type錯誤]]></title>
            <link>https://medium.com/@tuzaiz/swift-core-data-type-592e37e3f4c8?source=rss-34810ec544d3------2</link>
            <guid isPermaLink="false">https://medium.com/p/592e37e3f4c8</guid>
            <dc:creator><![CDATA[兔子]]></dc:creator>
            <pubDate>Sat, 18 Oct 2014 14:56:19 GMT</pubDate>
            <atom:updated>2014-10-18T14:56:19.470Z</atom:updated>
            <content:encoded><![CDATA[<p>這幾天用Swift撰寫Core Data的應用時總是會出現一些詭異的錯誤，像是下面這段Code：</p><pre>var fetchRequest = NSFetchRequest(entityName: “Person”)<br>var people = appDelegate.managedObjectContext?.executeFetchRequest(fetchRequest, error: nil)<br>var person = people?.first as Person<br>println(people)<br>println(person)</pre><p>同樣類似的用法，我曾遇過下面兩種奇特的狀況</p><p>一種是第一個println有輸出Array與值，但person卻是nil。</p><p>而另一種則是直接就顯示下面的Warning接著Crash</p><blockquote><strong>CoreData: warning: Unable to load class named ‘Person’ for entity ‘Person’. Class not found, using default NSManagedObject instead.</strong></blockquote><p>查了許多地方後終於找出了問題的所在，原來在Swift中關於Type的形式應該是 <strong>ProjectName.TypeName</strong></p><p>但Xcode在 .xcdatamodeld 新增Entity時，並不會將Entity指向正確的Type，格式只有 <strong>TypeName，</strong>導致Runtime時找不到該Type，所以不然是因為 as 的轉型態不正確而變成 nil，要不然就是直接Crash。</p><p>我想這是諸多Swift為了相容於舊專案而衍生出來的問題之一，不過解法也相當簡單，只要到 .xcdatamodeld 檔案中的Configurations將每一個Entity的Class指向正確的地方就可以了。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/632/1*Jqf15RZHO7l0XFWtaBYxJQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/634/1*qpMxPm6At9X99orRZLTjpg.png" /></figure><p>現在總算是可以正確的抓出我要的資料了。</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=592e37e3f4c8" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>