<?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 Michael Revlis on Medium]]></title>
        <description><![CDATA[Stories by Michael Revlis on Medium]]></description>
        <link>https://medium.com/@michaelrevlis?source=rss-c7e3d6c91730------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*twlqsPEjTU-9HG3A.</url>
            <title>Stories by Michael Revlis on Medium</title>
            <link>https://medium.com/@michaelrevlis?source=rss-c7e3d6c91730------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 18:55:51 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@michaelrevlis/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[Handling “SecurityError: The operation is insecure” When Using LocalStorage in an iOS WebView]]></title>
            <link>https://michaelrevlis.medium.com/handling-securityerror-the-operation-is-insecure-when-using-localstorage-in-an-ios-webview-565142b5ef8a?source=rss-c7e3d6c91730------2</link>
            <guid isPermaLink="false">https://medium.com/p/565142b5ef8a</guid>
            <category><![CDATA[js-localstorage]]></category>
            <category><![CDATA[agile-development]]></category>
            <category><![CDATA[wkwebview]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Michael Revlis]]></dc:creator>
            <pubDate>Sun, 24 Nov 2024 09:02:21 GMT</pubDate>
            <atom:updated>2024-11-24T09:09:45.803Z</atom:updated>
            <content:encoded><![CDATA[<p>Recently, I was tasked with rendering a demo page using an HTML string. While the HTML worked perfectly in any browser, it didn’t behave the same way on iOS. The content was simple enough that I quickly identified the issue as being related to the use of localStorage. A quick online search led me to numerous solutions and discussions on forums like StackOverflow. At that moment, I realized the importance of clearly defining my problem and documenting the steps I was taking. Without that clarity, I risked aimlessly wandering through a sea of information with no sense of direction or solution in sight.</p><p>Rather than attempting random fixes found on the net, it’s crucial to first identify the root cause. Since this issue spans iOS and WebView behavior, it’s important to approach it with a perspective broader than just that of an iOS developer. Let’s start by examining the error itself, as it originates from the WebView.</p><p>The error, <strong>SecurityError: The operation is insecure</strong>, is well-documented and typically occurs in the following scenarios (refer to <a href="https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage">MDN documentation</a>):</p><blockquote>The origin is not a valid scheme/host/port tuple. This can happen if the origin uses the file: or data: schemes, for example.</blockquote><blockquote>The request violates a policy decision. For example, the user has configured the browsers to prevent the page from persisting data.</blockquote><p>Let’s address the second case first. In this scenario, the issue arises from specific user configurations or policies. However, since I was testing on a clean, unmodified iPhone environment, this wasn’t applicable.</p><p>However, in the meantime, it’s important to recognize that those configurations and scenarios could also cause the WebView to fail. Instead of just solving the problem technically, this is an opportunity to take a step back and think like a product manager, not just a mobile developer. By sharing these insights with front-end developers and product managers early on, we can work together to set realistic product expectations and avoid unnecessary roadblocks down the line. This proactive approach helps ensure the product is well-rounded and robust. And this is exactly an example of how<strong> Incremental Product Design</strong> and <strong>Exploratory Development </strong>function in Agile Development.</p><p>Now, let’s focus on the first case: an invalid origin. This is particularly relevant because our scenario involves loading an HTML file locally. Many solutions emphasize the timing of localStorage operations without clarifying that their WebView is being loaded from a remote server.</p><p>According to <a href="https://developer.apple.com/documentation/webkit/wkwebview/loadhtmlstring(_:baseurl:)">Apple’s developer documentation</a>, when loading an HTML string in a WKWebView, you can specify a baseURL. This baseURL is used to resolve relative URLs within the HTML.</p><pre>@MainActor<br>func loadHTMLString(<br>    _ string: String,<br>    baseURL: URL?<br>) -&gt; WKNavigation?</pre><p>By default, baseURL is nil, which means the HTML’s origin is undefined. If you load an HTML string locally without defining a baseURL, it will be treated as insecure. To resolve this, you can set the baseURL to Bundle.main.bundleURL. This approach defines the origin and ensures it is considered secure.</p><p>Additionally, setting the baseURL to Bundle.main.bundleURL allows the HTML to access other local resources in your app’s bundle.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_t4O9XuCOTtOuVei_F2V5g.jpeg" /></figure><p>By properly defining the baseURL, you can resolve the SecurityError and enable your HTML to seamlessly interact with localStorage and other local resources. Additionally, this article highlights a systematic approach to problem-solving and identifies how we can be proactive to shape the product roadmap.</p><p>Further reading:</p><ul><li><a href="https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage">MDN: Window: localStorage property</a></li><li><a href="https://developer.apple.com/documentation/webkit/wkwebview/loadhtmlstring(_:baseurl:)">Apple Developer Document &gt; WebKit &gt; WKWebView &gt; loadHTMLString(_:baseURL:)</a></li><li><a href="https://github.com/WebView-CG/usage-and-challenges/issues/7">What is the “Origin” in a WebView, for locally hosted content?</a></li><li><a href="https://github.com/react-native-webview/react-native-webview/issues/2093">react-native-webview: can’t use localstorage, The operation is insecure. #2093</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=565142b5ef8a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[焦慮與自我懷疑？或許是挑戰或環境的問題，而不是你！]]></title>
            <link>https://michaelrevlis.medium.com/%E7%84%A6%E6%85%AE%E8%88%87%E8%87%AA%E6%88%91%E6%87%B7%E7%96%91-%E6%88%96%E8%A8%B1%E6%98%AF%E6%8C%91%E6%88%B0%E6%88%96%E7%92%B0%E5%A2%83%E7%9A%84%E5%95%8F%E9%A1%8C-%E8%80%8C%E4%B8%8D%E6%98%AF%E4%BD%A0-f314e0a8d132?source=rss-c7e3d6c91730------2</link>
            <guid isPermaLink="false">https://medium.com/p/f314e0a8d132</guid>
            <category><![CDATA[底層邏輯]]></category>
            <category><![CDATA[心流]]></category>
            <category><![CDATA[被討厭的勇氣]]></category>
            <category><![CDATA[心態致勝]]></category>
            <dc:creator><![CDATA[Michael Revlis]]></dc:creator>
            <pubDate>Sun, 17 Nov 2024 16:54:54 GMT</pubDate>
            <atom:updated>2024-11-17T16:54:54.492Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>失落的時候別往心裡去、心流：挑戰與技能的匹配、專注於可改變的部分，成長心態、記錄與回顧、拍拍屁股走人</blockquote><p>焦慮和缺乏自信其實是很常見的情緒，尤其是在我們面臨超出自身能力範圍的挑戰時。這並不意味著我們的能力不足，而更多是因為當前的挑戰與我們的技能不太匹配，讓我們感受到壓力和不安。</p><p>每個人在面對挫折時的反應，都會受到環境和經驗的影響。比如那些長期表現穩定且出色的人，往往對自己的能力有較高的信任。即使偶爾遇到失誤，他們也能以平靜的心態看待，因為他們有許多過往的成功經驗來支撐對自己的肯定。然而，對於那些經常犯錯的人來說，情況就不太一樣了。如果錯誤反覆發生，甚至無法找到外在的解釋時，內心難免會開始質疑自己的能力。</p><p><strong>原因一：挑戰與能力不匹配</strong></p><p>或許你也有過類似的經驗：有時你會感到自己能夠順利應對挑戰，充滿自信；但有時挑戰過於艱難，讓你感到壓力重重，甚至懷疑自己的能力。這種情況正好呼應了心理學家希克森米哈伊在《心流》一書中提出的：當我們的技能和挑戰相匹配時，容易進入一種充滿專注和成就感的狀態，稱為「心流」；相反，當挑戰過高時，我們會感到焦慮和壓力。</p><p>而<strong>除了技能水平以外，所具備的技能組是否吻合挑戰內容的需求也是一個要點</strong>。例如，一位初入職場的新人可能被指派需要高階技能的專案，而這些技能需要時間培養。他可能因無法快速達成目標而懷疑自己的能力，並因此對自己產生負面評價。然而，這種情況更多是挑戰所需的技能組與其當下所具備的技能組並不吻合所致，而不是個人的問題。剛步入職場的「前學生」過去數十年的時間都投入在「學校體制」下所需要的技能 — 推理、研究。而職場上要求他的可能是專業領域知識、職場文化、向上管理等技能。</p><p>面對技能水平不夠的狀況，透過調整目標難度或精進技能；面對技能組不匹配的狀況，則可透過挑選挑戰內容或積極學習所缺少的技能。具體問題具體分析，一步一步來，逐步縮小這個差距。</p><p>長期的焦慮感最終可能會導致我們開始懷疑自己的能力。這種懷疑並不是毫無依據的，它反映了現實中的困難。但這並不意味著我們無法改變現狀。首先，我們可以<strong>專注於那些自己能夠改變的部分</strong>，正如岸見一郎和古賀史健在《被討厭的勇氣》中提到的「課題分離」，將注意力放在我們可以掌控的範圍，而不是被外界的評價或過去的失誤所牽引。現實中我們有一大堆問題要面對，每個都有緊急得不得了的理由，但我們可從自己掌握度最高的項目開始著手，且不可貪心、心急，逐步把瓶頸一個個解開。</p><p>此外，擁有「成長心態」也是突破困境的關鍵。心理學家卡羅爾·杜維克的研究指出，當我們相信自己的能力可以通過學習和努力提升時，困境反而成為成長的機會。即使遇到自己造成的問題，我們也能看待這些為可改變的挑戰，並找到需要學習的技能，透過刻意練習來加強自己。我們可以考慮適當地調整挑戰的難度，這並不是退縮，而是讓自己能逐步前進。例如，設立更符合當前能力的目標，或將目標轉向尋求他人協助來完成任務，這也是一種合作策略。甚至，我們也可以重新審視工作的內容和職責，確保它們更符合我們當前的能力，也不排除在適當的時候做出職場上的變化。</p><p>為了能夠持續追蹤自己的進步，或許我們可以使用 OKR，<strong>詳細記錄自己的目標和成就。這樣的過程不僅能提供一個清晰的進步路徑，還能幫助我們看到每一步中的成長</strong>。唯有透過紀錄我們才有機會看到一路上的起伏，不至於僅見眼前的樹卻不見背後的林。</p><p><strong>原因二：環境與自身價值觀不符</strong></p><p>另一個容易讓人感到挫折和失落的原因，則來自於環境的影響。有些時候，我們可能處在一個價值觀或制度與自身認知相左的環境中，這樣的落差會導致彼此之間的期待難以契合。即使具備足夠的能力，也可能因無法發揮自己的優勢，而覺得事倍功半。</p><p>舉例來說，有些人重視高效率的工作方式，但所處的職場可能更看重加班文化，甚至暗含非明文規定的加班要求，讓他感到與環境格格不入。又或者，一些主管習慣以嚴厲甚至言語暴力進行管理，營造出讓人壓抑的氛圍，而在這樣的環境中，那些習慣以溝通和合作為核心的人，往往會感到難以適應。這些價值觀上的差異並不是能力的問題，而是環境本身未能提供適合發揮的空間。</p><p>劉潤在《底層邏輯》中提到事實、觀點、立場、信仰，每一層的衝突可以嘗試往上一層尋找共識。但如果衝突來自於信仰層面，底層的價值觀有太大的隔閡，那換環境或許是更好的選擇，畢竟「損失最大者才是輸家」，幫自己選一個事半功倍、切合自己地方並不是逃避，而是讓自己不輸，對自己負責。</p><p>總的來說，焦慮和自我懷疑是當我們面臨高壓挑戰時自然會出現的反應，這並不代表能力的不足。<strong>失落的時候千萬別往心裡去</strong>，本文提供兩個不同層面的剖析幫助自己找到問題與著力點。通過調整挑戰、尋求適配的環境、專注於可改變的部分，並培養成長心態，找到更符合自己的成長路徑。每一段低谷，都有可能是未來成長的起點。</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f314e0a8d132" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[黃金圈原理與星巴克的忠誠危機：為何折扣和促銷挽救不了品牌信仰？]]></title>
            <link>https://michaelrevlis.medium.com/%E9%BB%83%E9%87%91%E5%9C%88%E5%8E%9F%E7%90%86%E8%88%87%E6%98%9F%E5%B7%B4%E5%85%8B%E7%9A%84%E5%BF%A0%E8%AA%A0%E5%8D%B1%E6%A9%9F-%E7%82%BA%E4%BD%95%E6%8A%98%E6%89%A3%E5%92%8C%E4%BF%83%E9%8A%B7%E6%8C%BD%E6%95%91%E4%B8%8D%E4%BA%86%E5%93%81%E7%89%8C%E4%BF%A1%E4%BB%B0-b12631097f68?source=rss-c7e3d6c91730------2</link>
            <guid isPermaLink="false">https://medium.com/p/b12631097f68</guid>
            <category><![CDATA[start-with-why]]></category>
            <category><![CDATA[starbucks-coffee]]></category>
            <category><![CDATA[the-golden-rule]]></category>
            <category><![CDATA[simon-sinek]]></category>
            <category><![CDATA[loyal-customer]]></category>
            <dc:creator><![CDATA[Michael Revlis]]></dc:creator>
            <pubDate>Sun, 11 Aug 2024 13:35:19 GMT</pubDate>
            <atom:updated>2024-08-11T13:43:54.581Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Yw2Z7_-WP00Sl95f3kbDtA.jpeg" /><figcaption>星巴克完全無視黃金圈原理，不跟忠誠顧客談品牌核心價值，反企圖用促銷等操弄手段挽回流失的顧客</figcaption></figure><p>日前星巴克股價大跌，而<a href="https://www.youtube.com/watch?v=zaPJWgbliQ8">星巴克 CEO Laxman Narasimhan 在 Squawk on the Street 節目的訪談</a>（來源: CNBC）中，主持人直接點出目前星巴克的問題是忠實客戶的流失以及偶爾性顧客的回訪減少。為了解決這些問題，Narasimhan 提出了星巴克的具體的對策，包括在星巴克app上提供限時促銷、推出新的產品組合、優惠活動等諸多價值等著客戶來體驗。然而，這些策略似乎並未成功挽回忠實客戶的流失，市場對此反應冷淡。</p><p>根據 Simon Sinek 的「黃金圈原理」，成功的企業必須從「為什麼」（Why）出發，這是企業的核心信念和使命。而「怎麼做」（How）和「做什麼」（What）應該圍繞這一核心來展開。Sinek 也點出許多企業過分仰賴的「操弄」手法，透過價格折扣、促銷、限時優惠等方式來吸引顧客，這些手法往往只能帶來短期的銷售增長，卻無法建立長期的品牌忠誠度。我們不應依賴這些操弄手法，因為它們吸引的是對價格敏感、忠誠度低的顧客，而非真正認同品牌價值的忠實客戶。</p><p>具體回到星巴克的情況，Narasimhan 的策略主要依賴操弄手法來試圖挽回流失中的「忠誠顧客」。然而，這些促銷和新產品的推出並未觸及星巴克的核心價值，也未能重建顧客對品牌的情感聯繫。根據 Sinek 的論述，操弄手段無法真正吸引忠實顧客，因為這些顧客的忠誠來源於對品牌「為什麼」的深刻認同，而非一時的優惠或促銷。星巴克依賴操弄手段，雖然可能短期內吸引了一些交易，但這些顧客往往缺乏忠誠度，容易被其他更具吸引力的折扣或促銷活動所吸引。因此，這樣的策略未能成功挽回真正的忠實客戶，反而可能使品牌陷入過度依賴價格戰和促銷手段的陷阱。</p><p>備註：看看其他人更多的評論：<a href="https://www.youtube.com/watch?v=G5pGk95r64k">https://www.youtube.com/watch?v=G5pGk95r64k</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b12631097f68" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[用系統思考看前英國首相 Liz Truss 的經濟政策]]></title>
            <link>https://michaelrevlis.medium.com/%E7%94%A8%E7%B3%BB%E7%B5%B1%E6%80%9D%E8%80%83%E7%9C%8B%E5%89%8D%E8%8B%B1%E5%9C%8B%E9%A6%96%E7%9B%B8-liz-truss-%E7%9A%84%E7%B6%93%E6%BF%9F%E6%94%BF%E7%AD%96-56ce2396678a?source=rss-c7e3d6c91730------2</link>
            <guid isPermaLink="false">https://medium.com/p/56ce2396678a</guid>
            <category><![CDATA[systems-thinking]]></category>
            <category><![CDATA[analysis-training]]></category>
            <category><![CDATA[economics]]></category>
            <dc:creator><![CDATA[Michael Revlis]]></dc:creator>
            <pubDate>Sun, 16 Jun 2024 10:51:15 GMT</pubDate>
            <atom:updated>2024-06-16T10:51:15.934Z</atom:updated>
            <content:encoded><![CDATA[<p>2022 年是英國經濟日益惡化的一年，通貨膨脹率飆升、失業率居高不下。年底剛新上任的英國首相 Truss 擔下了這個重責大任，市場期望她的計畫能挽救這個傳奇國度的最後一根救命稻草。但在 Truss 發表了一系列的經濟與稅務政策後，卻讓英國陷入更深的經濟困境。那麼，Truss 到底做了什麼，導致了這場經濟大崩盤？</p><p>首先 Truss 的計畫包括減稅刺激經濟、提供慷慨的能源補貼振興經濟，並協助家庭維持消費水準。乍看之下，這些政策將可以為民眾減少不少的負擔，尤其是在這個高通膨、薪資縮水的時期。但經濟是一個龐大寫複雜的系統，我們不能只看到自己的小確幸，見樹不見林，今天將以系統思考的角度來切入，帶大家看看這些政策將怎麼影響整個英國。</p><h4>減稅</h4><ul><li>減稅使大家不必把收入繳給政府，稅減得越多，手上可支配的資金越多，是一個正相關。覺得錢變多了也直接提升民眾滿意度。</li><li>可支配資金增加，進一步帶動股市房市。熱錢長期下來將引來通膨，雖是一個正相關，但卻有時間遞延性。且逐步升高的通膨也不會馬上引來民怨，而是累積到某個程度後民眾變開始受不了了，這裡也是一個有時間遞延的正相關。最終滿意度下降。</li></ul><h4>能源補貼</h4><ul><li>補貼的越多，意味著本來該支出的變少，則可支配的資金增加。承前述推演，短期增加滿意度，長期減少滿意度。</li></ul><h4>升息</h4><ul><li>升息則會使貸款要付出的利息增加，直接引想到大家可支配的金錢，進一步引來抱怨，降低滿意度。</li><li>但這也同時減少了熱錢進入市場，避免通膨。長期可以提升滿意度。</li><li>英國升息則意味的英國債券將支付更多利息給投資人，英債的吸引力變大。當資金流向債市時，則會減少流入其他市場的熱錢，這邊是一個負相關。透過吸收本來要流入其他市場的資金，最終達到打擊通膨的效果。長期可以提升滿意度。</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bnOVUSfZmewwd8FtYAGgWQ.jpeg" /></figure><p>圖的左半邊我們全部一起講</p><ul><li>一方面減稅越多，國家收入越少；另一方面，能源補貼意味著政府支出增加；加上升息意味著國債的利息更高，未來要付出去的利息更多。收入減少、支出增加之下，國家可調用的資金變少，未來能因應突發狀況的能力變差，故三者都降低了政府未來面對突發狀況的餘裕，國家財政穩定性降低，雖不是馬上，但卻是逐步地，這裡也有時間遞延效應。</li><li>而財政穩定性差意味著未來國家可能無法支付國債利息的風險變高，債券的信用評價可能被下修，進而降低投資人對英國國債的青睞。英債吸引力低則資金轉而投向市場。最終推升通膨，降低滿意度。</li></ul><p>在這邊我們可以先總結系統思考圖中的幾個要點：</p><ol><li>減稅、能源補貼短期可增加滿意度</li><li>然而減稅與能源補貼在長期可能會帶來通膨與國家財政的不穩定，最終引來民怨與滿意度下降</li><li>升息短期會使民眾增加還款壓力並引來民怨，但長期能抑制通膨</li><li>減稅、能源補貼、升息三個政策長期下來都給國家財政帶來負擔</li></ol><p>此時我們的系統思考圖已經完成了，只要再加上目標情境的特有條件，我們便能迅速依循圖中的脈絡找到每個事件最終將會帶來什麼影響。為什麼還要根據特定條件去做修改？其實就在於根據當下的狀況不同，各作用間產生的效果與程度也會不同。讓我們慢慢加一點只屬於當時英國的狀況進來：</p><ul><li>這次的減稅主要是富人稅的減稅比率最高，一般中產階級幾乎沒有減少，因此引來民怨，也沒有達到減稅短期可以帶來滿意度的效果。</li><li>英國當時已在高通膨的狀況下，已經在高通膨的民怨臨界值，時間遞延效應不會發揮，又看到政策未來將為引發更劇烈的通膨，苦還會更苦，直接進入低滿意度的結果。</li><li>這個世界是複雜的，雖然政策的對象是英國，但在全球化的影響下其他國家的政策也能產生蝴蝶效應。看到圖中下方紅色的，英國在升息的同時美國也在升息，而美國的升息程度則遠高於英國，這意味著美債比英債更有吸引力。美國升息降低了英債的吸引力（負相關）。投資人開始拋售手中的英鎊去兌換美元用以購買美債。英鎊被拋售使得英鎊貶值，意味著要花更多的英鎊才能買到來自（英）國外的商品，英鎊貶值通貨膨脹，最終減少滿意度。</li><li>英國有龐大的退休基金，他們平時為了避開利率漲跌的風險而有購買對沖風險的金融商品，這反而在一口氣大升息時被逼著賣債券補保證金，進而導致債券拋售潮。英債的拋售導致沒有人要英鎊，英鎊貶值，根據系統思考圖的脈絡，最後也是降低滿意度。</li></ul><p>結語</p><p>英國政府實施的減稅和能源補貼政策，增加了國家財政不穩定性和通貨膨脹的風險，且政策細節的制定與當時的經濟狀況，亦無法讓社會感受到短期的善意。另外未考量到國內退休金投資的特性與他國金融政策的影響，也讓政策在實行上多了許多不確定性。</p><p>後記</p><p>撇開這次 Truss 的經濟政策在英國的狀況，從圖中我們可以看到一般而言減稅與能源補貼（水、電、油、民生必需品等亦然）可以直接帶來滿意度的提升，但是其所造成的負面影響 — 通膨，則有時間遞延性，需要一段時間的發酵後問題才會浮出檯面，而此時執政者可能早就換人了，當初推行此政策的人可能早已搜刮到他所需要的政治影響力（執政滿意、選票），並將問題甩鍋給後人承擔。</p><p>相對的，在高通膨的狀況下，升息雖最終能解決通膨的問題，但短期則會面臨滿意度的下降。淪於民粹的政府只是一昧討好民意獲得短期的滿意度，而把問題留給未來。</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=56ce2396678a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[什麼是 iOS codesign、distribution certificate 和 provisioning profile? 更新或撤銷它們會有什麼影響?]]></title>
            <link>https://michaelrevlis.medium.com/%E4%BB%80%E9%BA%BC%E6%98%AF-ios-codesign-distribution-certificate-%E5%92%8C-provisioning-profile-%E6%9B%B4%E6%96%B0%E6%88%96%E6%92%A4%E9%8A%B7%E5%AE%83%E5%80%91%E6%9C%83%E6%9C%89%E4%BB%80%E9%BA%BC%E5%BD%B1%E9%9F%BF-8c1f9362ba6?source=rss-c7e3d6c91730------2</link>
            <guid isPermaLink="false">https://medium.com/p/8c1f9362ba6</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[provisioning-profile]]></category>
            <category><![CDATA[code-signing]]></category>
            <category><![CDATA[certificate]]></category>
            <dc:creator><![CDATA[Michael Revlis]]></dc:creator>
            <pubDate>Mon, 04 Apr 2022 15:49:29 GMT</pubDate>
            <atom:updated>2022-04-04T15:49:29.134Z</atom:updated>
            <content:encoded><![CDATA[<h3>什麼是 iOS code signing、Distribution Certificate 和 Provisioning Profile? 更新或撤銷它們會有什麼影響?</h3><p>iOS code signing 是每一個 iOS 開發者都碰過，但也都不太熟的，除了 Xcode 的 automatically manage signing 幫開發者處裡掉這些問題外，distribution certificate 和 provisioning profile 一年才過期一次，這類繁雜的事情要不是 CD 工具處裡掉，就是久久才人工處理一次，導致許多開發者對此似懂非懂，甚至某些公司分工分得很細，開發功能的人根本不用處理這些事。</p><p>本篇會用買一本書做為<strong><em>譬喻</em></strong>，來介紹 iOS 的 code signing 認證機制，並解釋 distribution certificate、provisioning profile 是什麼，並著重更多在實務上可能會遇到的應用題。觀念的部分多是<em>打個比方</em>，如果想看詳細且嚴謹的說明，非常推薦看<a href="https://pewpewthespells.com/blog/migrating_code_signing.html">這篇</a>:</p><p><a href="https://pewpewthespells.com/blog/migrating_code_signing.html">Migrating Code Signing Configurations to Xcode 8</a></p><h4>從買書來認識 iOS 認證機制</h4><p>現在資訊發達，買東西肯定是先上網查察評價。買書的話也是，除了看暢銷排行榜上有什麼外，可能還會看一下作者是誰。而除了作者外，還可能會翻一下推薦序是誰寫的，通常是相關領域的佼佼者，或是一些名人，顯然這本書受到了他們的青睞與肯定。</p><p>我們把開發者想像成作家，app 當作是創作出來的書籍。但在這個競爭激烈的市場中，消費者怎麼知道誰得書好看呢? 在 iOS 的世界裡，讀者(iOS 裝置，如 iPhone 手機)是認這本書的推薦序(distribution certificate)是誰寫的，如果是 Apple Certificate Authority 寫的，那肯定是嚴選好書，即便我不認識作者(開發者)，但我相信 Apple 的眼光。所以 iOS 的 code signing 讓每次 app 在安裝/開啟時，省去了一一確認開發者是誰的步驟，直接驗證 certificate 是否是 Apple 所核發的，因為相信 Apple 已經驗證過開發者是誰了，所以進而相信開發者。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/593/1*RJzvKztEaMQazqpnKD19Rw.png" /></figure><p>除了推薦序以外，書的內頁也會載明出版商、譯者、編輯、印刷版本等資訊，我們可以從這邊知道翻譯是否換人了? 現在是第幾版? 而 provisioning profile 扮演的就是這樣的功能，provisioning profile 上除了 app bundle ID (書名)、distribution certificate (推薦序)外，還有此 app 是否啟用推播、Apple Pay、Apple Sign-In 等功能。每次更新這些資訊，provisioning profile 也都會跟著更新，以記載最新的狀態。</p><p>另外在打包 app 的時後有一個動作叫做 singning binary，這好比是針對書的內容章節，幫它做一個目錄跟對應的頁數(hash of a file)，如果作者有增刪什麼內容，那這個目錄及頁數都會改變，所以只要對一下目錄上的頁數，跟實際上的頁數是否一致，就知道內容是否有被異動過了。</p><h4>renew/revoke or remove certificate 和 provisioning profile 會發生什麼事?</h4><p>先講結論：<strong>不會怎麼樣</strong>。隨時想更新、撤銷/刪除或不小心過期了都不會怎麼樣。不過還是有些但書，後面娓娓道來，細節可參考<a href="https://developer.apple.com/support/certificates/">官方說明</a>。</p><p>首先 distribution certificate 是 Apple 拍胸鋪認證的證明，承接上面的譬喻情境，Apple 說「這本書很好看，但我每年都會重新評選一次，所以請留意 certificate 的有效期間是哪一年間」。但已經印刷出去的書呢，它的推薦序不會因為時間到了就消失，書仍在書店中販售。所以在 AppStore 上的 app 仍可以被下載，也可以打開使用，不論當初的 certification 是過期、撤銷或是更新了，都不會影響已上架的 app。</p><p>但這有一個前提，那就是你是 Apple Developer Program。如果是 iOS Developer Enterprise Program 的話，則會讓所有已安裝的 app 都無法使用。Enterprise Program 為了滿足<strong>內部使用</strong>這個的需求，允許 app 不透過 AppStore 就可安裝到 iOS 裝置中。既然是企業內部使用，那企業就對這個 app 的控管負責，在這個機制下如果要安裝/開啟 app，第一件事都是去線上驗證此 app 中的 certificate 是否仍有效。所以有使用 MDM (Mobile Device Management) 來安裝 app 的朋友可要注意了! 可以看看<a href="https://developer.apple.com/library/archive/documentation/ToolsLanguages/Conceptual/DevPortalGuide/ManaginganiOSDistributionCertificate/ManaginganiOSDistributionCertificate.html">官方的相關說明</a>。(p.s. iOS Developer Enterprise Program的 distribution certificate 效期則相對地延長到三年)</p><p>但作者如果想要再版時，就不能再拿過期的推薦序(distribution certificate)放在新版的書中。故開發者必須要先更新 certificate 才可以在 AppStore 上發佈新的更版(開始印刷下一版)。</p><p>再來是 provisioning profile，在前面的譬喻中我們說它包含的是書的出版細節，試想一下一本暢銷書，再版了五六次，但會因為第八版出來了，前面的第七版就不能看了嗎? 並不會，所以 provisioning profile 不管更新多少次都不會對架上的 app 有任何影響。而我們平常在設定 app capabilities 的時候 Xcode 也會自動幫我們更心 provisioning profile，如果是在 Apple Developer Portal 上設定的話網站也會跳出相關的提示訊息:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*6qmnKBfJpp8lYcat.jpeg" /></figure><p>到這邊先整理一下，書的推薦序跟出版資訊都會印在書上，iOS app 的 distribution certificate 和 provisioning profile 也是，都會在打包 app 的時候一起包上去，所以這些東西會跟著 app 一起上到 AppStore，然後被使用者下載下來，如此一來不論是 certificate 還是 provisioning profile，日後開發者對它們的異動(更新、撤銷/移除)都不會對架上的 app 或已經安裝到使用者手機上的 app 有任何影響，使用者手機上的仍是當初我們打包時的那份 certificate、provisioning profile。</p><p>這是 iOS 的 code signing 機制，尤其是 certificate 的應用機制跟網頁的 certificate 不太一樣。工作上常遇到合作廠商其實並不是那麼瞭解，聽到 certificate 被異動到了氣得直跳腳；又或是新人一聽到被指派去處理 certificate 就戰戰兢兢、瑟瑟發抖。希望在讀完這篇文章後，能更清楚地了解 certificate 和 provisioning profile 所扮演的角色，以及異動它們意味著什麼。而準備要寫自動化工具的朋友，也能知道一般的 iOS Developer Program 與 iOS Developer Enterprise Program 是有所差異的，如果公司剛好同時兩種帳號都有，那就要格外留意了，要動 Enterprise Program 帳號下的 distribution certificate 要三思，它可是會影響到線上的 app 的。</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8c1f9362ba6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[一次看懂 Apple Pay 惱人的啟用設定和專有名詞]]></title>
            <link>https://michaelrevlis.medium.com/%E4%B8%80%E6%AC%A1%E7%9C%8B%E6%87%82-apple-pay-%E6%83%B1%E4%BA%BA%E7%9A%84%E5%95%9F%E7%94%A8%E8%A8%AD%E5%AE%9A%E5%92%8C%E5%B0%88%E6%9C%89%E5%90%8D%E8%A9%9E-a5f0d64d43fa?source=rss-c7e3d6c91730------2</link>
            <guid isPermaLink="false">https://medium.com/p/a5f0d64d43fa</guid>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[concept]]></category>
            <category><![CDATA[apple-pay]]></category>
            <dc:creator><![CDATA[Michael Revlis]]></dc:creator>
            <pubDate>Thu, 31 Mar 2022 08:17:18 GMT</pubDate>
            <atom:updated>2022-03-31T10:06:59.234Z</atom:updated>
            <content:encoded><![CDATA[<h4>Apple Pay 在商業應用場景上是極為便利的，拿出手機刷臉然後「逼！」一下就完成付款了。但 Apple Pay 在開發前的設定上卻是複雜的（沒錯！還沒到開發，開發反而很簡單）。本篇將用營業用計程車的方式來做譬喻，帶大家認識 Apple Pay 啟用設定會用到的各種東西。</h4><blockquote>這邊只講一個粗淺的觀念，設定的操作、畫面等請參 <a href="https://michaelrevlis.medium.com/apple-pay-%E7%94%B3%E8%AB%8B%E6%B5%81%E7%A8%8B%E6%89%8B%E6%8A%8A%E6%89%8B%E6%95%99%E5%AD%B8-3166dad321b4"><strong>Apple Pay 申請流程手把手教學</strong></a></blockquote><p><a href="https://michaelrevlis.medium.com/apple-pay-%E7%94%B3%E8%AB%8B%E6%B5%81%E7%A8%8B%E6%89%8B%E6%8A%8A%E6%89%8B%E6%95%99%E5%AD%B8-3166dad321b4">Apple Pay 申請流程手把手教學</a></p><p>先假設讀者是有自行上架經驗的 iOS 工程師，對 Apple Developer Account 和 app bundle ID 都不陌生。今天就要用開車來譬喻我們的 app：你新建了一個 app 專案，並跟 Apple 註冊了獨一無二的 app bundle ID，我們把它想成是你購買了一輛汽車。你可以在自家院子裡隨意開車，但如果要上路（上架到 AppStore）就需要考駕照，不過 Apple 的駕照不用考🎉，只要繳 100 鎂就可以拿到 Apple Developer Membership，只是這個東西要年繳…💸💸💸</p><p>有一天看到那麼多多元計程車在街上跑，心血來潮也想拿自己的車來營業，也就是讓 app 搭載 Apple Pay 功能並在上面做支付。看了一下 Apple 官方的說明，在啟用 Apple Pay 前還要去申請一個 merchant ID，我們可以把它想像成是營業用的車牌，要先申請到營業用車牌才可以在街上載人營業，不然就是白牌計程車，是違法的。</p><p>另外這個車牌除了要官方認證外，也是有效期的。所以我們要幫 merchant ID 申請 payment certificate，擁有了這個 certificate 就代表是 Apple 官方認可過的。而 certificate 的申請方式就是使用 CSR。</p><p>但可不是拿到一張新的營業用車牌，自己鎖到汽車上就可以到處趴趴走。還是要跟官方登記說你的某一台車要使用這個營業用車牌，這個動作就是在我們 app ID 的 capabilities 中啟用 Apple Pay，並且指定是使用哪一個（或多個）merchant ID。</p><p>做完了上述的設定，那相關的文件也會要跟著更新，這樣未來臨檢的時候才有最新的資料可以核對。這也是每次我們異動 app 的 capabilities 時，provisioning profile 都需要更新，且要用新的 provisioning profile 打包 app 並送審，這樣新的 app 上才可以使用 Apple Pay 了。</p><p>上面用汽車、營業用車牌等譬喻來讓大家認識 Apple Pay 整個申請與設定的概念，以下把流程上會遇到的專有名詞一一作解釋：</p><p><strong>merchant ID</strong>：被譬喻成營業用車牌。實際上它用來辨識 Apple Pay 的收款對象是誰。最簡單的設定方式就是一個 app 對應一個 merchant ID，merchant ID 的取名上更可以用 merchant. + bundle ID這樣的規則，容易分辨。但也可根據不同的商業面用途而有多種組合：</p><p><strong>每個 app 綁定多組 merchant ID</strong>：例如你的 app 是一個商城，上面有 A, B, C 三個賣家，因各自的收款對象、可接受的國際信用卡組織不同等商業面需要，故有必要分開來設定。則可以申請三個不同的 merchant IDs，並在專案的程式碼中針對不同的 merchant ID 指定不同的國際信用卡組織 supportedNetworks（ex. .visa, .masterCard），或是可接收的收單類型merchantCapabilities（ex. .capability3DS, .capabilityDebit）</p><p><strong>每個 merchant ID 被綁定在多個 app 上</strong>：例如你的公司針對不同客群的使用習慣，共出了兩個 app，此時就可以只申請一組 merchant ID，並讓這兩個 app 都綁定同一組 merchant ID。又或者你也在網頁上實作了 Apple Pay，則網頁跟 app 的 merchant ID 也可以使用同一個。</p><p><strong>payment certificate</strong>：被譬喻成營業用車牌的認證有效期限。實際上也的確是類似的功能，這個 payment certificate 是開發者向 Apple 申請的，每張 certificate 的有效期限是 <strong>25 個月</strong>（兩年要更新一次，並給你一個月的緩衝期）。官方也為了避免一個月緩衝不夠，允許一張 merchant ID 底下同時存在兩張 payment certificates，但只有一張會是 active 的狀態，讓有效期間互相重疊，當第一張 active 的 certificate 過期時，就會自動啟用第二張 certificate。喜歡做自動化的朋友，也可以定時就產一張 payment certificate 並把較舊的那一張換掉。（流程細節：revoke 舊的 certificate，第二張 certificate 自動變成 active，再把新的 certificate 加到 merchant ID 中，保持仍有兩張 certificates）。</p><p><strong>CSR</strong>：要跟 Apple 申請 payment certificate 的 CSR，跟申請 app distribution/development certificate 的 CSR 是<strong>不一樣</strong>的！申請 Apple Pay payment certificate 的 CSR 要特別指定是 ECC 演算法、256 bit 密鑰。<a href="https://help.apple.com/developer-account/#/devbfa00fef7">官方說明</a>也有特別強調這個差異。</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a5f0d64d43fa" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Apple Pay 申請流程手把手教學]]></title>
            <link>https://michaelrevlis.medium.com/apple-pay-%E7%94%B3%E8%AB%8B%E6%B5%81%E7%A8%8B%E6%89%8B%E6%8A%8A%E6%89%8B%E6%95%99%E5%AD%B8-3166dad321b4?source=rss-c7e3d6c91730------2</link>
            <guid isPermaLink="false">https://medium.com/p/3166dad321b4</guid>
            <category><![CDATA[merchant-processing]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[apple-pay]]></category>
            <category><![CDATA[tutorial]]></category>
            <dc:creator><![CDATA[Michael Revlis]]></dc:creator>
            <pubDate>Thu, 31 Mar 2022 08:15:34 GMT</pubDate>
            <atom:updated>2022-04-04T15:52:16.808Z</atom:updated>
            <content:encoded><![CDATA[<p>Apple Pay 的一些相關知識可以先參考 <a href="https://michaelrevlis.medium.com/%E4%B8%80%E6%AC%A1%E7%9C%8B%E6%87%82-apple-pay-%E6%83%B1%E4%BA%BA%E7%9A%84%E5%95%9F%E7%94%A8%E8%A8%AD%E5%AE%9A%E5%92%8C%E5%B0%88%E6%9C%89%E5%90%8D%E8%A9%9E-a5f0d64d43fa"><strong>一次看懂 Apple Pay 惱人的啟用設定和專有名詞</strong></a>。</p><p><a href="https://michaelrevlis.medium.com/%E4%B8%80%E6%AC%A1%E7%9C%8B%E6%87%82-apple-pay-%E6%83%B1%E4%BA%BA%E7%9A%84%E5%95%9F%E7%94%A8%E8%A8%AD%E5%AE%9A%E5%92%8C%E5%B0%88%E6%9C%89%E5%90%8D%E8%A9%9E-a5f0d64d43fa">一次看懂 Apple Pay 惱人的啟用設定和專有名詞</a></p><blockquote>本篇只講流程操作：<br>Step 1: 註冊 merchant ID<br>Step 2: 產出 CSR（手動 or openssl） <br>Step 3: 用 CSR 向 Apple 申請 Apple Pay payment certificate<br>Step 4: 在欲使用 Apple Pay 的 app ID 上綁定 merchant ID<br>Step 5: 更新 Xcode 專案（optional）</blockquote><h4>Step 1: 註冊 merchant ID</h4><p>向 Apple 申請一組用來代表商家可接受付款的 ID。先登入 Apple Developer Account，找到 Certificates, Identifiers &amp; Profiles，再選擇 identifiers，此時右上角選 Merchant IDs 會看到以下的畫面，點選 Register a Merchant ID 就可以註冊 merchant ID 了。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*crbMS_ZX2N_6c5NtB6xWvw.png" /><figcaption>path: Apple Developer Account &gt; Certificates, Identifiers &amp; Profiles &gt; identifiers &gt; Merchant IDs &gt; Register a Merchant ID</figcaption></figure><p>merchant ID 的命名上是有規範的，必須要以 merchant. 開頭，例如：merchant.demoapp.mycompany.com。順帶一提， description 是不能有特殊符號，底線 _也不行。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mdjjWlCfFQpwns0OOBmakg.png" /></figure><p>另外說明一下，每個 Apple 帳號是可以申請多組 merchant ID 的，其實務上的應用可能如下：</p><p><strong>每個 app 可以綁定多組 merchant ID</strong>：例如你的 app 是一個商城，上面有 A, B, C 三個賣家，因各自的收款對象、可接受的國際信用卡組織不同等商業面需要，故有必要分開來設定。則可以申請三個不同的 merchant IDs，並在專案的程式碼中針對不同的 merchant ID 指定不同的國際信用卡組織 supportedNetworks（ex. .visa, .masterCard），或是可接收的收單類型merchantCapabilities（ex. .capability3DS, .capabilityDebit）</p><p><strong>每個 merchant ID 可以綁定在多個 app 上</strong>：例如你的公司針對不同客群的使用習慣，共出了兩個 app，此時就可以只申請一組 merchant ID，並讓這兩個 app 都綁定同一組 merchant ID。又或者你也在網頁上實作了 Apple Pay，則網頁跟 app 的 merchant ID 也可以使用同一個。</p><h4>Step 2: 產出 CSR (certificate signing request)</h4><h4>option 1: 手動操作</h4><p>打開 Keychain &gt; 左上角鑰匙圈存取 &gt; 憑證輔助程式 &gt; 從憑證授權要求憑證</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0opuRQFX9SUpC7jCHxrvpg.png" /></figure><p>輸入電子郵件、一般名稱，選擇 儲存到磁碟、指定密鑰配對資訊</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tEAmCuMteu-AgCjMVTqSUQ.jpeg" /></figure><p>指定儲存的檔名、位置</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/666/1*9hzRWtNe9IJPGFs8ExeOnQ.jpeg" /></figure><p>選擇密鑰配對資訊，再按下「繼續」後就完成了<br>* 密鑰大小：256 bit<br>* 演算法：ECC</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/862/1*tdPWMVFLHq-ya9lUw-HjeA.png" /></figure><h4>option 2: command line 操作 (openssl)</h4><p>下述指令會產出一個使用 ECC 演算法（prime256v1）的 private key（產出的檔名叫 <em>private.key</em>）</p><pre>openssl ecparam -out private.key -name prime256v1 -genkey</pre><p>使用剛剛得到的 <em>private.key</em> 去產出一個大小為 256 bit 的 CSR（產出的檔名叫 request.csr）</p><pre>openssl req -new -sha256 -key private.key -nodes -out request.csr</pre><h4>Step 3: 用 CSR 向 Apple 申請 Apple Pay payment certificate</h4><p>再次來到 Apple Developer Account &gt; Certificates, Identifiers &amp; Profiles &gt; identifiers &gt; Merchant IDs 點選剛剛在 Step 1 註冊的 merchant ID，會看到如下畫面，選擇 Create Certificate</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pA1mXLrVwdq_xPW98UJzOQ.png" /></figure><p>如果是第一次幫這個 merchant ID 做設定的話，會跳出Will payment associated with ... be processed exclusively in China?，這指的是當前的 merchant ID 相關的付款只在 China 使用，根據你自己的需求，如果是在 China 以外的地區皆要選擇 NO 。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mVcm46E9Ja5lQAYTmPjWzw.png" /></figure><p>上傳剛剛 Step 2 產出的 CSR。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r5rSj2Wa3cyeFTLipWupQQ.png" /></figure><p>接著順著流程走 Continue &gt; Download &gt; Done，就可以下載到 Apple Pay payment certificate，檔名應為預設的 <em>apple_pay.cer</em>。同時我們也可以在 Apple Developer Account &gt; Certificates, Identifiers &amp; Profiles &gt; Certificates 可看到多一張 Name 為 Step 1 產的 Merchant ID 的 certificate，且它的 Type 是 Apple Pay Payment Processing。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ilhm9BJ7JDRDp6t2HNKcSw.png" /></figure><h4>Step 4: 在欲使用 Apple Pay 的 app ID 上綁定 merchant ID</h4><p>在 Apple Developer Account &gt; Certificates, Identifiers &amp; Profiles &gt; Identifiers &gt; App ID 找到欲使用 Apple Pay 的 app，點進去後在 Capabilities 這邊我們要把 Apple Pay Payment Processing 給 enabled。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/775/1*cPK_GoyF-gvq5t3TutbxUA.png" /></figure><p>打勾後右邊的 Configure 會變成 Edit，注意這邊的 Enabled Merchant IDs 旁邊括號的數字是 0，意味著這個 app 雖然有啟用 Apple Pay，但卻沒有綁定任何的 merchant ID。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*56mpvZKSMJZlfxSnam_SZQ.jpeg" /></figure><p>點擊 Edit 後就可以選擇此 app 想要綁定的 merchant ID（複選）。這邊也是 Step 1 中所說的，如果一個 app 想要有多組 merchant IDs，就是在這裡設定。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1007/1*5eeQlqhUgqLRtBRtNUmyYw.png" /></figure><p>按下 Continue 後會出現以下這個警告，別緊張。由於 app ID 的 capability 變了，所以連帶也要更新 provisioning profile，並用新的 provisioning profile 打包新的 app 並送審，如此以來新版的 app 使用者才可以使用者個功能。所以這邊我們就放心地按下 Confirm 就好。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4hcjr62zZQDhICXaQG2o4g.jpeg" /></figure><p>至於關於 signing, CSR, certificate, provisioning profile 之間的關係，<a href="https://pewpewthespells.com/blog/migrating_code_signing.html">這邊有詳盡的說明</a>。或參考我另一篇輕鬆一點的介紹文章:</p><p><a href="https://michaelrevlis.medium.com/%E4%BB%80%E9%BA%BC%E6%98%AF-ios-codesign-distribution-certificate-%E5%92%8C-provisioning-profile-%E6%9B%B4%E6%96%B0%E6%88%96%E6%92%A4%E9%8A%B7%E5%AE%83%E5%80%91%E6%9C%83%E6%9C%89%E4%BB%80%E9%BA%BC%E5%BD%B1%E9%9F%BF-8c1f9362ba6">什麼是 iOS codesign、distribution certificate 和 provisioning profile? 更新或撤銷它們會有什麼影響?</a></p><p>順帶一提，沒有指定 merchant 就代表這個 Apple Pay 沒有處理收款的對象，就像是你買了汽車（app ID），申請了營業用車牌（merchant ID），但卻沒有向主管機關（Apple）登記這個車牌是要給這部汽車用的，所以是無法上路載客。故如果沒有綁定 merchant ID，或是 merchant ID 中沒有有效的 payment certificate 的話，你的 app 雖然還是可以叫出 Apple Pay payment sheet，但在使用者同意付款授權後會看到以下的錯誤訊息（還是可以硬開車上路，但遇到臨檢就會被攔下來）：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/890/1*sbb1csCJVXRLkYNOda2Wbw.jpeg" /></figure><h4>Step 5: 更新 Xcode 專案（optional）</h4><p>這個步驟其實是非必要的，因為一般情況下不論是使用 Xcode 的 automatically manage signing 或是使用其它 signing 自動化工具（如 fastlane），只要確保 archive 時會使用新的 provisioning profile 即可。至於 Xcode 專案的 capabilities 有沒有更新則沒有關係。但如果你想要在 Xcode 上先試跑 Apple Pay 看看的話，就還是得設定。</p><p>打開 Xcode 並找到要使用 Apple Pay 的 target，選擇 Signing &amp; Capabilities，由於 capabilities 預設是沒有 Apple Pay 的所以我們要新增它，並且輸入 Step 1 產的 merchant ID。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YVkTLD8yhzMpur65u6YwYA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/721/1*DbJW6JOQwJUNNZjEG_nesA.png" /></figure><p>另外剛剛 Step 4 最後面有提示我們 provisioning profile 會被更新，所以我們也要去 Apple Developer Account &gt; Certificates, Identifiers &amp; Profiles &gt; Profiles 中找到我們的 provisioning profile，下載下來並 import 到 Xcode 專案中。</p><p>以上就是如何產生、設定 Apple Pay 的 merchant ID, payment certificate , capabilities 和 provisioning profile。</p><p>至於想看官方的流程說明可以參考：</p><p><a href="https://developer.apple.com/library/archive/ApplePay_Guide/Configuration.html#//apple_ref/doc/uid/TP40014764-CH2-SW1">https://developer.apple.com/library/archive/ApplePay_Guide/Configuration.html#//apple_ref/doc/uid/TP40014764-CH2-SW1</a></p><p><a href="https://help.apple.com/developer-account/#/devb2e62b839?sub=dev103e030bb">https://help.apple.com/developer-account/#/devb2e62b839?sub=dev103e030bb</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3166dad321b4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What are the components of a URL? Why things should be encoded? What does it look likes in Swift?]]></title>
            <link>https://michaelrevlis.medium.com/what-are-the-components-of-a-url-why-things-should-be-encoded-what-does-it-look-likes-in-swift-55ae6e5992c3?source=rss-c7e3d6c91730------2</link>
            <guid isPermaLink="false">https://medium.com/p/55ae6e5992c3</guid>
            <category><![CDATA[urlcomponents]]></category>
            <category><![CDATA[encoding]]></category>
            <category><![CDATA[url]]></category>
            <category><![CDATA[querystring]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Michael Revlis]]></dc:creator>
            <pubDate>Wed, 16 Mar 2022 14:44:05 GMT</pubDate>
            <atom:updated>2022-03-16T14:45:51.364Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*KM4SSYJhP4vihj-G.jpg" /><figcaption>source: <a href="https://www.dreamstime.com/crop-guy-sealing-box-unrecognizable-young-man-using-sticky-tape-to-seal-carton-relocating-new-flat-image123825751">https://www.dreamstime.com/crop-guy-sealing-box-unrecognizable-young-man-using-sticky-tape-to-seal-carton-relocating-new-flat-image123825751</a></figcaption></figure><p>Most of the beginners didn’t know why the value of a query string needs to be encoded or even didn’t know it should be encoded. Yes, it just looks the same if there’s no disallowed character and if there is, most of the browsers take good care of these, making it friendly for human reading.</p><p>If you are familiar with URLs, skip Question 1.</p><h3>Question 1: What are the components of a URL?</h3><p>If you are wondering what a URL is, and you look it up on the Internet. You may find out this <a href="https://www.ibm.com/docs/en/cics-ts/5.1?topic=concepts-components-url">document</a> explaining what a URL is by IBM. That’s taking this as an example.<strong> A URL is composited of a scheme, host, and path, and sometimes with additional information like query strings or a fragment.</strong> In this case, “<em>HTTPS”</em> is the <strong>scheme</strong> that means it’s used on the Internet and follows related protocols. “<em>www.ibm.com</em>” is the <strong>host</strong>, telling us who owns this resource. And “<em>/docs/en/cics-ts/5.1</em>” is the <strong>path</strong>. It probably saying that this resource is a document in English describing something about cics, whatever it means. Truly, it is a document about IBM’s CICS(Customer Information Control System) Transaction Server in version 5.1.</p><blockquote><a href="https://www.ibm.com/docs/en/cics-ts/5.1?topic=concepts-components-url">https://www.ibm.com/docs/en/cics-ts/5.1?topic=concepts-components-url</a></blockquote><p><strong>Considering URL as a way to transfer information.</strong> We can obtain a lot of information by just reading a URL. But sometimes scheme, host, and path are just not enough. And it comes up with <strong>query strings</strong>, a series of key-value pair data with a “<strong>&amp;</strong>” delimiter, revealing more information to us. Here we can just recognize the query string on the above URL as “the topic is the concepts of URL components”. A query string always comes after the path with a “<strong>?</strong>” delimiter. And query strings can be plenty and complex, just like the one below. It reveals information about Google AD tracking (utm_medium, utm_campaign, and utm_source), FB AD tracking (FB CLID), and it seems like there’s a sorting feature on this page.</p><blockquote><a href="https://www.timberland.com.tw/v2/official/SalePageCategory/421382?utm_medium=0304-0314&amp;utm_source=FB_CA&amp;utm_campaign=SS22VIP&amp;fbclid=IwAR2yl_Rgu3QtcFinh0kaRAk4mMEKPISgkNrC-mMUDbL8qDTD0PsxJRXmyMs&amp;sortMode=Curator">https://www.timberland.com.tw/v2/official/SalePageCategory/421382?utm_medium=0304-0314&amp;utm_source=FB_CA&amp;utm_campaign=SS22VIP&amp;fbclid=IwAR2yl_Rgu3QtcFinh0kaRAk4mMEKPISgkNrC-mMUDbL8qDTD0PsxJRXmyMs&amp;sortMode=Curator</a></blockquote><p>If you are dealing with apps, you might see a custom URL scheme like below. For further information about the iOS custom URL scheme, see <a href="https://developer.apple.com/documentation/xcode/defining-a-custom-url-scheme-for-your-app">this article</a>. Here “<em>twitter</em>” is the scheme, telling the operating system to find an app defined as “<em>twitter</em>”. Because it’s a custom URL scheme, this URL might function as making a post with the message “hello world”.</p><blockquote>twitter://post?message=hello%20world</blockquote><h3>Question 2: Why things should be encoded in the query string?</h3><p>There’re symbols with specific meanings in a URL (“<em>:</em>”, “<em>/</em>”, “<em>?</em>”, “<em>&amp;</em>”, “<em>=</em>”, etc.). And here comes the question: What if I need a “?” as the value of a query string? What if I need a URL as the value of a query string? Something like “<em>redirect_url=https://medium.com</em>”. Moreover, what about blank spaces or Chinese characters? The symbols just mess up together.</p><p>Imagine that you are buying an iPhone and a Google Pixel on Amazon. The package just arrived and you can’t wait to open it. Inside the package, there are two boxes, a box with an iPhone inside it and a box with Google Pixel inside it. You open both the minute boxes and there are two different types of chargers but you won’t be confused with them. Because the iPhone charger is inside the iPhone box, and the other one, too.</p><p>In the story above,<strong> you can think of “encoding it” as putting things into a box.</strong> Therefore, you won’t get an iPhone along with a manual of Google Pixel or missing a charger. And this is exactly what encoding a query string wants to achieve. This is why you are seeing “<em>hello%20world</em>” instead of “<em>hello world</em>” in the previous case, and “<em>%E4%BD%A0%E5%A5%BD</em>” instead of “<em>你好</em>” in the case of Chinese characters.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*6xgW08_7O47m_IAa.JPG" /><figcaption>source: <a href="https://zh.wikipedia.org/zh-tw/File:IPhone_4_box_no_lid.JPG">https://zh.wikipedia.org/zh-tw/File:IPhone_4_box_no_lid.JPG</a></figcaption></figure><h3>Question 3: What does it look likes in Swift?</h3><p>It’s time for coding. Let’s take a look at a more complex scenario:</p><ol><li>There’re two apps, FlashPay, and FlashBuy.</li><li>A customer is shopping on FlashBuy and will pay with FlashPay. That is, FlashBuy will open FlashPay via a custom URL scheme:<br>“flashpay://pay?price={price}&amp;redirect_link={a_redirect_link}”</li><li>FlashBuy has defined another custom URL scheme for continuing the checkout process: <br>“flashbuy://checkout?trade_id={trade_id}”</li><li>After the payment is authorized on FlashPay, it will try to open the link from <em>redirect_link</em> with an additional query string, authorized token.<br>“a_redirect_link?token={token}”</li><li>When FlashBuy is opened by FlashPay, it will capture the authorized token and verify the result.</li></ol><p>Let’s see what FlashBuy should do. First, prepare a redirect link for FlashPay to open itself, that is “<em>flashbuy://checkout?trade_id=TID123456</em>”. And before we put this link into query string <em>redirect_link, let’s </em>“package” it first by encoding the entire link.</p><p>I suggest using <a href="https://developer.apple.com/documentation/foundation/urlcomponents">URLComponents</a> to create a URL in Swift. It does all the trivial matters and frees us from possible typo mistakes. To create a query string, use <a href="https://developer.apple.com/documentation/foundation/urlqueryitem">URLQueryItem</a> and assign it to URLComponents’s queryItems. URLComponents will automatically encode the query for us. As you can see, all the symbols are added automatically.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9c04e12187ed62f30d56156dbf7d1ff8/href">https://medium.com/media/9c04e12187ed62f30d56156dbf7d1ff8/href</a></iframe><p>If you don’t want the automatic encoding feature, use percentEncodedQueryItems or <a href="https://developer.apple.com/documentation/foundation/urlcomponents/1780305-percentencodedquery">percentEncodedQuery</a> instead.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/235fc51d9c84f2bdfa38765531f0a650/href">https://medium.com/media/235fc51d9c84f2bdfa38765531f0a650/href</a></iframe><p>Now, when we put the redirectLink to linkToFlashPay as a query item, it will be encoded by URLComponents, of course, automatically. Imagine the encoded redirectLink as a sealed box with an iPhone (the basic URL) and a manual (the <em>trade_id</em> query string) inside it. And the linkToFlashPay is the Amazon delivery package with your iPhone (the <em>redirect_link</em> query string), and Google Pixel (the <em>price </em>query string). And the logistic company is ready to delivery the package to you.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6001664194c82d0aca03a7fd13d5f70b/href">https://medium.com/media/6001664194c82d0aca03a7fd13d5f70b/href</a></iframe><p>When FlashPay receives a custom URL scheme from FlashBuy, it will capture the redirect_link from the URL scheme and decode it. Here, URLComponents also do the decode trick for us automatically.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/db7d674fe219209d7ef93742cf31a8d4/href">https://medium.com/media/db7d674fe219209d7ef93742cf31a8d4/href</a></iframe><p>After some processing, FlashPay would like to append a token to the redirect_link. Please <strong>DON’T</strong> add the query string by just appending a string like this “?key1=value1&amp;key2=value2”. It’s not only because the string might need to be encoded but also you are not sure whether there’s any query string that already exists or not. I’ve seen a lot of services dealing with a URL in this way. <strong>It’s frail!</strong> Don’t assume any precondition unless it’s defined. Consider flexibility for your codes. As the tests below, the token query appended to the URL is mixed up with the existed query.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5f1ae737eed94c50186597959f49c009/href">https://medium.com/media/5f1ae737eed94c50186597959f49c009/href</a></iframe><p>Let’s all. Hopes you have a better understanding of a URL and how to code it in a modern way. Happy coding.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=55ae6e5992c3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[淺談UICollectionViewCompositionalLayout 的結構與如何閱讀]]></title>
            <link>https://michaelrevlis.medium.com/%E6%B7%BA%E8%AB%87uicollectionviewcompositionallayout-%E7%9A%84%E7%B5%90%E6%A7%8B%E8%88%87%E5%A6%82%E4%BD%95%E9%96%B1%E8%AE%80-85fcda766392?source=rss-c7e3d6c91730------2</link>
            <guid isPermaLink="false">https://medium.com/p/85fcda766392</guid>
            <category><![CDATA[uicollectionview]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[compositional-layout]]></category>
            <dc:creator><![CDATA[Michael Revlis]]></dc:creator>
            <pubDate>Tue, 18 Jan 2022 11:04:37 GMT</pubDate>
            <atom:updated>2022-01-18T18:39:08.493Z</atom:updated>
            <content:encoded><![CDATA[<p>iOS 13 以後我們可以用 UICollectionViewCompositionalLayout 來更輕鬆地做到某些畫面的呈現，算是便利開發者的一大福音，最大的亮點大概就是：</p><ul><li><strong>易於閱讀的 layout 設定，先見林再見樹，算是 DX 的一個優化</strong><br>過往的 UICollectionViewDelegateFlowLayout 是功能集中設定的，例如所有的 section inset 都放在一起、所有的 header 放在一起。但是現實中我們可能更在意的是某個 section 他自己的 inset、header 設定，使用 compositional layout 就不用在多個 delegate 間反覆跳著看才能看到全貌，可以聚焦在某個目標區塊的呈現。</li><li><strong>在一個垂直滑動的 CollectionView 中實踐左右滑動的內容</strong><br>終於不用在 CollectionViewCell 中再塞一個 CollectionView 了，不只結構扁平化，資料與行為的傳遞也扁平了。</li></ul><pre>本篇只會簡單講到 compositional layout 的基礎結構、可以做到什麼、該如何閱讀它。其餘更細節的探究會陸續用別的篇幅說明。</pre><p>接下來會直接帶大家看 code，以下是一個簡單的 UICollectionView 設定，閱讀上建議 <strong>從下面往上 </strong>開始看、<strong>從大的畫面看到小的</strong>：collection view -&gt; collection view layout -&gt; section -&gt; group -&gt; item -&gt; size， 但在 init 的結構上則會是反過來由小到大。如果是複雜的結構可能還會有多個 section、group，但只要好好的命名，就能幫助未來維護的人（也可能就是自己）快速找到對應的畫面區塊。也由於這樣的組成結構，讓我們在開發、閱讀的時候可以聚焦在某個 section，或某個 group 上，而不用在多個 delegate 中穿梭，再配上 switch-case, if-else 才能找到某個特定的畫面，所有跟某個區塊相關的設定都集中在這裡。</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cca74245d1b0d3bd409f069a0d5401f3/href">https://medium.com/media/cca74245d1b0d3bd409f069a0d5401f3/href</a></iframe><p>在第 12 行我們先用 UICollectionViewCompositionalLayout 來初始化我們的 UICollectionView。往上看到第 11 行，發現 compositional layout 的 init 是需要先設定 NSCollectionLayoutSection 的。<strong>Demo code 1</strong> 中這個 collection view 中有一個 section，但如果我們想要多個 section 呢？這邊就直接往下看到<a href="https://developer.apple.com/documentation/uikit/uicollectionviewcompositionallayout">官方的文件</a>，原來除了單個 section 的 init 外，還可以透過 sectionProvider 來創建多個 sections 的設定，甚至如果希望 CollectionView 長得像 TableView 的話，還可以使用 list(using:)，詳細的討論之後再另外寫一篇補上。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/759/1*9o4lsW3nfwGB6Hc1ibdfog.jpeg" /><figcaption>Apple Developer Documentation — UICollectionViewCompositionalLayout</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/722/1*hcfVLTf1mO7Ht_QsEmmH0w.jpeg" /><figcaption>Apple Developer Documentation — UICollectionViewCompositionalLayout</figcaption></figure><p>接著看到第 10 行 NSCollectionLayoutSection 的初始化。這邊看到了不一樣的東西：<strong>NSCollectionLayoutGroup</strong>，這個就是 compositional layout 引入的新構想，在 section 與 item 中插入了 group 這一個階層，由 group 來決定 item 的呈列方式，藉此達到垂直滑動的 CollectionView 也可以有左右滑動的內容，有別於以往 item 的呈列方式是跟著 CollectionView 是一起的。更進階一點，我們甚至可以 item 和 group 一起塞到另一個 group 中，以做到更複雜的排列。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/676/1*VS3qRuFMQ1e0_whXlQjanA.png" /><figcaption>Apple Developer Documentation — UICollectionViewCompositionalLayout</figcaption></figure><p>第 7 行我們來看看這個 NSCollectionLayoutGroup，從官方文件可以看到他有五個 init 方式，分別是可以決定它的排版是水平、垂直或自訂。這裡我們可以從 Xcode 的文件看到官方圖文並茂的解釋，且原來水平、垂直排版還可以指定一個 group 要被多少個 item 去均分！省去我們手動計算一屏畫面中要顯示多少個 item。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z-q_A_rgWcsfbAyqH5zwGA.jpeg" /><figcaption>Xcode — NSCollectionLayoutGroup</figcaption></figure><p>舉個例子，在 <strong>Demo code 2</strong> 中，我們想要讓畫面上一次呈現兩個半的 items（假設 UICollectionView 是滿版、item 之間也沒有 spacing），<strong>option1</strong> 比較是傳統上我們會寫的：指定 item 的寬度是 collection view 總寬的 1/3（這裡因為是用 compositional layout，所以嚴格來說是 group 的 1/3）；但我們也可以考慮 <strong>option2</strong> 用 horizontal(layoutSize:, subitem:, count:) 並指定 count: 3。雖然結果一樣，但在閱讀上還是有差異的，看各位開發者如何取捨。另外值得一提的是這兩個 compositional layout 的做法因為都是讓 item 去跟 group 作對齊，而 group 真正的大小又是它自己的 contentInsets、其 section 的 contentInsets、interGroupSpacing 等設定得結果。跟過去可能要在 collectionView(_:, layout:, sizeForItemAt:) 中自己手動計算 item 寬方面簡潔許多，不用費力找出對應的 section 和當前 item 的 contentInsets、spacing 再一一減去，或有一堆 magic number 造成維運與閱讀上的困擾。</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7c5dd0249ac4f3f5d9a60318e09ab514/href">https://medium.com/media/7c5dd0249ac4f3f5d9a60318e09ab514/href</a></iframe><p>回到 <strong>Demo code 1</strong> 第六行的 NSCollectionLayoutItem 就是整個 collection view 中最小最基礎的畫面元件，可以是 cell、header、footer。且我們可以指定 item 的 size，分別針對寬、高設定，看是要指定一個絕對值 .absolute(44)；想要內容可以 run time 改變的就用 .estimated(44)；如果是要對齊其容器(也就是 group)寬就用 .fractionalWidth(0.2)；要對齊容器高 .fractionalHeight(0.2) 。</p><p>以上就是一個 compositional layout 的基本結構介紹。<strong>Demo code 1</strong> 的內容實作出來跟一個一般的 UICollectionView 其實是一樣的，並沒有用到新的花招 XD 但也是想藉此讓大家看看最單純的 compositional layout 會怎麼寫、又該怎麼閱讀它。</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=85fcda766392" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[深入探討UILabel確切行數. Calculating the exact number of lines of a UILabel]]></title>
            <link>https://michaelrevlis.medium.com/%E6%B7%B1%E5%85%A5%E6%8E%A2%E8%A8%8Euilabel%E7%A2%BA%E5%88%87%E8%A1%8C%E6%95%B8-calculating-the-exact-number-of-lines-of-a-uilabel-23541477bf60?source=rss-c7e3d6c91730------2</link>
            <guid isPermaLink="false">https://medium.com/p/23541477bf60</guid>
            <category><![CDATA[nsattributedstring]]></category>
            <category><![CDATA[uilabel]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Michael Revlis]]></dc:creator>
            <pubDate>Sun, 02 Jan 2022 15:46:32 GMT</pubDate>
            <atom:updated>2022-01-02T15:46:32.156Z</atom:updated>
            <content:encoded><![CDATA[<p>最近晚輩遇到了一個需求「某段文字要根據內容決定顯示的高度，一行或兩行，但最多僅顯示兩行，超過的話下方要長出一個『顯示更多』的按鈕，點擊後再展開...」</p><p>先不討論這樣的設計到底是不是一個 mobile app 適用的體驗，既然需求開出來了工程師就要去解決它。晚輩找了幾篇相關的文章，都能解決這樣的需求，但為了避免知其然而不知其所以然，這裡還是把詳細的程式碼一一解釋一下，並進一步做延伸思考。</p><p><a href="https://stackoverflow.com/a/43002072">這篇 StackOverFlow</a> 是我覺得寫得比較完整的，以它為範例進行改寫:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4164a155baece5b4207e929f71dd2342/href">https://medium.com/media/4164a155baece5b4207e929f71dd2342/href</a></iframe><p>第6行是取得字體大小，避免因為給定了 UILabel 其他字型字體設定，跟預設有差異而導致計算上的誤差。</p><p>第9行是要指定這個 UILabel 的大小，因為我們想要知道的是有多少行高，所以寬度就以自身寬為準，高度給定 CGFloat.greatestFiniteMagnitude，顧名思義就是給了一個很大很大的值(<a href="https://developer.apple.com/documentation/coregraphics/cgfloat/1845207-greatestfinitemagnitude">官方說明看此</a>)，讓 UILabel 可以想長多高就多高幾乎不受限制。</p><p>而第11行這邊使用了 NSString 的 boundingRect(with: options: attributes: context:) 這個 method，是根據指定的參數設定在指定的範圍內畫出圖像內容(<a href="https://developer.apple.com/documentation/foundation/nsstring/1524729-boundingrect">官方說明</a>)。因為是 NSString，所以才有第4行的轉型，這邊偷懶硬轉，直接講解 boundingRect 的參數。size 就是上面第9行的邊界大小，因為寬是固定的，所以會根據內容往下延長。</p><p>第12行的 options 指的是繪出文字的設定，這邊使用的是 .usesLineFragmentOrigin，是在計算多行文字內容時官方所推薦的選項。NSStringDrawingOption 目前總共有四種設定，有興趣的可以再去看看<a href="https://developer.apple.com/documentation/foundation/nsstring/nsstringdrawingoptions">官方資料</a>。</p><blockquote>To correctly draw and size multi-line text, pass <a href="https://developer.apple.com/documentation/foundation/nsstring/nsstringdrawingoptions/1534956-useslinefragmentorigin">usesLineFragmentOrigin</a> in the options parameter.</blockquote><p>第13行的 attributes 就是 NSStringAttributedString 中所需要的屬性，這邊使用的是第6行的 attributes，但僅包含該 UILabel 的字型。這邊就會有人提問了:「<em>是否有字型大小以外的參數會影響到文字個高度呢？</em>」，答案是有的，如果該 UILabel 使用是 attributedText 來顯示文字，那我們可以透過 NSMutableParagraphStyle 來給定諸如行距等設定。所以這邊留了一個伏筆，也就是被註解掉的第7行，我們去取得當前這個 UILabel 的 attributedText 的屬性。NSAttributedString 有一個 <a href="https://developer.apple.com/documentation/foundation/nsattributedstring/1415682-attributes">attributes(at:effectiveRange:)</a> 的 method 可以抓出指定範圍內的文字屬性，其中 at (location) 是要給從哪邊開始，這邊因為 demo 方便給定 0 其實是很危險的寫法，因為當 string 是空字串時 location 0 其實就超過空字串自身的範圍了。而 effectiveRange 這邊因為我們是要拿整段文字，就不指定範圍了直接給 nil。</p><blockquote>index<br>The index for which to return attributes. This value must lie within the bounds of the receiver.<br>aRange<br>Upon return, the range over which the attributes and values are the same as those at index... If you don&#39;t need this value, pass NULL.</blockquote><p>而最後一個參數 context 是指其它的設定，如果有知道的話可以加上去，但如果是要寫一個 <strong>通用 </strong>的 method 來計算 UILabel 行數，那大可忍受這樣的不精確。</p><p>後面14到20行其實就是簡單地把總高度除以該字型單行行高，取無條件進位後轉換成 Int 而已。</p><h4>再深入想一想</h4><p>「<em>第7行我們擷取了 attributedString 的屬性來計算，那如果 attributedString 有兩段以上不同的屬性設定呢？</em>」「<em>如果使用 NSMutableParagraphStyle 指定單行行高呢？這樣用 UIFont.lineHeight 還適合嗎？</em>」這真是好問題，例如果們給了前後段文字不同的 UIFont 時，第7行的程式碼計算的結果就會跟我們的預想有出入，畢竟條件不一樣了。當我們抽絲剝繭深入去看到每一個環節的細節時就會發現，其實沒有一個通用的方法可以完美地計算出所有可能，都是取捨的問題，如果想要寫一個 <strong>通用</strong> 的 method，勢必只能符合大部分的情況；如果是要符合某個特殊案例，那還是要乖乖針對這個案例去解析。而當務之急還是先理情眼前的需求，找出適切的方案(當然，如果能進一步與需求單位溝通那也是一條路)。</p><h4>後記</h4><p>這篇文章其實沒有講到甚麼多深入的東西，反而是一直貼官方文件出來，其實是希望初學者樣成一個好習慣，多去看看寫下的每一行程式碼其背後的意涵。現在網路上找資料很方便，看到有人寫 code 遇到問題是貼上，跑不動換下一個答案貼上；或是不仔細看 error message 的內容，找到甚麼答案改什麼，但其實那不一定適用當前遇到的問題。知道自己寫的 code 是怎麼跑的，出錯時才有頭緒可能是哪邊出問題了，而不是一頭霧水。</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=23541477bf60" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>