<?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/@b97201019?source=rss-8c065ad30be1------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*-cuttijpii1xmUmUR0y0Hg.jpeg</url>
            <title>Stories by 張庭瑋 on Medium</title>
            <link>https://medium.com/@b97201019?source=rss-8c065ad30be1------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 00:32:25 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@b97201019/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[[GitHub] Actions]]></title>
            <link>https://b97201019.medium.com/github-actions-e6c5c41f5f67?source=rss-8c065ad30be1------2</link>
            <guid isPermaLink="false">https://medium.com/p/e6c5c41f5f67</guid>
            <category><![CDATA[github-actions]]></category>
            <dc:creator><![CDATA[張庭瑋]]></dc:creator>
            <pubDate>Wed, 19 Apr 2023 03:55:58 GMT</pubDate>
            <atom:updated>2023-04-19T03:55:58.251Z</atom:updated>
            <content:encoded><![CDATA[<p>最近在尋找免費的雲服務來上傳 Node.js 應用程式時</p><p>對於 <a href="https://render.com/">render</a> 感到十分佩服</p><p>只要稍微設定過，就能在每次 github 專案的指定 branch 有新的 commit 時</p><p>自動 deploy</p><p>後來突然想到</p><p>每次自我介紹更新時，都要另外手動 deploy 到 github page</p><p>應該也可以這樣有新的 commit 時自動 deploy 吧？</p><p><a href="https://github.com/features/actions">GitHub Actions · CI/CD and automations · Agentic Workflows · Workflows</a></p><p>首先在專案的根目錄建立 .github/workflows<strong> </strong>資料夾</p><p>接著建立 build.yml 檔案選</p><pre>name: Build and Deploy<br><br>on:<br>  push:<br>    branches:<br>      - master # 選擇要監聽的 branch<br><br>jobs:<br>  build-and-deploy:<br>    runs-on: ubuntu-latest<br>    steps:<br>      - name: Checkout repository<br>        uses: actions/checkout@v2<br>      - name: Setup Node.js environment<br>        uses: actions/setup-node@v2<br>        with:<br>          node-version: 16.13.0 # 需要的 node 版本<br>      - name: Install dependencies<br>        run: yarn install # 需要的 install 指令<br>      - name: Build<br>        run: yarn build # 需要的 build 指令<br>      - name: Deploy to GitHub Pages<br>        uses: peaceiris/actions-gh-pages@v3<br>        with:<br>          personal_token: ${{ secrets.AUTO_TOKEN }} # token<br>          publish_dir: ./dist # build 檔案路徑<br>          publish_branch: gh-pages</pre><p>裡面當然需要設定 github token 了</p><p>首先先<a href="https://github.com/settings/tokens">創建一個新的 token</a>（自己要保存好）</p><p>並且選取 <strong>workflow</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Wdg4-g_ellQtqyhJX0sfTw.png" /></figure><p>由於 token 是機密資料</p><p>不該直接寫在專案裡，有可能會被別人盜用</p><p>就算直接寫在專案裡，github 也會自動將 token 作廢</p><p>所以需要設定 secrets（類似環境變數）</p><p>打開專案的 Settings tab, 選取 Secrets and variables 的 Actions</p><p>點擊 New repository secret 並加入剛剛新增的 token</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/684/1*4G7jM2fw-70Ft6hnesz0cQ.png" /></figure><p>而這裡我的 Name 的設定是 <strong>AUTO_TOKEN</strong></p><p>這樣就可以藉由secrets.AUTO_TOKEN來取得我設定的 token 了</p><p>往後只要 master 分支有新的 commit，就會自動幫我上傳到 github page 了</p><p>不得不說越來越方便了．．．</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e6c5c41f5f67" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[[Next] 從 css 轉換至 css module]]></title>
            <link>https://b97201019.medium.com/next-%E5%BE%9E-css-%E8%BD%89%E6%8F%9B%E8%87%B3-css-module-e476a3628dda?source=rss-8c065ad30be1------2</link>
            <guid isPermaLink="false">https://medium.com/p/e476a3628dda</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[css-modules]]></category>
            <category><![CDATA[nextjs]]></category>
            <dc:creator><![CDATA[張庭瑋]]></dc:creator>
            <pubDate>Wed, 01 Dec 2021 14:16:02 GMT</pubDate>
            <atom:updated>2021-12-01T14:16:02.684Z</atom:updated>
            <content:encoded><![CDATA[<p>Next.js 如果想在元件層級直接像這樣 import ‘./xxx.css’ 插入css，會遇到這個錯誤</p><p><a href="https://nextjs.org/docs/messages/css-global">Global CSS Must Be in Your Custom \&lt;App&gt;</a></p><p>然而總不能每一個 css 都插到 pages/_app`，當成global css來用</p><p>於是 Next.js 自己也提出了數種解決方案</p><p>其中一種是 <a href="https://nextjs.org/docs/basic-features/built-in-css-support#adding-component-level-css">Adding Component-Level CSS</a></p><p>不過腦袋轉不太過來，還是靠同事的幫忙</p><p>在此記錄一下轉換的過程</p><p>這裡我的 Carousel 的結構大概是</p><pre>&lt;div&gt;<br>  &lt;Slider {...setting}&gt;</pre><p>而 Slider 內部則為</p><pre>&lt;ul&gt;<br>  &lt;li&gt;<br>    &lt;button&gt;</pre><p>而 setting 可以在裡面塞要添加到 &lt;button/&gt; 上的 class 名</p><pre>settings={<br>  ...<br>  dotsClass: &#39;carousel-dot&#39;,</pre><pre>}</pre><p>所以實際上大概是</p><pre>&lt;div&gt;<br>  &lt;ul&gt;<br>    &lt;li class=&quot;slick-active&quot;&gt;<br>      &lt;button class=&quot;carousel-dot&quot;&gt;</pre><p>(slick-active為套件內設計，當滑到該張圖片會添加到 li 上的 class 名)</p><p>而 card 的結構大致是</p><pre>&lt;div class=&quot;card-wrapper&quot;&gt;<br>  ...<br>    &lt;div class=&quot;card-title&quot;&gt;</pre><p>原本的 css :</p><pre>// carousel.css</pre><pre>.carousel-dot::before {</pre><pre>  @apply text-white !important;</pre><pre>  opacity: 1 !important;</pre><pre>}</pre><pre>.slick-active button::before {</pre><pre>  @apply text-primary !important;</pre><pre>}<br></pre><pre>.card-wrapper:hover .card-title {</pre><pre>  @apply text-primary;</pre><pre>}</pre><p>上半部是為了修改 <a href="https://react-slick.neostack.com/docs/get-started">React Slick</a> 裡輪播的切換點的顏色</p><p>下半部是為了讓區塊被 hover 時 title 的顏色會跟著改變</p><p>（現在仔細一看這怎麼會放在同一個檔案裡…）</p><p>首先要當檔名改為 xxx.module.css</p><pre>import <strong>styles from</strong> &#39;./carousel.module.css&#39;</pre><p>由於 &lt;Slider/&gt;的結構是藏在套件中，用這種 import 法修改不到，所以 slick-active 的 style 覆蓋需要換個方法，變成從外側的 div 伸入</p><p>carousel.module.css 改寫成</p><pre>.carousel li button.carousel-dot::before {</pre><pre>  @apply text-white;</pre><pre>  opacity: 1;</pre><pre>}</pre><pre>.carousel :global(li.slick-active) button.carousel-dot::before {</pre><pre>  @apply text-primary;</pre><pre>}</pre><p>這裡要注意由於 li 並非屬於此元件，需要使用 ( :global ) 宣告為全局</p><p>Carousel 則改成這樣</p><pre>import styles from &#39;./carousel.module.css&#39;</pre><pre>export default function Carousel(...){</pre><pre>...<br>  return (<br>    &lt;div className={<strong>styles.carousel</strong>}&gt;<br>      &lt;Slider {...setting}&gt;</pre><pre>  )</pre><pre>}</pre><p>Card 的 css 則不用特別改變</p><pre>// card.module.css<br>.card-wrapper:hover .card-title {</pre><pre>  @apply text-primary;</pre><pre>}</pre><p>Card部分則如此修改</p><pre>import classNames from &#39;classnames&#39;<br>import styles from &#39;./card.module.css&#39;</pre><pre>export default function Card(...){</pre><pre>...<br>  return (<br>    &lt;div class={<strong>styles[&#39;card-wrapper&#39;]</strong>}&gt;<br>      ...<br>        &lt;div class={<strong>styles[&#39;card-title&#39;]</strong>}&gt;</pre><pre>  )</pre><pre>}</pre><p>Card的部分相當單純，而 Carousel 的部分因為牽扯到修改套件的 style，採取調整選擇器的方式處理，希望下次遇到這種狀況時腦袋也能轉一下…</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e476a3628dda" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[[Git] cherry-pick 的順序]]></title>
            <link>https://b97201019.medium.com/git-cherry-pick-%E7%9A%84%E9%A0%86%E5%BA%8F-a9b513cff148?source=rss-8c065ad30be1------2</link>
            <guid isPermaLink="false">https://medium.com/p/a9b513cff148</guid>
            <category><![CDATA[git]]></category>
            <dc:creator><![CDATA[張庭瑋]]></dc:creator>
            <pubDate>Fri, 30 Jul 2021 08:03:25 GMT</pubDate>
            <atom:updated>2021-07-30T08:03:25.785Z</atom:updated>
            <content:encoded><![CDATA[<p>＊本篇只是小筆記</p><p>今天在工作的時候遇到一個狀況</p><p>同事：舊的版本也要用這幾個 commit，幫我發一份過來</p><p>我：（直接從新版扔 MR）</p><p>同事：（關掉 MR）用 cherry-pick</p><p>我：（抖）</p><p>cherry-pick的用法可以參考這篇</p><p><a href="https://gitbook.tw/chapters/faq/cherry-pick.html">【狀況題】如果你只想要某個分支的某幾個 Commit？ - 為你自己學 Git | 高見龍</a></p><p>基本上就是</p><pre>git cherry-pick sha1 sha2 ......</pre><p>總共需要4個 commit</p><p>從新到舊是 sha1, sha2, sha3, sha4</p><p>於是我下了</p><pre>git cherry-pick sha1 sha2 sha3 sha4</pre><p>結果撿進來的東西不完整</p><p>同事：不就 git cherry-pick sha4 sha3 sha2 sha1</p><p>我：我下的順序跟你是反的</p><p>同事：難怪……要依現實時間從舊到新啊</p><p>我：Orz</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a9b513cff148" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[[RN] 如何不讓使用者回上一頁]]></title>
            <link>https://b97201019.medium.com/rn-%E5%A6%82%E4%BD%95%E4%B8%8D%E8%AE%93%E4%BD%BF%E7%94%A8%E8%80%85%E5%9B%9E%E4%B8%8A%E4%B8%80%E9%A0%81-cc56b3f754bb?source=rss-8c065ad30be1------2</link>
            <guid isPermaLink="false">https://medium.com/p/cc56b3f754bb</guid>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[react-navigation]]></category>
            <dc:creator><![CDATA[張庭瑋]]></dc:creator>
            <pubDate>Sat, 17 Jul 2021 03:44:18 GMT</pubDate>
            <atom:updated>2021-07-17T03:44:18.042Z</atom:updated>
            <content:encoded><![CDATA[<p>＊這裡使用的是 <a href="https://reactnavigation.org/">react-navigation</a></p><p>這裡講的回上一頁都是在說按 Android的 soft menu的上一頁或是使用 ios的手勢，至於 App裡 header的上一頁箭頭是可以隱藏的，這裡就不討論</p><ol><li>reset</li></ol><pre>import { CommonActions } from &#39;@react-navigation/native&#39;;</pre><pre>navigation.dispatch(</pre><pre>  CommonActions.reset({</pre><pre>    index: 1,</pre><pre>    routes: [</pre><pre>      { name: &#39;Home&#39; },</pre><pre>      {</pre><pre>        name: &#39;Profile&#39;,</pre><pre>        params: { user: &#39;jane&#39; },</pre><pre>      },</pre><pre>    ],</pre><pre>  })</pre><pre>);</pre><p>然而由於 reset的概念是清空 history後使用自己設定的 history，如果只是想不讓這個頁面返回，下一個頁面還是能用 <a href="https://reactnavigation.org/docs/navigation-prop#navigate">navigate返回</a>的話這個方式就行不通</p><blockquote>If the screen is already present in the stack’s history, it’ll go back to that screen and remove any screens after that.</blockquote><p>2. push之後鎖住 go back</p><p>單個頁面鎖住 go back就是這篇的重點了，ios 跟 android的實現方式有所不同</p><h3>Ios</h3><p>在 screen的 option增加 gestureEnabled</p><pre>&lt;Stack.Screen</pre><pre>  name=&quot;screenName&quot;</pre><pre>  component={ScreenComponent}</pre><pre>  options={{gestureEnabled: false}}</pre><pre>/&gt;</pre><p>如果想鎖住 Stack也可以</p><pre>&lt;Stack.Navigator<br>  screenOptions={{<br>    gestureEnabled: false,<br>  }}<br>&gt;    <br>  ...<br>&lt;/Stack.Navigator&gt;</pre><p>這裡的鎖住手勢只會鎖 swipe，所以點擊依舊 ok</p><h3>Android</h3><p><a href="https://reactnavigation.org/docs/custom-android-back-button-handling/">Custom Android back button behavior</a>，這裡可以簡單地寫個 hook讓使用起來比較方便</p><pre>import {useFocusEffect} from &#39;@react-navigation/native&#39;;</pre><pre>import {useCallback} from &#39;react&#39;;</pre><pre>import {BackHandler} from &#39;react-native&#39;;</pre><pre>export default function usePreventGoingBack(onBackPress = () =&gt; true) {</pre><pre>  useFocusEffect(</pre><pre>    useCallback(</pre><pre>      () =&gt; {</pre><pre>        BackHandler.addEventListener(&#39;hardwareBackPress&#39;,  <br>        onBackPress);</pre><pre>        return () =&gt;</pre><pre>        BackHandler.removeEventListener(&#39;hardwareBackPress&#39;,  <br>        onBackPress);</pre><pre>      },</pre><pre>      [onBackPress],</pre><pre>    ),</pre><pre>  );</pre><pre>}</pre><p>使用時的話直接在 component內調用</p><pre>...</pre><pre>export default ScreenComponent(){<br>  usePreventGoingBack()</pre><pre>  ...<br>}</pre><p>就能鎖住 go back了</p><p>參考：</p><p><a href="https://reactnavigation.org/docs/navigation-actions/#reset">https://reactnavigation.org/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cc56b3f754bb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[[React] 在useEffect中使用 setState造成無限重複渲染]]></title>
            <link>https://b97201019.medium.com/react-%E5%9C%A8useeffect%E4%B8%AD%E4%BD%BF%E7%94%A8-setstate%E9%80%A0%E6%88%90%E7%84%A1%E9%99%90%E9%87%8D%E8%A4%87%E6%B8%B2%E6%9F%93-a22733a23420?source=rss-8c065ad30be1------2</link>
            <guid isPermaLink="false">https://medium.com/p/a22733a23420</guid>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[張庭瑋]]></dc:creator>
            <pubDate>Tue, 25 May 2021 08:01:12 GMT</pubDate>
            <atom:updated>2021-05-25T08:01:12.637Z</atom:updated>
            <content:encoded><![CDATA[<p>如果有使用 eslint之類的工具，總是會在把 useEffect的 dependency補齊時發出警告</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/477/1*W4LWrQO7qeecBQ0g3S_6fg.png" /></figure><p>這裡我有個 list，需要在每次 props.data更新時同時更新 list</p><pre>const [list, setList] = useState({});</pre><pre>useEffect(() =&gt; {</pre><pre>  const newList = props.data.reduce((obj, item) =&gt; {</pre><pre>      obj[item.id] = <strong>list</strong>[item.id] || false;</pre><pre>      return obj;</pre><pre>    }</pre><pre>  , {});</pre><pre>  <strong>setList</strong>(newList);</pre><pre>}, [props.data]);</pre><p>這時 eslint會提醒將 list加入 dependency中（而且是以紅字），但加入會發生什麼事？</p><pre>}, [ <strong>list</strong>, props.data]);</pre><p>在第一次觸發 useEffect後，馬上因為呼叫了 setList而再次觸發 useEffect，就這樣一直無限循環，難道這裡只能拿掉 dependency了嗎？</p><p>當然最好不要，拿掉 dependency代表 list的值無法更新，可能會引起未知的 bug，這裡可以使用 <strong>useRef</strong>來解決</p><p>在 useEffect前使用 <strong>useRef</strong>來儲存舊的 list</p><pre>const oldListRef = useRef();</pre><pre>oldListRef.current = list;</pre><p>然後在 useEffect中不使用 list，而是 oldListRef.current</p><pre>useEffect(() =&gt; {</pre><pre>  const newList = props.data.reduce((obj, item) =&gt; {</pre><pre>      obj[item.id] = oldListRef.current[item.id] || false;</pre><pre>      return obj;</pre><pre>    }</pre><pre>  , {});</pre><pre><strong>  setList</strong>(newList);</pre><pre>}, [props.data]);</pre><p>這樣就可以讓 useEffect中可以拿到新的list值，也不會因為把list 加入dependency而進入無窮迴圈了</p><p>整體：</p><pre>const [list, setList] = useState({});<br>const oldListRef = useRef();<br></pre><pre>oldListRef.current = list;</pre><pre>useEffect(() =&gt; {</pre><pre>  const newList = props.data.reduce((obj, item) =&gt; {</pre><pre>      obj[item.id] = oldListRef.current[item.id] || false;</pre><pre>      return obj;</pre><pre>    }</pre><pre>  , {});</pre><pre><strong>  setList</strong>(newList);</pre><pre>}, [props.data]);</pre><ul><li><a href="https://reactjs.org/docs/hooks-effect.html">Using the Effect Hook - React</a></li><li><a href="https://reactjs.org/docs/hooks-reference.html#useref">Hooks API Reference - React</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a22733a23420" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[[JS] reduce的使用]]></title>
            <link>https://b97201019.medium.com/js-reduce%E7%9A%84%E4%BD%BF%E7%94%A8-bea6d7461896?source=rss-8c065ad30be1------2</link>
            <guid isPermaLink="false">https://medium.com/p/bea6d7461896</guid>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[張庭瑋]]></dc:creator>
            <pubDate>Tue, 25 May 2021 07:24:52 GMT</pubDate>
            <atom:updated>2021-05-25T07:24:52.037Z</atom:updated>
            <content:encoded><![CDATA[<p>今天工作剛好碰到需要使用的地方，太少使用了，一碰到就原地炸開，來記錄一下解決的過程</p><p><a href="https://developer.mozilla.org/zh-TW/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce">先貼個MDN</a></p><p>今天碰到的問題是：我有個物件長這樣</p><p>list = { [key]: boolean } , 我要確認 list中所有值皆為 true才 return <strong>true</strong> , 否則 return <strong>false</strong></p><p>簡單一點當然可以使用<strong> forEach</strong></p><pre>let result = true</pre><pre>Object.keys(list).forEach(key=&gt;{</pre><pre>  if(!list[key]){</pre><pre>    result = false</pre><pre>  }</pre><pre>})</pre><pre>return result</pre><p>同樣的作法，可以試著使用 reduce來做</p><p>首先是初始值為 true</p><pre>Object.keys(imagesLoadedList).reduce(..., <strong>true</strong>)</pre><p>在每次運算的過程，reduce的第一個值是上次運算的結果，第二個值是這次傳入的值，在使用 Object.keys的狀況下，每次傳入的值都是 property 的 key</p><p>list = { [<strong>key</strong>]: boolean }</p><p>所以在這裡的運算應該是上次運算的結果 <strong>value</strong>，和這次的 property的 value，即 list[key] 作比較</p><pre>value &amp;&amp; list[key]</pre><p>整個寫下來就是</p><pre>Object.keys(list).reduce((value, key) =&gt; {</pre><pre>  return <strong>value &amp;&amp; list[key]</strong></pre><pre>}, true)</pre><p>沒錯，這其實是很初級的 JS，我深刻地反省…</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bea6d7461896" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[[Swift] 使用 Realm製作待辦清單]]></title>
            <link>https://medium.com/peter-pan-swift-ios-class/swift-%E4%BD%BF%E7%94%A8-realm%E8%A3%BD%E4%BD%9C%E5%BE%85%E8%BE%A6%E6%B8%85%E5%96%AE-a63b7ab8ff22?source=rss-8c065ad30be1------2</link>
            <guid isPermaLink="false">https://medium.com/p/a63b7ab8ff22</guid>
            <category><![CDATA[realm]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[core-data]]></category>
            <dc:creator><![CDATA[張庭瑋]]></dc:creator>
            <pubDate>Fri, 29 Jan 2021 06:07:40 GMT</pubDate>
            <atom:updated>2021-01-29T08:47:30.208Z</atom:updated>
            <content:encoded><![CDATA[<p>比起 UserDefaults，CoreData可以儲存更複雜的資料，然而這時也有一個明顯的問題冒出來了：CoreData的程式碼閱讀性較差。這裡要試著使用閱讀性較高且速度較快的第三方套件：Realm</p><p><a href="https://cocoapods.org/pods/RealmSwift">RealmSwift</a></p><p>在安裝之前先在根目錄建立 <strong>.gitignore</strong>檔並將 Realm加入</p><pre>.gitignore</pre><pre>/Pods/Realm</pre><p>因為 Realm超過 github普通上傳的 100MB限制了，當然也可以乾脆整個 Pods都不要上傳到 github，接著就可以將 Realm加入 podfile</p><pre>pod &#39;RealmSwift&#39;</pre><p>接著執行安裝</p><pre>pod install</pre><p>跟 CoreData不同的地方是，AppDelegate可以不用多加設定，對於中途才決定使用資料庫的人來說，Realm方便了不少（中途加入 CoreData的有些是要另開新專案去複製 AppDelegate裡的設定）</p><p>這次簡單來試做個 TodoList，首先來定義種類以及下面的事項，這裡設定為一個種類下可以有複數個事項</p><h3>資料格式</h3><p>Item</p><p>宣告了三個響應式屬性，並以 LinkingObjects連結與 Category的關係</p><pre>import Foundation<br>import RealmSwift</pre><pre>class ItemRealm: Object {<br>    <a href="http://twitter.com/objc">@objc</a> dynamic var title: String = &quot;&quot;<br>    <a href="http://twitter.com/objc">@objc</a> dynamic var done:Bool = false<br>    <a href="http://twitter.com/objc">@objc</a> dynamic var dateCreated: Date?<br>    <br>    var parentCategory = LinkingObjects(fromType: CategoryRealm.self, property: &quot;itemRealms&quot;)<br>}</pre><p>Category</p><p>宣告了ㄧ個響應式屬性，並以 List&lt;T&gt;表達與 Item的一對多關係</p><pre>import Foundation<br>import RealmSwift</pre><pre>class CategoryRealm: Object {<br>    <a href="http://twitter.com/objc">@objc</a> dynamic var name: String = &quot;&quot;<br>    let itemRealms = List&lt;ItemRealm&gt;()<br>}</pre><p>接著在 StoryBoard上以兩個 TableView表達 Category與 Item畫面</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q4McZO4JwT3UQ7NdssGbOw.png" /></figure><h3>滑動刪除</h3><p>由於普通的 todo list在點擊時，通常都是把事項標示已做或未做，而刪除可能會以滑動的方式，這裡使用 SwipeCellKit來簡單解決這方面的功能</p><p><a href="https://github.com/SwipeCellKit/SwipeCellKit">SwipeCellKit/SwipeCellKit</a></p><pre>target &#39;Project&#39; do</pre><pre>  ...<br>  <strong>pod &#39;SwipeCellKit&#39;</strong><br>  <br>end</pre><p>接著終端機輸入</p><pre>pod install</pre><p>由於預計 Category和 Item都有滑動刪除的功能，所以這裡先新增一個super class繼承 SwipeTableViewCellDelegate，由於滑開後需要空間插入刪除等操作的圖示，這裡先提升欄位高度</p><pre>class SwipeTableViewController: UITableViewController, <strong>SwipeTableViewCellDelegate</strong> {<br>    <br>    override func viewDidLoad() {<br>        super.viewDidLoad()<br>        <br>        <strong>tableView.rowHeight = 60</strong><br>        <br>    }</pre><pre>    ...<br>    <br>}</pre><p>接著在 tableview data source methods的 <strong>cellForRowAt中 return </strong>SwipeTableViewCell，由於這裡 Item跟 Category的操作應該會有所不同所以作為 superclass就不再添加過多的東西</p><pre>// MARK: - tableview data source methods<br>    override func tableView(_ tableView: UITableView, <strong>cellForRowAt</strong> indexPath: IndexPath) -&gt; UITableViewCell {</pre><pre>        let cell = tableView.dequeueReusableCell(withIdentifier: &quot;Cell&quot;, for: indexPath) as! <strong>SwipeTableViewCell</strong><br>        <br>        cell.delegate = self<br>    <br>        return cell<br>    }</pre><p>接著新增SwipeTableViewCellDelegate methods的方法，這裡定義空的 updateModel()，供 subclass override，然後這裡可以修改刪除的圖示，除此外的都偏向設定，可以照官方的教學</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/182/1*2rtm5F3eahkDaPlp9JMmkg.png" /><figcaption>圖示</figcaption></figure><pre>// SwipeTableViewCellDelegate methods<br>    func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath, for orientation: SwipeActionsOrientation) -&gt; [SwipeAction]? {<br>        guard orientation == .right else { return nil }<br>        <br>        let deleteAction = SwipeAction(style: .destructive, title: &quot;Delete&quot;) { action, indexPath in<br>            // handle action by updating model with deletion<br>            <strong>self.updateModel(at: indexPath)</strong><br>        }<br>        <br>        // customize the action appearance<br>        <strong>deleteAction.image = UIImage(systemName: &quot;trash.fill&quot;)</strong><br>        <br>        return <strong>[deleteAction]</strong><br>    }</pre><pre>func tableView(_ tableView: UITableView, editActionsOptionsForRowAt indexPath: IndexPath, for orientation: SwipeActionsOrientation) -&gt; SwipeOptions {<br>        var options = SwipeOptions()<br>        options.expansionStyle = .destructive<br>        options.transitionStyle = .border<br>        return options<br>    }<br>    <br>    func <strong>updateModel</strong>(at indexPath: IndexPath) {<br>        // update<br>    }</pre><h3>CategoryViewController</h3><p>首先繼承剛剛創造的 SwipeTableViewController</p><pre><strong>class</strong> CategoryViewController: SwipeTableViewController</pre><h4>載入資料</h4><p>新增 Realm實體，並且定義<strong>種類們</strong>為 Results&lt;CategoryRealm&gt; （這裡要注意因為要接收 realm從資料庫中回傳的資料，不可以使用陣列），然後定義 <strong>loadCategories()</strong>載入資料後更新畫面</p><pre>class CategoryViewController: SwipeTableViewController {<br>    <br>    <strong>let realm = try! Realm()</strong><br><br>    var categories: <strong>Results&lt;CategoryRealm&gt;?</strong><br><br>    override func viewDidLoad() {<br>        super.viewDidLoad()<br>        <br>        loadCategories()<br>    }<br>    <br>    func loadCategories() <br>        categories = <strong>realm.objects(CategoryRealm.self)</strong><br>        <br>        tableView.reloadData()<br>    }<br> <br>    ......</pre><pre>}</pre><h4>儲存及刪除</h4><p>需要修改資料庫的資料時需要以 do catch配上 try，而 delete的部分則是直接覆寫 SwipeTableViewController中的 updateModel，由於需要支援滑動刪除才需要用複寫的，普通直接寫個 delete()其實也沒問題</p><pre>   // func saveCategories() {<br>    func save(category: CategoryRealm) {<br>        do {<br>            // try context.save()<br>            try <strong>realm.write {<br>                realm.add(category)<br>            }</strong><br>        } catch {<br>            print(&quot;error saving category: \(error)&quot;)<br>        }<br>        tableView.reloadData()<br>    }<br>    <br>    // MARK: - delete data from swipe<br>    override func updateModel(at indexPath: IndexPath) {<br>        if let categoryForDeletion = self.categories?[indexPath.row] {<br>            do {<br>                try <strong>self.realm.write {<br>                    self.realm.delete(categoryForDeletion)<br>                }</strong><br>            } catch {<br>                print(&quot;error deleting category: \(error)&quot;)<br>            }<br>            <br>        }<br>    }</pre><h4><strong>點擊新增</strong></h4><p>對右上角加號的 Bar Button Item新增 IBAction</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/180/1*NcP-3r9VUIv6uqD59Y0sZg.png" /><figcaption>＋</figcaption></figure><p>這裡使用 UIAlertController搭配 UITextField以彈出框的形式新增種類，輸入完畢後調用剛剛寫的 save()</p><pre><a href="http://twitter.com/IBAction">@IBAction</a> func addButtonPressed(_ sender: UIBarButtonItem) {<br>        var textField = UITextField()<br>        <br>        let alert = UIAlertController(title: &quot;Add New Category&quot;, message: &quot;&quot;, preferredStyle: .alert)<br>        let action = UIAlertAction(title: &quot;Add&quot;, style: .default) { (action) in<br><br>            let newCategory = CategoryRealm()<br>            newCategory.name = textField.text!<br><br>            <strong>self.save(category: newCategory)</strong><br>        }<br>        alert.addAction(action)<br>        alert.addTextField { (field) in<br>            textField = field<br>            textField.placeholder = &quot;Add a new category&quot;<br>        }<br>        present(alert, animated: true, completion: nil)<br>    }</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*6g9Fcm1DdNzMsbFybfxHZA.png" /></figure><h4><strong>Table view data source</strong></h4><p>當然該補上的東西還是要補上…這裡要注意的是在 cellForRowAt中調用的 cell直接從 superclass的 cellForRowAt裡取得</p><pre>// MARK: - Table view data source<br>    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -&gt; Int {<br>        return categories?.count ?? 1<br>    }<br>    <br>    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -&gt; UITableViewCell {<br>        // let cell = tableView.dequeueReusableCell(withIdentifier: &quot;CategoryCell&quot;, for: indexPath) as! SwipeTableViewCell<br>        let cell = <strong>super.tableView(tableView, cellForRowAt: indexPath)</strong><br>        <br>        cell.textLabel?.text = categories?[indexPath.row].name ?? &quot;No Categories Added Yet&quot;<br>        <br>        return cell<br>    }</pre><h4>點擊</h4><p>當在 Category項目點擊後，前往 Item頁的同時將點擊的 Category傳入下一頁，這裡假設 ToDoListTableViewController中有 selectedCategory這個屬性</p><pre>//MARK: - Table View Delegate Methods<br>    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {<br>        performSegue(withIdentifier: &quot;goToToDoItems&quot;, sender: self)<br>    }<br>    <br>    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {<br>        let destinationTVC = segue.destination as! ToDoListTableViewController<br>        <br>        if let indexPath = tableView.indexPathForSelectedRow {<br>            <strong>destinationTVC.selectedCategory = categories?[indexPath.row]</strong><br>        }<br>    }</pre><p>現在可以新增種類了</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/886/1*2vTeSSElr20uL_I06RL1OA.png" /></figure><h3>ToDoListTableViewController</h3><p>第一步還是繼承 SwipeTableViewController</p><pre><strong>class</strong> ToDoListTableViewController: SwipeTableViewController</pre><h4>載入資料</h4><p>新增 realm實體，同時把剛剛假設的 <strong>selectedCategory</strong>屬性補上，由於 categories?代表可能是空的，而只有在 categories不為空時才去載入資料(載入資料依標題排序)，所以這裡要在 didset進行載入的動作而非 viewDidLoad</p><pre>class ToDoListTableViewController: SwipeTableViewController {<br>    <br>    var todoItems: Results&lt;ItemRealm&gt;<br>    var selectedCategory: CategoryRealm? {<br>        didSet{<br>            loadToDoItems()<br>        }<br>    }<br>    <br>    let realm = try! Realm()</pre><pre>    // MARK: - load todo item<br>    func loadToDoItems() {<br>        <br>        todoItems = selectedCategory?.itemRealms.sorted(byKeyPath: &quot;title&quot;, ascending: true)<br>        <br>        tableView.reloadData()<br>    }    <br>    ...</pre><pre>}</pre><h4>刪除 Item</h4><p>基本上跟 Category上的做法是一樣的</p><pre>override func updateModel(at indexPath: IndexPath) {<br>        if let todoItemForDeletion = self.todoItems?[indexPath.row] {<br>            do {<br>                try <strong>self.realm.write {<br>                    self.realm.delete(todoItemForDeletion)<br>                }</strong><br>            } catch {<br>                print(&quot;error deleting todo item: \(error)&quot;)<br>            }<br>            <br>        }<br>    }</pre><h4>新增 Item</h4><p>這裡沒有另外寫個 save()，除此外跟 Category上的做法大體相同</p><pre>//MARK: - add new item<br>    <a href="http://twitter.com/IBAction">@IBAction</a> func addNewItem(_ sender: UIBarButtonItem) {<br>        var  textField = UITextField()<br>        <br>        <br>        let alert = UIAlertController(title: &quot;Add new to item&quot;, message: &quot;&quot;, preferredStyle: .alert)<br>        let action = UIAlertAction(title: &quot;Add Item&quot;, style: .default) { (action) in<br>            <br>            if let currrentCategory = self.selectedCategory {<br>                do {<br>                    try <strong>self.realm.write {<br>                        let newTodo = ItemRealm()<br>                        newTodo.title = textField.text! <br>                        newTodo.dateCreated = Date()<br>                        <br>                        currrentCategory.itemRealms.append(newTodo)<br><br>                    }</strong><br>                } catch {<br>                    print(&quot;Add new items fail:\(error)&quot;)<br>                }<br>                <br>            }<br>            self.tableView.reloadData()<br>          <br>        }<br>        <br>        alert.addTextField { (alertTextField) in<br>            alertTextField.placeholder = &quot;enter sth.&quot;<br>            <br>            textField = alertTextField<br>        }<br>        alert.addAction(action)<br>        <br>        present(alert, animated: true, completion: nil)<br>    }</pre><h4><strong>Table view data source方法</strong></h4><p>cellForRowAt中的 cell一樣需使用 superclass中的 cellForRowAt回傳的以外，</p><p>每當點擊 cell時就要反轉 <strong>done</strong>屬性，並在 cellForRowAt中以此更改 cell的 accessoryType</p><pre>override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -&gt; Int {<br>        // #warning Incomplete implementation, return the number of rows<br>        return todoItems?.count ?? 1<br>    }<br>    <br>    override func tableView(_ tableView: UITableView, <strong>cellForRowAt</strong> indexPath: IndexPath) -&gt; UITableViewCell {<br>        // let cell = tableView.dequeueReusableCell(withIdentifier: &quot;ToDoItemCell&quot;, for: indexPath)<br>        let cell = <strong>super.tableView(tableView, cellForRowAt: indexPath)</strong><br>        <br>        if let item = todoItems?[indexPath.row] {<br>            cell.textLabel?.text = item.title<br>            cell.accessoryType = item.done ? .checkmark : .none<br>        } else {<br>            cell.textLabel?.text = &quot;No Item Added&quot;<br>        }<br>        <br>        return cell<br>    }<br>    <br>    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {<br>        <br>        if let item = todoItems?[indexPath.row] {<br>            do {<br>                try <strong>realm.write {<br>                    item.done = !item.done<br>                }</strong><br>            } catch {<br>                print(&quot;error saving done status\(error)&quot;)<br>            }<br>            <br>        }<br>        tableView.reloadData()<br>        <br>        tableView.deselectRow(at: indexPath, animated: true)<br>    }</pre><h4>搜尋</h4><p>由於有放入一個搜尋框，所以順便來實作搜尋功能</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/946/1*ngaxZ56WHLIsS9b1edSA5w.png" /></figure><p>先拉 IBOutlet並加入 delegate</p><pre>class ToDoListTableViewController: SwipeTableViewController {<br>    <br>    ...<br>    <br>    <a href="http://twitter.com/IBOutlet">@IBOutlet</a> weak var searchBar: UISearchBar!<br>    <br>    override func viewDidLoad() {<br>        super.viewDidLoad()<br>        <br>        searchBar.delegate = self<br>    }<br>    ...<br>}</pre><p>為了 code的可讀性，以 extension的方式編寫 UISearchBarDelegate的功能</p><pre>//MARK: - UISearchBarDelegate<br>extension ToDoListTableViewController: UISearchBarDelegate {<br>}</pre><p>首先是按下 enter後以輸入框的文字過濾資料，並以創造日期排列後重新載入資料，這裡的 <strong>title CONTAINS[cd] %@</strong>是指 title這個屬性中含有後面的參數：<strong>searchBar.text!</strong>的意思</p><pre>func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {<br>        <br>        <strong>todoItems = todoItems?.filter(&quot;title CONTAINS[cd] %@&quot;, searchBar.text!).sorted(byKeyPath: &quot;dateCreated&quot;, ascending: true)</strong><br>        <br>        tableView.reloadData()<br>        <br>    }</pre><p>當輸入框清空時重新顯示所有資料，並且關閉鍵盤</p><pre>func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {<br>        if searchBar.text?.count == 0 {<br>            <strong>loadToDoItems()</strong><br>            <br>            DispatchQueue.main.async {<br>                // dismiss keyboard...<br>                <strong>searchBar.resignFirstResponder()</strong><br>            }<br>            <br>        }<br>    }</pre><h3>編輯</h3><p>既然滑動那邊可以刪除，也能再加上編輯的功能，不過之前刪除函式用的名字是 updateModel()，現在看起來就很容易搞混…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/822/1*JogqAnu2rz0TaPJupOzgUA.png" /><figcaption>改成這樣，當然 override的名字之類的也要跟著換</figcaption></figure><p>跟刪除一樣，寫個空的函式給 subclass override，並加入 SwipeTableViewController的 editActionsForRowAt，大致上跟刪除是一樣的，由於預設顏色是紅色，如果要修改可以更改 <strong>backgroundColor</strong>屬性</p><pre>     func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath, for orientation: SwipeActionsOrientation) -&gt; [SwipeAction]? {<br>        guard orientation == .right else { return nil }<br>        <br>        let deleteAction = SwipeAction(style: .destructive, title: &quot;Delete&quot;) { action, indexPath in<br>            // handle action by updating model with deletion<br>            self.deleteModel(at: indexPath)<br>        }<br>        <strong>let editAction = SwipeAction(style: .destructive, title: &quot;Edit&quot;) { action, indexPath in<br>            // handle action by updating model with edition<br>            self.updateModel(at: indexPath)<br>        }</strong><br>        <br>        // customize the action appearance<br>        deleteAction.image = UIImage(systemName: &quot;trash.fill&quot;)<br>        <strong>editAction.image = UIImage(systemName: &quot;pencil&quot;)<br>        editAction.backgroundColor = UIColor(red: 238/255, green: 162/255, blue: 57/255, alpha: 1)</strong><br>        <br>        return [deleteAction<strong>, editAction</strong>]<br>    }</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/898/1*MLdEBiB0Gs4qlmtNoCbZBQ.png" /></figure><h4>滑動到最底是刪除？編輯？</h4><p>值得要注意的是最後回傳的陣列，由於這個滑動 cell支援兩種滑動操作，一種是滑開來點擊，一種是滑到底，那麼滑到底會執行哪個 Action?或是所有都執行一次嗎？答案是位於 0位置的 Action</p><pre>// run deleteAction<br>[deleteAction, editAction]</pre><pre>// run editAction<br>[editAction, deleteAction]</pre><p>接著就要在 subclass override <strong>deleteModel()</strong></p><h4>ToDoListTableViewController</h4><p>這裡預想是按下編輯後會跳出<strong>警告</strong>，然後把既有的內容（title）加入到警告中，等修改好按下確定後再寫入資料庫中，至於如何更新資料，其實只要直接修改 realm的物件的屬性就可以了</p><pre>override func updateModel(at indexPath: IndexPath) {<br>        if let todoItemForEdition = self.todoItems?[indexPath.row] {<br>            var textField = UITextField()<br>            <br>            <br>            let alert = UIAlertController(title: &quot;Edit item title&quot;, message: &quot;&quot;, preferredStyle: .alert)<br>            let action = UIAlertAction(title: &quot;Edit Item&quot;, style: .default) { (action) in<br>                <br>                do {<br>                    try <strong>self.realm.write {<br>                        todoItemForEdition.title = textField.text!<br>                    }</strong><br>                } catch {<br>                    print(&quot;Edit item fail:\(error)&quot;)<br>                }<br>                <br>                <br>                self.tableView.reloadData()<br>            }<br>            <br>            alert.addTextField { (alertTextField) in<br>                <strong>alertTextField.text = todoItemForEdition.title</strong><br>                <br>                textField = alertTextField<br>            }<br>            alert.addAction(action)<br>            <br>            present(alert, animated: true, completion: nil)<br>            <br>        }<br>    }</pre><h4>CategoryViewController</h4><p>這邊也是如法炮製</p><pre>override func updateModel(at indexPath: IndexPath) {<br>        if let categoryForEdition = categories?[indexPath.row] {<br>            var textField = UITextField()<br>            <br>            <br>            let alert = UIAlertController(title: &quot;Edit category title&quot;, message: &quot;&quot;, preferredStyle: .alert)<br>            let action = UIAlertAction(title: &quot;Edit Category&quot;, style: .default) { (action) in<br>                <br>                do {<br>                    try <strong>self.realm.write {<br>                        categoryForEdition.name = textField.text!<br>                    }</strong><br>                } catch {<br>                    print(&quot;Edit category fail:\(error)&quot;)<br>                }<br>                <br>                <br>                self.tableView.reloadData()<br>            }<br>            <br>            alert.addTextField { (alertTextField) in<br>                <strong>alertTextField.text = categoryForEdition.name</strong><br>                <br>                textField = alertTextField<br>            }<br>            alert.addAction(action)<br>            <br>            present(alert, animated: true, completion: nil)<br>            <br>        }<br>    }</pre><h3>成果</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/481/1*p1hE9UHoUwEMOuW4MoqtRw.gif" /></figure><h4>commit</h4><p><a href="https://github.com/KakeruChang/HoloIntroduction/commit/f2000b728b1c9ad3c5d7571af1a5a8bf861b34e6">feat: complete todo list · KakeruChang/HoloIntroduction@f2000b7</a></p><p>語法整體上比起 CoreData清爽了不少，如果是從頭開發新專案的，直接從 Realm開始也是個不錯的選擇。</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a63b7ab8ff22" width="1" height="1" alt=""><hr><p><a href="https://medium.com/peter-pan-swift-ios-class/swift-%E4%BD%BF%E7%94%A8-realm%E8%A3%BD%E4%BD%9C%E5%BE%85%E8%BE%A6%E6%B8%85%E5%96%AE-a63b7ab8ff22">[Swift] 使用 Realm製作待辦清單</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[[Swift] 大家來聊天-連接FireStore]]></title>
            <link>https://medium.com/peter-pan-swift-ios-class/swift-%E5%A4%A7%E5%AE%B6%E4%BE%86%E8%81%8A%E5%A4%A9-%E9%80%A3%E6%8E%A5firestore-2ce3b3b4597e?source=rss-8c065ad30be1------2</link>
            <guid isPermaLink="false">https://medium.com/p/2ce3b3b4597e</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[firestore]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[張庭瑋]]></dc:creator>
            <pubDate>Thu, 24 Dec 2020 13:19:03 GMT</pubDate>
            <atom:updated>2020-12-25T08:25:25.540Z</atom:updated>
            <content:encoded><![CDATA[<p>firebase其實還有一個 realtime database，不過感覺都快要被放棄了…這次用的是主推的fireStore</p><h4>連接資料庫</h4><p>打開 firebase後點選右邊的 cloud fireStore，新增一個資料庫</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vHqJhitNxSGGJMLdRJNmpg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iFBEiIlIaoh1yuIjx3Tyyg.png" /></figure><p>選擇測試模式</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0rJUakJZ1C2gb2VYZhmWAg.png" /></figure><p>由於之前已經在串接登入及註冊時順手安裝 firestore了，這裡可以直接跳過安裝步驟</p><p>要使用時只要插入以下的程式碼就能使用了</p><pre><strong>let</strong> db = Firestore.firestore()</pre><p>回到聊天室主頁，新增送出訊息的 IBAction</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fy2XThxxYctj676y5qwg2g.png" /></figure><p>在有登入且訊息不為空時儲存到 firestore</p><pre><a href="http://twitter.com/IBAction">@IBAction</a> func sendMessage(_ sender: UIControl) {<br>        if let messageBody = messageInput.text, let account = Auth.auth().currentUser?.email {<br>            <br>            let time = Date()<br>            <br>            db.collection(&quot;messages&quot;).addDocument(data: [&quot;account&quot;:  <br>            account, &quot;message&quot;: messageBody, &quot;time&quot;: time]) {  <br>            (error) in<br>                if let error = error {<br>                    print(error.localizedDescription)<br>                } else {<br>                    print(&quot;Successfully saved data.&quot;)<br>                    self.messageInput.text = nil<br>                }<br>            }<br>        }   <br>    }</pre><p>然後在畫面載入時向 firestore取得訊息列表</p><pre>    // 不需要假資料了<br>    var messages: [Message] = []<br>    <br>    override func viewDidLoad() {<br>        super.viewDidLoad()<br>        <br>        ...<br>        <br>        loadMessages()<br>    }</pre><pre>func loadMessages(){<br>        messages = []<br>        <br>        db.collection(&quot;messages&quot;).getDocuments { (querySnapshot, <br>        error) in<br>            if let error = error {<br>                print(error.localizedDescription)<br>            } else {<br>                if let snapshotDocument = querySnapshot?.documents {<br>                    for doc in snapshotDocument {<br>                        let data = doc.data()</pre><pre>// 確認值不為空</pre><pre>if let account = data[&quot;account&quot;] as? String, let message = data[&quot;message&quot;] as? String, let timestamp = data[&quot;time&quot;] as? Timestamp {</pre><pre>// 解析timestamp<br>                            let time = timestamp.dateValue()<br>                            let newMessage = Message(sender: account, content: message, time: time)<br>                            <br>                            self.messages.append(newMessage)<br>                            <br>                            DispatchQueue.main.async {<br>                                self.messageTableView.reloadData()<br>                            }<br>                            <br>                        } else {<br>                            print(&quot;sth wrong&quot;)<br>                        }<br>                        <br>                    }<br>                }<br>            }<br>        }<br>        <br>    }</pre><p>不過這種寫法只會在初次取得資料，在訊息有增加時畫面不會有所變化，因此這裡要改用 <strong>addSnapshotListener</strong></p><pre>func loadMessages(){<br>        messages = []<br>        <br>        db.collection(&quot;messages&quot;).<strong>addSnapshotListener</strong> {  <br>        (querySnapshot, error) in        <br>        // db.collection(&quot;messages&quot;).getDocuments { (querySnapshot, <br>        error) in</pre><p>不過這麼一來，由於清空資料的動作在 closure外側，導致每次抓取資料時不會清空現有的訊息，因此可以把清空的動作放進 closure中</p><pre>func loadMessages(){</pre><pre>db.collection(&quot;messages&quot;).addSnapshotListener {   <br>        (querySnapshot, error) in<br>            <strong>self.messages = []</strong></pre><p>接著因為訊息取回來順序是亂的，因此利用 timestamp來排序</p><pre>db.collection(&quot;messages&quot;)<strong>.order(by: &quot;time&quot;)</strong>.addSnapshotListener {   <br>        (querySnapshot, error) in<br>        ...</pre><p>如此一來取回的資料都是經過時間排序的</p><h4>鍵盤擋住輸入框</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/439/1*2tnUBi4hG19Rj5GhxhDkBw.png" /></figure><p>如同上圖，現在鍵盤升起來會擋到訊息框，要調整也不是容易的事，畢竟手機型號不同鍵盤尺寸也不同，這個時候可以使用第三方套件 <strong>IQKeyboardManager</strong></p><p><a href="https://github.com/hackiftekhar/IQKeyboardManager">GitHub - hackiftekhar/IQKeyboardManager: Codeless drop-in universal library allows to prevent issues of keyboard sliding up and cover UITextField/UITextView. Neither need to write any code nor any setup required and much more.</a></p><pre>pod &#39;IQKeyboardManagerSwift&#39;</pre><p>嗯…原本想用的</p><p>但發現用起來目前不支援botttom tabbar，位置會怪怪的，只好自己來寫功能，概念上就是在鍵盤出現時整個 view上移，然後修正 textfield和 tableview的條件</p><pre>extension ChatMainViewController {<br>    override func viewWillAppear(_ animated: Bool) {<br>        super.viewWillAppear(animated)</pre><pre>// 加入監聽 <br>        NotificationCenter.default.addObserver(self, selector: <br>        #selector(keyboardWillDisappear), name: <br>        UIResponder.keyboardWillHideNotification, object: nil)</pre><pre>NotificationCenter.default.addObserver(self, selector:   <br>        #selector(keyboardWillAppear), name:  <br>        UIResponder.keyboardWillShowNotification, object: nil)</pre><pre>}<br>    <br>    <a href="http://twitter.com/objc">@objc</a> func keyboardWillAppear(_ notification: Notification) {<br>        if let keyboardFrame: NSValue = notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue {<br>            let keyboardRectangle = keyboardFrame.cgRectValue<br>            // 取得鍵盤高度<br>            let keyboardHeight = keyboardRectangle.height<br>            // 取得tabbar高度<br>            let tabbarHeight = messageWrapper.safeAreaInsets.bottom<br>            <br>            // 移動view的基準點到一個鍵盤高<br>            messageWrapper.frame.origin.y = -keyboardHeight<br>            // textfield底部條件改為tabbar高度<br>            textfieldBottomConstraints.constant = tabbarHeight<br>            // tableview頂部條件向下壓一個鍵盤高<br>            tableViewTopConstraints.constant = keyboardHeight<br>            messageWrapper.layoutIfNeeded()<br>            <br>            // tableview滾到底部<br> let indexPath = IndexPath(row: messages.count - 1, section: 0)<br>            messageTableView.scrollToRow(at: indexPath, at: .top, animated: false)<br>        }<br>    }<br>    <br>    <a href="http://twitter.com/objc">@objc</a> func keyboardWillDisappear() {<br>        // 復原<br>        messageWrapper.frame.origin.y = 0<br>        textfieldBottomConstraints.constant = 0<br>        tableViewTopConstraints.constant = 0<br>        messageWrapper.layoutIfNeeded()<br>    }<br>    <br>    override func viewWillDisappear(_ animated: Bool) {<br>        super.viewWillDisappear(animated)<br>        // 移除監聽<br>        NotificationCenter.default.removeObserver(self)<br>    }<br>}</pre><p>然而此時點擊訊息畫面（tableView）時，鍵盤並不會自動收起來，這時可以在鍵盤升起來時監聽手勢，落下來時移除監聽</p><pre><a href="http://twitter.com/objc">@objc</a> func keyboardWillAppear(_ notification: Notification) {<br>        if let keyboardFrame: NSValue = notification.userInfo? <br>        [UIResponder.keyboardFrameEndUserInfoKey] as? NSValue {<br>            ......<br>            <br>            // add gesture recognizer<br>            let tap = UITapGestureRecognizer(target: self, action: <br>            #selector(UIInputViewController.dismissKeyboard))<br>            self.messageTableView.addGestureRecognizer(tap)<br>        }<br>    }<br>    <br><a href="http://twitter.com/objc">@objc</a> func keyboardWillDisappear() {</pre><pre>// remove gesture recognizer                    <br>             self.messageTableView.gestureRecognizers?<br>             .forEach(self.messageTableView.removeGestureRecognizer)</pre><pre>}</pre><p>由於監聽手勢會影響其他 action，像是點擊事件，所以這裡選擇鍵盤升起時才監聽，鍵盤未升起時還是能點擊泡泡</p><p>最後把決定 cell種類的判斷式換掉</p><pre>func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -&gt; UITableViewCell {<br>        // decide self or other<br>        var isSelf = false<br>        <br>        if <strong>messages[indexPath.row].sender == Auth.auth().currentUser?.email</strong> {<br>            isSelf = true<br>        }<br>//        if indexPath.row % 2 == 0 {<br>//            testResult = true<br>//        }</pre><p>這樣就可以比對訊息是否為自己發送的</p><p>最後錄個總成果：</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Fj3o1E5-ucnk%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3Dj3o1E5-ucnk&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2Fj3o1E5-ucnk%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/78a709260804866499341a1bef1f68f7/href">https://medium.com/media/78a709260804866499341a1bef1f68f7/href</a></iframe><p>GitHub：</p><p><a href="https://github.com/KakeruChang/HoloIntroduction/commit/8e593329f2594cfc654b5bab0d003e19846697dc">feat:complete 1st version of chat · KakeruChang/HoloIntroduction@8e59332</a></p><p>這個 App能做的東西還有很多，例如說傳送含照片的message，或是添加登入失敗的警告，或者是上傳大頭貼…等，不過也練習到了非常多的東西，希望以後有機會也能參與這種產品的開發。</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2ce3b3b4597e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/peter-pan-swift-ios-class/swift-%E5%A4%A7%E5%AE%B6%E4%BE%86%E8%81%8A%E5%A4%A9-%E9%80%A3%E6%8E%A5firestore-2ce3b3b4597e">[Swift] 大家來聊天-連接FireStore</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[[Swift] 大家來聊天-客製訊息泡泡]]></title>
            <link>https://medium.com/peter-pan-swift-ios-class/swift-%E5%A4%A7%E5%AE%B6%E4%BE%86%E8%81%8A%E5%A4%A9-%E5%AE%A2%E8%A3%BD%E8%A8%8A%E6%81%AF%E6%B3%A1%E6%B3%A1-d989a79935ac?source=rss-8c065ad30be1------2</link>
            <guid isPermaLink="false">https://medium.com/p/d989a79935ac</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[snapkit]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[張庭瑋]]></dc:creator>
            <pubDate>Thu, 24 Dec 2020 08:16:42 GMT</pubDate>
            <atom:updated>2021-07-29T08:22:41.900Z</atom:updated>
            <content:encoded><![CDATA[<p>接續上一篇，要來做訊息的泡泡</p><p><a href="https://b97201019.medium.com/swift-%E5%A4%A7%E5%AE%B6%E4%BE%86%E8%81%8A%E5%A4%A9-%E4%B8%B2%E6%8E%A5firebase%E7%99%BB%E5%85%A5%E7%99%BB%E5%87%BA-dd4807cbbdc9">[Swift] 大家來聊天-串接Firebase登入登出</a></p><h3>Table datasource and delegate</h3><p>選取 cell後輸入 identifier</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nKhT67P_PlpDLe-x_6vpcA.png" /></figure><p>新增 Message內容</p><pre>struct Message {<br>    let sender: String // email<br>    let content: String<br>    let time: Date<br>    let bgColor: UIColor?<br>    let textColor: UIColor?<br>    let img: String?<br>}</pre><p>然後在主畫面宣告一些假資料</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XoPdjySBzzfWh0iawPlccw.png" /></figure><p>接著將 controller自己作為 table view的資料來源，同時實作 UITableViewDataSource的兩個方法，這裡要注意創造 cell時用的 identifier便是一開始取的 identifier</p><pre>class ChatMainViewController: UIViewController {<br>    <br>    <a href="http://twitter.com/IBOutlet">@IBOutlet</a> weak var messageTableView: UITableView!<br>    ...<br>    <br>    override func viewDidLoad() {<br>        super.viewDidLoad()<br>        <br>        <strong>messageTableView.dataSource = self</strong><br>        <br>        ...</pre><pre>//MARK: - UITableViewDataSource<br>extension ChatMainViewController: UITableViewDataSource {<br>    func tableView(_ tableView: UITableView, numberOfRowsInSection <br>    section: Int) -&gt; Int {<br>        return <strong>messages.count</strong><br>    }<br>    <br>    func tableView(_ tableView: UITableView, cellForRowAt indexPath: <br>    IndexPath) -&gt; UITableViewCell {<br>        let cell = tableView.dequeueReusableCell(withIdentifier:  <br>        <strong>&quot;ReusableCell&quot;</strong>, for: indexPath)<br>        cell.textLabel?.text = &quot;This is a cell&quot;<br>        return cell<br>    }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/884/1*pqJbX0Vox1Iiwpy2lkXApA.png" /><figcaption>顯示三個 cell</figcaption></figure><p>接著就要將訊息替換成實際的內容</p><pre>func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -&gt; UITableViewCell {<br>        let cell = tableView.dequeueReusableCell(withIdentifier:       <br>        &quot;ReusableCell&quot;, for: indexPath)<br>        cell.textLabel?.text = <strong>messages[indexPath.row].content</strong><br>        return cell<br>}</pre><p>接著加入 <strong>UITableViewDelegate</strong></p><pre>override func viewDidLoad() {<br>        super.viewDidLoad()<br>        <br>        messageTableView.dataSource = self<br>        <strong>messageTableView.delegate = self</strong><br>        ......</pre><pre>//MARK: - UITableViewDelegate<br>extension ChatMainViewController: <strong>UITableViewDelegate</strong> {<br>    <br>}</pre><p>然後在裡面增加 didSelectRowAt方法，這樣就能知道第幾個 cell被選取了</p><pre>extension ChatMainViewController: UITableViewDelegate {<br>    <strong>func tableView(_ tableView: UITableView, didSelectRowAt <br>    indexPath: IndexPath) {<br>        print(indexPath.row)<br>    }</strong><br>}</pre><h3>客製 table cell</h3><p>在 View資料夾中新增一個 UITableViewClass的子 Class檔案，同時勾選新增 XIB檔案</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_mcYsBiBAnsCVwcgrZcx5w.png" /></figure><p>此時在 xib設計的樣式會被cell拿來使用</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o1jts2UYRCxr4Ip2gHZenQ.png" /></figure><p>不過由於要分成幾種 cell，再多開個 cell的資料夾並先完成自己發言的 cell</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EbbcwUbMue1-JZfJQ5LhCw.png" /></figure><p>建立 IBOutlet</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-OxcUP_S8s3O2eEoPuW4Wg.png" /></figure><p>外層的 cell加上 identifier</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-ULO-X-PpiqosHBYBvQJig.png" /></figure><p>接著回到主畫面的 Controller，nibName輸入 xib的檔案名，forCellReuseIdentifier輸入 cell的identifier</p><pre>class ChatMainViewController: UIViewController {<br>    <br>    ...<br>    <br>    override func viewDidLoad() {<br>        ...<br>        <br>        messageTableView.register(UINib(nibName: <br>        &quot;<strong>MessageSelfTextCell</strong>&quot;, bundle: nil), forCellReuseIdentifier:  <br>        &quot;<strong>ReusableCell</strong>&quot;)<br>    }</pre><p>接著要讓 cell的範圍縮小為剛剛客製的 cell，並傳入假資料內容</p><pre>//MARK: - UITableViewDataSource<br>extension ChatMainViewController: UITableViewDataSource {<br>    ...<br>    <br>    func tableView(_ tableView: UITableView, cellForRowAt indexPath: <br>   IndexPath) -&gt; UITableViewCell {<br>        let cell = tableView.dequeueReusableCell(withIdentifier:   <br>        &quot;ReusableCell&quot;, for: indexPath) <strong>as! MessageSelfTextCell</strong></pre><pre>cell.<strong>messageLabel</strong>.text = messages[indexPath.row].content<br>        return cell<br>    }<br>}</pre><p>原本的 cell已經用不到了可以刪除</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5jShRrnmL3mx8mxfS1cufw.png" /></figure><p>剛剛寫的 cell已經出現在畫面上了</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/842/1*mZKhpttt8e88LUZDAFn9eg.png" /></figure><p>不過這種對話框顯然不夠好看，所以可以修改一下樣式，不過 layout的修改不是重點，所以這裡提幾個遇上的麻煩</p><h4>如何畫對話框邊邊的角？</h4><p>可以使用 UIBezierPath搭配 CAShapeLayer，如果有對話框底圖的話也可以使用 <strong>resizebleImageWithCapInsets</strong>，不過因為我沒有底圖所以選擇UIBezierPath</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1sfQ3B52ubtNQ82L-hXDpQ.png" /><figcaption>這裡我寫了一個 drawMessageAngle 的 function來畫圖</figcaption></figure><h4>如何讓泡泡隨著訊息伸縮？</h4><p>讓泡泡跟內部的 label加上固定距離的條件，泡泡本身則是對於某一邊加上大於等於的條件（像我是設定≥10），這樣泡泡便不會每次都頂到最邊邊去</p><h4>角會畫兩次的原因？</h4><p>要畫角時可以寫在 cell中的 layoutSubviews()</p><pre>override func layoutSubviews() {<br>        super.layoutSubviews()</pre><pre>drawMessageAngle(messageBubble: messageBubble, isSelf:  <br>        isSelf, bubbleColor: bubbleColor)<br>    }</pre><p>不過因為 autolayout又會再執行一次 layoutSubviews()，導致角又被畫一次，所以會導致角重複出現在不同的位置，這時只要加上 layoutIfNeeded()就能正確取得角 layout完的位置，而不會看到兩個角</p><pre>override func layoutSubviews() {<br>        super.layoutSubviews()<br>        <strong>contentView.layoutIfNeeded()</strong></pre><pre>drawMessageAngle(messageBubble: messageBubble, isSelf:  <br>        isSelf, bubbleColor: bubbleColor)<br>    }</pre><h4>如何做成 line或 fb那種只有泡泡能點的效果</h4><p>首先要關掉 tableView的單選效果防止背景反灰</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/528/1*7S7CjmS0afMgrS0gnUdiAQ.png" /></figure><p>然後只要讓泡泡是 UIButton，或是可以點選的 UIView(繼承 UIControl)，如果是用 UIView，對於樣式的客製化可能就要多用點心（例如要自己在 ibaction加上點選後顏色變深的效果）</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/431/1*kFd4QAYx5eamsgloPa8N1Q.gif" /><figcaption>能點選的泡泡</figcaption></figure><h3>按讚</h3><p>這次就來試試看如何只用 code完成排版及 layout</p><p>首先在新增的 class生成想要的元素</p><pre>class MessageGoodImgCell: UITableViewCell {</pre><pre>let bubble = UIView()<br>    let goodWrapper = UIControl()<br>    let good = UIImageView()<br>    let timeLabel = UILabel()<br>    var isSelf: Bool = true</pre><p>接著在 init的地方加上各元素的 NSLayoutConstraint</p><pre>override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {<br>        print(&quot;override init?&quot;)<br>        //<br>        super.init(style: style, reuseIdentifier: reuseIdentifier)<br>        <br>        good.image = UIImage(systemName: &quot;hand.thumbsup.fill&quot;)<br>        timeLabel.font = timeLabel.font.withSize(12)<br>        <br>        contentView.addSubview(bubble)<br>        bubble.addSubview(goodWrapper)<br>        goodWrapper.addSubview(good)<br>        bubble.addSubview(timeLabel)<br>        <br>        bubble.translatesAutoresizingMaskIntoConstraints = false<br>        let bubbleHeightConstraint = NSLayoutConstraint(item: bubble, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 60)<br>        bubbleHeightConstraint.isActive = true<br>        NSLayoutConstraint(item: bubble, attribute: .trailing, relatedBy: .equal, toItem: contentView, attribute: .trailing, multiplier: 1, constant: -10).isActive = true<br>        NSLayoutConstraint(item: bubble, attribute: .leading, relatedBy: .equal, toItem: contentView, attribute: .leading, multiplier: 1, constant: 10).isActive = true<br>        let bubbleTopConstraint = NSLayoutConstraint(item: bubble, attribute: .top, relatedBy: .equal, toItem: contentView, attribute: .top, multiplier: 1, constant: 10)<br>        bubbleTopConstraint.priority = UILayoutPriority(rawValue: 999)<br>        bubbleTopConstraint.isActive = true<br>        let bubbleBottomConstraint = NSLayoutConstraint(item: bubble, attribute: .bottom, relatedBy: .equal, toItem: contentView, attribute: .bottom, multiplier: 1, constant: -10)<br>        bubbleBottomConstraint.priority = UILayoutPriority(rawValue: 999)<br>        bubbleBottomConstraint.isActive = true<br>        <br>        goodWrapper.translatesAutoresizingMaskIntoConstraints = false<br>        NSLayoutConstraint(item: goodWrapper, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 40).isActive = true<br>        NSLayoutConstraint(item: goodWrapper, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 40).isActive = true<br>        NSLayoutConstraint(item: goodWrapper, attribute: .trailing, relatedBy: .equal, toItem: bubble, attribute: .trailing, multiplier: 1, constant: -10).isActive = true<br>        NSLayoutConstraint(item: goodWrapper, attribute: .top, relatedBy: .equal, toItem: bubble, attribute: .top, multiplier: 1, constant: 10).isActive = true<br>        NSLayoutConstraint(item: goodWrapper, attribute: .bottom, relatedBy: .equal, toItem: bubble, attribute: .bottom, multiplier: 1, constant: -10).isActive = true<br>        <br>        good.translatesAutoresizingMaskIntoConstraints = false<br>        NSLayoutConstraint(item: good, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 40).isActive = true<br>        NSLayoutConstraint(item: good, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 40).isActive = true<br>        NSLayoutConstraint(item: good, attribute: .trailing, relatedBy: .equal, toItem: goodWrapper, attribute: .trailing, multiplier: 1, constant: 0).isActive = true<br>        NSLayoutConstraint(item: good, attribute: .leading, relatedBy: .equal, toItem: goodWrapper, attribute: .leading, multiplier: 1, constant: 0).isActive = true<br>        NSLayoutConstraint(item: good, attribute: .top, relatedBy: .equal, toItem: goodWrapper, attribute: .top, multiplier: 1, constant: 0).isActive = true<br>        NSLayoutConstraint(item: good, attribute: .bottom, relatedBy: .equal, toItem: goodWrapper, attribute: .bottom, multiplier: 1, constant: 0).isActive = true<br>        <br>        timeLabel.translatesAutoresizingMaskIntoConstraints = false<br>        NSLayoutConstraint(item: timeLabel, attribute: .trailing, relatedBy: .equal, toItem: good, attribute: .leading, multiplier: 1, constant: 5).isActive = true<br>        NSLayoutConstraint(item: timeLabel, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 60).isActive = true<br>        NSLayoutConstraint(item: timeLabel, attribute: .bottom, relatedBy: .equal, toItem: bubble, attribute: .bottom, multiplier: 1, constant: -10).isActive = true<br>    }<br>    <br>    required init?(coder: NSCoder) {<br>        print(&quot;required init?&quot;)<br>        super.init(coder: coder)!<br>    }</pre><p>嗯…總之就是把平常幹的事情 code化，可以看得出來非常的…長</p><p>這時候換個套件上吧</p><p><a href="https://github.com/SnapKit/SnapKit">GitHub - SnapKit/SnapKit: A Swift Autolayout DSL for iOS &amp; OS X</a></p><pre>pod &#39;SnapKit&#39;, &#39;~&gt; 5.0.0&#39;</pre><p>這時候剛剛的 code會變得如何呢…</p><pre>override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {<br>        print(&quot;override init?&quot;)<br>        //<br>        super.init(style: style, reuseIdentifier: reuseIdentifier)<br>        <br>        good.image = UIImage(systemName: &quot;hand.thumbsup.fill&quot;)<br>        timeLabel.font = timeLabel.font.withSize(12)<br>        <br>        contentView.addSubview(bubble)<br>        bubble.addSubview(goodWrapper)<br>        goodWrapper.addSubview(good)<br>        bubble.addSubview(timeLabel)<br>        <br>        bubble.snp.makeConstraints { (make) -&gt; Void in<br>            make.height.equalTo(60)<br>            make.left.right.equalToSuperview().inset(10)<br>            make.top.bottom.equalToSuperview().inset(10).priority(999)<br>        }</pre><pre>goodWrapper.snp.makeConstraints { (make) -&gt; Void in<br>            make.height.width.equalTo(40)<br>            make.right.top.bottom.equalToSuperview().inset(10)<br>        }</pre><pre>good.snp.makeConstraints { (make) -&gt; Void in<br>            make.height.width.equalTo(40)<br>            make.left.right.top.bottom.equalToSuperview()<br>        }</pre><pre>timeLabel.snp.makeConstraints { (make) -&gt; Void in<br>            make.width.equalTo(60)<br>            make.right.equalTo(good.snp.left).inset(5)<br>            make.bottom.equalToSuperview().inset(10)<br>        }<br>    }</pre><p>這裡不得不說原生的 NSLayoutConstraint雖然不難懂，但實在太長了…當畫面一複雜就很難整理</p><p>註冊 cell時的方式也要改變（因為沒有xib就沒地方設定 identifier）</p><pre>// cell with xib<br>messageTableView.register(UINib(nibName: &quot;MessageOtherTextCell&quot;, bundle: nil), forCellReuseIdentifier: &quot;ReusableCellOther&quot;)</pre><pre>// cell made by code only<br>messageTableView.register(MessageGoodImgCell.self, forCellReuseIdentifier: &quot;ReusableGoodImgCell&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/846/1*EzZdmZ2vxHD4RCeZY6Albw.png" /></figure><p>由於是用 code來寫，內容的調整就靈活很多，所以當要製作對方按讚的 cell時，直接在原 class加點條件修改，這裡利用原本設置的<strong>var isSelf: Bool</strong>來判斷是否為自己的發言，然後在 <strong>layoutSubviews()</strong>時進行條件的修改</p><pre>override func layoutSubviews() {<br>        super.layoutSubviews()</pre><pre>if isSelf == false {<br>            setToOtherCell()<br>        } else {<br>            setToSelfCell()<br>        }<br>        contentView.layoutIfNeeded()<br>}</pre><p>然後補上兩邊的設定</p><pre>    func setToSelfCell(){<br>        otherImageWrapper.removeFromSuperview()<br>        <br>        goodWrapper.snp.remakeConstraints { (make) -&gt; Void in<br>            make.height.width.equalTo(40)<br>            make.right.top.bottom.equalToSuperview().inset(10)<br>        }</pre><pre>good.snp.remakeConstraints { (make) -&gt; Void in<br>            make.height.width.equalTo(40)<br>            make.left.right.top.bottom.equalToSuperview()<br>        }</pre><pre>timeLabel.snp.remakeConstraints { (make) -&gt; Void in<br>            make.width.equalTo(60)<br>            make.right.equalTo(goodWrapper.snp.left).inset(5)<br>            make.bottom.equalToSuperview().inset(10)<br>        }<br>    }<br>    <br>    func setToOtherCell(){<br>        otherImage.image = UIImage(systemName: &quot;person.fill&quot;)<br>        bubble.addSubview(otherImageWrapper)<br>        otherImageWrapper.addSubview(otherImage)<br>        <br>        otherImageWrapper.snp.remakeConstraints { (make) -&gt; Void in<br>            make.width.height.equalTo(40)<br>            make.bottom.top.equalToSuperview().inset(10)<br>            make.left.equalToSuperview().inset(0)<br>        }<br>        <br>        otherImage.snp.remakeConstraints { (make) -&gt; Void in<br>            make.width.height.equalTo(40)<br>            make.bottom.left.right.top.equalToSuperview()<br>        }<br>        <br>        goodWrapper.snp.remakeConstraints { (make) -&gt; Void in<br>            make.height.width.equalTo(40)<br>            make.left.equalTo(otherImageWrapper.snp.right).offset(10)<br>            make.bottom.equalToSuperview().inset(10)<br>        }</pre><pre>timeLabel.snp.remakeConstraints { (make) -&gt; Void in<br>            make.width.equalTo(60)<br>            make.left.equalTo(goodWrapper.snp.right).offset(5)<br>            make.bottom.equalToSuperview().inset(10)<br>        }<br>    }</pre><p>然後在 tableView中給值以判斷要生產哪種 cell（這裡先隨便給值讓 cell左右切換）</p><pre>// MARK: - UITableViewDataSource<br>extension ChatMainViewController: UITableViewDataSource {<br>    ...<br>    // MessageTableViewCell<br>    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -&gt; UITableViewCell {<br>        // decide self or other<br>        var <strong>testResult</strong> = false<br>        if indexPath.row % 2 == 0 {<br>            testResult = true<br>        }</pre><pre>// self press good<br>        if let img = messages[indexPath.row].img, img == &quot;good&quot; {<br>            let goodCell = tableView.dequeueReusableCell(withIdentifier: &quot;ReusableGoodImgCell&quot;, for: indexPath) as! MessageGoodImgCell<br>            goodCell.timeLabel.text = messages[indexPath.row].getMessageTimeString()<br>            goodCell.isSelf = <strong>testResult</strong><br> <br>            return goodCell<br>        }<br>        <br>        ...<br>}</pre><p>成果：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/846/1*dmrtQK7UcqCIolU5HQ2usQ.png" /></figure><p>下一篇要把這些成果存進資料庫裡，每次都能像 fb那些以樣呈現過往的對話紀錄</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d989a79935ac" width="1" height="1" alt=""><hr><p><a href="https://medium.com/peter-pan-swift-ios-class/swift-%E5%A4%A7%E5%AE%B6%E4%BE%86%E8%81%8A%E5%A4%A9-%E5%AE%A2%E8%A3%BD%E8%A8%8A%E6%81%AF%E6%B3%A1%E6%B3%A1-d989a79935ac">[Swift] 大家來聊天-客製訊息泡泡</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[[Swift] 大家來聊天-串接Firebase登入登出]]></title>
            <link>https://medium.com/peter-pan-swift-ios-class/swift-%E5%A4%A7%E5%AE%B6%E4%BE%86%E8%81%8A%E5%A4%A9-%E4%B8%B2%E6%8E%A5firebase%E7%99%BB%E5%85%A5%E7%99%BB%E5%87%BA-dd4807cbbdc9?source=rss-8c065ad30be1------2</link>
            <guid isPermaLink="false">https://medium.com/p/dd4807cbbdc9</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[firebase]]></category>
            <dc:creator><![CDATA[張庭瑋]]></dc:creator>
            <pubDate>Wed, 23 Dec 2020 03:43:45 GMT</pubDate>
            <atom:updated>2020-12-25T08:25:04.539Z</atom:updated>
            <content:encoded><![CDATA[<p>這次想做的是聊天的 App，目標是做登入註冊加上聊天的功能</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yEt7HgPlfZEWqWQRZi47vg.png" /><figcaption>隨便做點 layout</figcaption></figure><p>在登入與註冊與主畫面建立segue way</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-eb6MuTY8sLGdtQQqWNMxg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U62zEb8yb2218PKSNcRZ8w.png" /></figure><p>接著把初始畫面的按鈕與對應頁面建立segue way</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/917/1*-Ph-uZryxJQY4ZEJp4WsUw.png" /><figcaption>順便調整位置</figcaption></figure><p>把連接至主畫面的兩個 segue way的 identifier取名</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7tlZrxdaURySOBNQpZoW6A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VwBGCktWVusbC26vgnsWdA.png" /></figure><p>接著開始做一些功能</p><h3>開頭動畫</h3><p>首先把 Image用 View包裹起來，並加上動畫：不間斷地調整透明度營造閃爍感</p><pre><a href="http://twitter.com/IBOutlet">@IBOutlet</a> weak var chatImageWrapper: UIView!<br>    <br>    override func viewDidLoad() {<br>        ...</pre><pre>        UIView.animate(withDuration: 1,<br>                                   delay: 0,<br>                                   options: [.autoreverse, .repeat],<br>                                   animations: {<br>                                    self.chatImageWrapper.alpha = 0<br>                                   },<br>                                   completion: nil)<br>    }</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bJTcsCyoLJtdTriqeddPQw.png" /></figure><p>而按鈕的文字則只在初次播放動畫，同時營造打字效果</p><pre>        let signupText = &quot;Sign up&quot;<br>        let loginText = &quot;Log in&quot;<br>        var tmpSignupText = &quot;&quot;<br>        var tmpLoginText = &quot;&quot;<br>        for (i, letter) in signupText.enumerated() {<br>            Timer.scheduledTimer(withTimeInterval: 0.2 * Double(i), repeats: false) { (Timer) in<br>                tmpSignupText.append(letter)<br>                self.homeSignupButton.setTitle(tmpSignupText, for: .normal)<br>            }<br>        }<br>        for (j, letter) in loginText.enumerated() {<br>            Timer.scheduledTimer(withTimeInterval: 0.2 * Double(j), repeats: false) { (Timer) in<br>                tmpLoginText.append(letter)<br>                self.homeLoginButton.setTitle(tmpLoginText, for: .normal)<br>            }<br>        }</pre><p>這裡有一點很重要的地方是，如果是使用預設的按鈕，在更新文字時整個按鈕會閃一下，所以如果間隔只設定 0.1秒會1秒中閃十下…，這裡可以把按鈕 Type改成 <strong>Custom</strong>就可以解決問題了</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uioKitXit6yT1Oum4yerzw.png" /></figure><p>效果：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/431/1*MatUuK_KrCadk4QbZAksmg.gif" /></figure><h3>安裝第三方套件</h3><p>這次想要使用 <a href="https://cocoapods.org/pods/CLTypingLabel">CLTypingLabel</a>，在此之前要先用 terminal安裝 cocoapods</p><pre>sudo gem install cocoapods</pre><p>接著將終端機導向到專案目錄並創建 pod檔案</p><pre>cd 專案目錄路徑<br>pod init</pre><p>這時專案資料夾會多出一個檔案來，用 Xcode打開</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/364/1*bGjUd5bYWgZDoULK4APEpA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CCoXUeu5xqwMZJBKu5lizA.png" /></figure><p>將 <strong>pod ‘CLTypingLabel’</strong>貼進 Podfile</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/884/1*30JiPuZazIdYvCfDEwG1LA.png" /></figure><p>接著安裝 CLTypingLabel</p><pre>pod install</pre><p>然後從現在開始，要使用 <strong>.xcworkspace</strong>而非原來的 .xcodeproj</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gfmmGmR5BSuJmZIkGGlPRA.png" /><figcaption>使用白底藍字的</figcaption></figure><p>新增一個 Label並將 <strong>Class</strong>改為 <strong>CLTypingLabel</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TR1nx5kntmus5ZbIIKTEyQ.png" /></figure><p>同時更改 code</p><pre><strong>@IBOutlet</strong> <strong>weak</strong> <strong>var</strong> testLabel: UILabel!</pre><pre>==&gt;</pre><pre><strong>@IBOutlet</strong> <strong>weak</strong> <strong>var</strong> testLabel: CLTypingLabel!</pre><p>同時第三方插件要記得 import</p><pre>import CLTypingLabel</pre><p>之後只要更改文字就能有一樣的效果</p><pre>override func viewDidLoad() {<br>        ...</pre><pre>        testLabel.text = &quot;Let&#39;s chat!&quot;<br>    }</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/431/1*UXeHFO4ohpEXrXmS6KV-Rg.gif" /></figure><p>不過由於我後來才發現這是 UILabel的替代方案而不是button的，所以這個插件之後應該不會繼續用…</p><h3>會員註冊及登入</h3><p>這裡用的是 google底下的 firebase</p><p><a href="https://firebase.google.com/">Firebase | Google&#39;s Mobile and Web App Development Platform</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fDVvVHYphBxW7Zuy7OtgxA.png" /></figure><p>首先先創建專案</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/772/1*K7l-Icy43IW5r8lhGNJFEA.png" /></figure><p>輸入名字和選擇一些資訊便可創建專案</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dgAOz6drYiFiYfVPEEXxTw.png" /></figure><p>進來主畫面後先點擊左邊的 ios圖示</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lRltTIwbqaSISR2mjMMpuQ.png" /></figure><p>輸入 bundle id，其他的上架時才需要用到</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NXqxSIJgkPC7rSwqxxQAyg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/792/1*fyjwFSSXYcUcM-glzm0BNw.png" /><figcaption>在 xcode的專案資訊頁面可以找到</figcaption></figure><p>將 plist下載後放入專案資料夾</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LGSouht3IqBLkikjY9xgag.png" /></figure><p>接著在 Podfile新增需要的套件（認證及資料庫）</p><pre>pod &#39;Firebase/Auth&#39;<br>pod &#39;Firebase/Firestore&#39;</pre><p>然後在終端機執行安裝</p><pre>pod install</pre><p>然後在 <strong>AppDelegate.swift</strong>新增以下代碼</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SMBhJmq659VZets0aHBo3Q.png" /><figcaption>新增旁邊有複製按鈕的代碼即可</figcaption></figure><p>接著回到首頁選擇 Authentication</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/892/1*d6M1lD2PaasFdnU0O9hDrg.png" /></figure><p>接著開啟 email認證</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z5ZAkkIuJ2XcSQ4xY_smuQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IFt6nMaQVrTpPwkLe0-tAw.png" /></figure><p>基本設定到此結束</p><h4>註冊</h4><p>在 signup的 controller加入</p><pre>import UIKit<br><strong>import Firebase</strong></pre><pre>class ChatSignUpViewController: UIViewController {</pre><pre>   ...<br>    <br><strong>    </strong><a href="http://twitter.com/IBAction"><strong>@IBAction</strong></a><strong> func signupPressed(_ sender: UIButton) {<br>        Auth.auth().createUser(withEmail: email, password: password) <br>        { authResult, error in<br>          // ...<br>        }<br>    }</strong><br>    <br>}</pre><p>接著將 textfield的值傳入，由於 textfield的 text值是 optional，所以需要 optional binding</p><pre><a href="http://twitter.com/IBOutlet">@IBOutlet</a> weak var accountTextField: UITextField!<br><a href="http://twitter.com/IBOutlet">@IBOutlet</a> weak var passwordTextField: UITextField!</pre><pre>override func viewDidLoad() {<br>        ...<br>    <br>    <a href="http://twitter.com/IBAction">@IBAction</a> func signupPressed(_ sender: UIButton) {<br>        <br>       <strong> if let account = accountTextField.text , let password = <br>        passwordTextField.text </strong>{<br>            Auth.auth().createUser(withEmail: account, password: <br>            password) { authResult, error in<br>                // ...<br>            }<br>        }<br>    }</pre><p>由於 error也是 optional，所以也要處理</p><pre>Auth.auth().createUser(withEmail: account, password: password) { authResult, error in<br>                <br><strong>            if let error = error {<br>               print(error)                   <br>            } else {<br>               // ...<br>            }</strong><br> }</pre><p>接著複製註冊畫面往主畫面 segue way的 identifier</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Xay--7b_cwuRyby2UpcYFQ.png" /></figure><p>當 error沒發生時導向主畫面</p><pre>Auth.auth().createUser(withEmail: account, password: password) { authResult, error in<br>                <br>                if let error = error {<br>                    print(error)<br>                } else {<br><strong>                    self.performSegue(withIdentifier: <br>                    &quot;SignupToChat&quot;, sender: self)</strong><br>                }<br>            }</pre><h4>登入</h4><p>跟註冊十分相似，在對應的 controller中的登入按鈕的 action中寫入登入程序</p><pre>import Firebase<br>...</pre><pre>Auth.auth().signIn(withEmail: email, password: password) {  <br>authResult, error in<br>  // ...<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q-kF9QlOhhIy6EcCUKhudw.png" /></figure><h4>登出</h4><p>在主畫面的右上角新增 <strong>bar button item</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/868/1*JSPoK6PfV8YrO7E2HrR3tA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/345/1*6-_j2cRa2KhMs_lGF4VRow.png" /></figure><p>建立 IBAction</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/993/1*U6VGFYXEcCX3Idcu0zkewg.png" /></figure><p>貼上 log out 步驟</p><pre>import Firebase</pre><pre>...</pre><pre>let firebaseAuth = Auth.auth()</pre><pre>do {<br>  try firebaseAuth.signOut()<br>} catch let signOutError as NSError {<br>  print (&quot;Error signing out: %@&quot;, signOutError)<br>}</pre><p>最後按下登出按鈕後彈回根view controller（不過這裡因為我的首頁並不是初始頁面的原因，按下登出會彈回上一層的集合頁）</p><pre>do {<br>    try firebaseAuth.signOut()<br>            <br>    <strong>navigationController?.popViewController(animated: true)</strong><br>            <br>} </pre><h4>正確跳回主畫面</h4><p>如果想要解決就必須使用 <strong>unwindSegue</strong></p><p>首先在要回去的頁面加上標記（內容可以為空）</p><pre>class ChatHomeViewController: UIViewController {<br>    ...<br>    <br>    <a href="http://twitter.com/IBAction">@IBAction</a> func backToChatHome(_ unwindSegue: <strong>UIStoryboardSegue</strong>)  <br>   {}</pre><p>主頁面的 view controller拉線至 exit（手動建立 segue），同時命名 segue的 identifier</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/218/1*f-vanNBU3Zga_ONgyAv0Hw.png" /></figure><p>然後更改主頁面的 Log out按鈕的IBAction內容，如此一來點擊按鈕後便能跳回標示的主頁面</p><pre><a href="http://twitter.com/IBAction">@IBAction</a> func logoutPressed(_ sender: Any) {<br>        let firebaseAuth = Auth.auth()<br>        do {<br>            try firebaseAuth.signOut()<br>            print(&quot;log out success&quot;)<br>            <br>            <strong>performSegue(withIdentifier: &quot;backToHome&quot;, sender: self)</strong><br>            <br>        } catch let signOutError as NSError {<br>            print (&quot;Error signing out: %@&quot;, signOutError)<br>        }<br>        <br>    }</pre><p>然後把這一系列頁面的 back按鈕都藏起來</p><pre>override func viewDidLoad() {<br>        super.viewDidLoad()title = &quot;Holo Chat&quot;</pre><pre>       <strong> navigationItem.hidesBackButton = true</strong><br>}</pre><p>並給主畫面的 navbar加上 title</p><pre>override func viewDidLoad() {<br>        super.viewDidLoad()</pre><pre><br>        navigationItem.hidesBackButton = true<br>        <strong>title = &quot;Holo Chat&quot;</strong><br>    }</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/431/1*fbrFgdQwNKxJ94Th2w93Bg.gif" /></figure><p>下一篇會完成一些 cell的功能</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dd4807cbbdc9" width="1" height="1" alt=""><hr><p><a href="https://medium.com/peter-pan-swift-ios-class/swift-%E5%A4%A7%E5%AE%B6%E4%BE%86%E8%81%8A%E5%A4%A9-%E4%B8%B2%E6%8E%A5firebase%E7%99%BB%E5%85%A5%E7%99%BB%E5%87%BA-dd4807cbbdc9">[Swift] 大家來聊天-串接Firebase登入登出</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>