<?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 Jru on Medium]]></title>
        <description><![CDATA[Stories by Jru on Medium]]></description>
        <link>https://medium.com/@jieru04?source=rss-7f58831db4fb------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*ouzvQtmHbzfeRjQtiBFY0A.jpeg</url>
            <title>Stories by Jru on Medium</title>
            <link>https://medium.com/@jieru04?source=rss-7f58831db4fb------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 00:08:06 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jieru04/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[客製化TextField]]></title>
            <link>https://medium.com/@jieru04/%E5%AE%A2%E8%A3%BD%E5%8C%96textfield-a2724e020529?source=rss-7f58831db4fb------2</link>
            <guid isPermaLink="false">https://medium.com/p/a2724e020529</guid>
            <category><![CDATA[textfield]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Jru]]></dc:creator>
            <pubDate>Sun, 13 Apr 2025 14:51:30 GMT</pubDate>
            <atom:updated>2025-04-14T13:14:42.881Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/664/1*HECpSX4e6lE8uKw0UiWbXA.png" /><figcaption>樣式</figcaption></figure><p>由原生 UITextField產生，具有以下功能：</p><ol><li>支援標題顯示：清楚提示欄位輸入目的。</li><li>動態邊框顏色：輸入時動態變更邊框顏色，提升欄位辨識度。</li><li>錯誤訊息提示：驗證失敗時顯示錯誤訊息，協助使用者即時修正。</li><li>自訂右側功能：可自訂是否顯示清除按鈕（Clear Button）或右側按鈕（Right View）。</li></ol><h4>使用方式（Usage）</h4><p><strong>使用 Storyboard / Xib</strong></p><pre>@IBOutlet weak var textField: BorderTextFieldWithErrorMsg!</pre><p><strong>使用 Auto Layout 動態建立元件</strong></p><p>建立元件</p><pre>lazy private var textField: BorderTextFieldWithErrorMsg = {<br>      let textField = BorderTextFieldWithErrorMsg()<br>      textField.setTitleInfo(titleText: &quot;標題名稱&quot;)<br>      textField.placeholder = &quot;預設文字&quot;<br>      self.view.addSubview(textField)<br>      return textField<br>  }()</pre><p>設定元件位置</p><pre>NSLayoutConstraint.activate([<br>    textField.topAnchor.constraint(equalTo: view.topAnchor, constant: 120),<br>    textField.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 24),<br>    textField.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -24)<br>  ])</pre><h4>標題（Title）</h4><p><strong>顯示標題</strong></p><pre>textField.setTitleInfo(titleText: &quot;標題名稱&quot;)</pre><p><strong>隱藏標題</strong></p><p>可以給空字串或nil</p><pre>textField.setTitleInfo(titleText: &quot;&quot;)</pre><h4>預設文字（Placeholder）</h4><p>可透過程式碼設定，或在 Interface Builder 的 Attributes inspector 中設定</p><pre>textField.placeholder = &quot;預設文字&quot;</pre><h4>清除按鈕（Clear Button）</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/664/0*aiSQblCvTeJZDNgl.png" /></figure><p>輸入文字時，右側出現清除文字按鈕</p><pre>textField.clearButtonMode = .whileEditing</pre><h4>右側按鈕（RightView)</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/664/0*EJ2F5Bbb7ESiyWuN.png" /></figure><p>可加上自訂按鈕或圖示</p><pre>textField.rightView = UIView()</pre><h4>錯誤訊息（ErrorInfo)</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/664/0*mGt4W_dYnwdo-nPj.png" /></figure><p><strong>顯示錯誤訊息</strong></p><pre>textField.setErrorInfo(errorText: &quot;錯誤訊息&quot;)</pre><p><strong>隱藏錯誤訊息</strong></p><p>可以給空字串或nil</p><pre>textField.setErrorInfo(errorText: &quot;&quot;)</pre><h4>邊框顏色設定</h4><ul><li>borderColor： 尚未點擊的邊框的顏色</li><li>inputBorderColor： 輸入中的邊框顏色</li></ul><pre>textField.setBorderColor(borderColor: UIColor.purple, inputBorderColor: UIColor.purple)</pre><blockquote><strong>GitHub</strong></blockquote><p><a href="https://github.com/Huangjieru/CustomBorderTextFieldWithErrorMsg/tree/master">https://github.com/Huangjieru/CustomBorderTextFieldWithErrorMsg/tree/master</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a2724e020529" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[TextField and Button]]></title>
            <link>https://medium.com/@jieru04/textfield-and-button-72c1e095c0a6?source=rss-7f58831db4fb------2</link>
            <guid isPermaLink="false">https://medium.com/p/72c1e095c0a6</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[textfield]]></category>
            <dc:creator><![CDATA[Jru]]></dc:creator>
            <pubDate>Sat, 04 Nov 2023 08:54:35 GMT</pubDate>
            <atom:updated>2023-11-04T08:54:35.342Z</atom:updated>
            <content:encoded><![CDATA[<p>當輸入框有文字後，button才可以被點擊，並改變顏色</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/296/1*DT88DG6K7z4_lURdthqSGQ.gif" /></figure><h4>Step1.</h4><p>設置代理人</p><pre> override func viewDidLoad() {<br>        super.viewDidLoad()<br>        <br>        myTextField.delegate = self<br>    }</pre><h4>Step2.</h4><pre>extension ViewController: UITextFieldDelegate {<br>    <br>    func textFieldShouldBeginEditing(_ textField: UITextField) -&gt; Bool {<br>        self.myTextField.text = &quot;&quot;<br>        canNotUseSendButton()<br>        return true<br>    }<br>    <br>    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -&gt; Bool {<br>        <br>        if let text = myTextField.text, (text.count + string.count) - range.length != 0 {<br>           canUseSendButton()<br>        } else {<br>            canNotUseSendButton()<br>        }<br>        return true<br>    }<br>}</pre><ul><li>開始編輯前：清空textField，並設定button不能使用及顏色。</li><li>開始編輯：計算輸入框增加或刪除前的文字數(text.count)；加上新增的文字數(string.count)；減去要刪除的文字數(range.length)。若輸入框內尚有文字，則button可以點擊；反之，輸入框內沒有文字，button不可被點擊。</li></ul><pre>//button「不可」被點擊<br>private func canNotUseSendButton() {<br>      sendButton.isEnabled = false<br>      sendButton.setTitleColor(.systemGray5, for: .normal)<br>      sendButton.backgroundColor = .systemGray3<br>}<br>//button「可」被點擊   <br>private func canUseSendButton() {<br>     sendButton.isEnabled = true<br>     sendButton.setTitleColor(.white, for: .normal)<br>     sendButton.backgroundColor = .systemMint<br> }</pre><p><strong>&lt;說明&gt;</strong></p><ul><li>text.count：增加或刪除前的文字數。</li><li>string.count：新增的文字數。</li><li>range.length：刪除的文字數。</li><li>range.location：增加或刪除的文字位置(第一個數的位置為 0 )。</li><li>回傳 true：允許文字輸入。</li><li>回傳 false：不允許文字輸入。</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NrxHOh5yqdkP-MuJmZu03Q.png" /><figcaption>增加文字</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cNkWOOnrD6RpBWUi6cL3uw.png" /><figcaption>刪除文字</figcaption></figure><blockquote><strong>Reference</strong></blockquote><ul><li><a href="https://www.hangge.com/blog/cache/detail_1907.html">Swift - 限制TextField只能输入中文（附：中文字数的限制）</a></li><li><a href="https://badgameshow.com/steven/swift/https-badgameshow-com-steven-349/">Swift 限制UITextField輸入字數 📝</a></li><li><a href="https://medium.com/%E5%BD%BC%E5%BE%97%E6%BD%98%E7%9A%84-swift-ios-app-%E9%96%8B%E7%99%BC%E5%95%8F%E9%A1%8C%E8%A7%A3%E7%AD%94%E9%9B%86/%E5%88%A9%E7%94%A8textfield-shouldchangecharactersin-replacementstring-%E6%8E%A7%E5%88%B6%E6%96%87%E5%AD%97%E8%BC%B8%E5%85%A5%E7%9A%84%E5%AD%97%E6%95%B8-4804732129cd">利用textField(_:shouldChangeCharactersIn:replacementString:) 控制文字輸入的字數</a></li><li><a href="https://blog.51cto.com/u_15223551/2833825">UItextfield各个通知和回调的顺序_51CTO博客_uitextfield设置文本提示</a></li><li><a href="https://franksios.medium.com/ios-%E4%BD%BF%E7%94%A8uitextfield%E6%8F%90%E4%BE%9B%E7%9A%84delegate%E4%BE%86%E9%A9%97%E8%AD%89%E6%AC%84%E4%BD%8D-fcbc3beb4065">使用 UITextField 提供的 Delegate 來驗證欄位</a></li></ul><blockquote><strong>MyGitHub</strong></blockquote><p><a href="https://github.com/Huangjieru/TextField_Button">GitHub - Huangjieru/TextField_Button</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=72c1e095c0a6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Swift:下拉table view放大頂端圖片]]></title>
            <link>https://medium.com/@jieru04/swift-%E4%B8%8B%E6%8B%89table-view%E6%94%BE%E5%A4%A7%E9%A0%82%E7%AB%AF%E5%9C%96%E7%89%87-1d0d952468a2?source=rss-7f58831db4fb------2</link>
            <guid isPermaLink="false">https://medium.com/p/1d0d952468a2</guid>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Jru]]></dc:creator>
            <pubDate>Sun, 23 Jul 2023 09:06:49 GMT</pubDate>
            <atom:updated>2023-07-23T13:08:17.561Z</atom:updated>
            <content:encoded><![CDATA[<h3>Swift: 下拉 table view放大頂端圖片</h3><p>將圖片加到table view裡，下拉table view時，頂端的圖片會放大，放開table view後，圖片又回到原來的大小。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/296/1*fjrJZ-a5tcmUmqM41fsjdw.gif" /></figure><p>Step 1: 在storyboard加入table view。</p><p>Step 2: 使用table view的屬性contentInset，把圖片加入table view頂端。</p><p>Step 3: 加入Xib製作的cell、設定table view 的 function（使用MVVM）。</p><p>Step 4: 用 scrollViewDidScroll 方法監聽滑動的距離，並用transform縮放圖片。</p><p>注：解說 table view function 的 MVVM放在最後。</p><h3>Step 1 :</h3><p>在storyboard裡加入table view，設定auto layout貼齊螢幕上下左右邊。</p><p>並連接table view的@IBOutlet，讓ViewController作為table view的代理人。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FybURFbKXASFJosDheM6Hw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/793/1*8ZXNc0m-FBOOlz82TEqIVw.png" /></figure><pre>class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {<br><br>   @IBOutlet weak var tableView: UITableView!<br><br>   override func viewDidLoad() {<br>        super.viewDidLoad()<br>        <br>        tableView.delegate = self<br>        tableView.dataSource = self<br>}</pre><h3>Step 2 :</h3><ul><li>在 Assets 加入名為 image 的圖片。</li><li>圖片高度設為 200，調整 table view 的 Content inset，把圖片加到table view頂端。</li><li>圖片 y 位置為 -200，Content inset 的 top 為 200 。</li></ul><pre>var headerImageView: UIImageView = {<br>       let image = UIImageView()<br>        image.frame = CGRect(x: 0, y: -200, width: UIScreen.main.bounds.width, height: 200)<br>        image.image = UIImage(named: &quot;image&quot;)<br>        image.contentMode = .scaleAspectFill<br>        return image<br>    }()<br><br>override func viewDidLoad() {<br>        super.viewDidLoad()<br>        <br>        tableView.addSubview(headerImageView)<br>        tableView.contentInset = UIEdgeInsets(top: 200, left: 0, bottom: 0, right: 0)<br>}</pre><p><strong>Reference</strong></p><p><a href="https://medium.com/@t0915290092/content-offset-%E5%92%8C-content-inset%E6%89%80%E4%BB%A3%E8%A1%A8%E7%9A%84%E6%84%8F%E7%BE%A9-%E5%A4%96%E5%8A%A0%E5%AF%A6%E4%BD%9C-instagram%E5%80%8B%E4%BA%BA%E7%B0%A1%E4%BB%8B%E9%A0%81%E9%9D%A2%E7%9A%84%E6%BB%91%E5%8B%95-swift-4-3be10887638f">運用 contentOffset / contentInset 手把手實作 instagram 個人簡介頁面的滑動 -swift 4</a></p><h3>Step 3 :</h3><p>另開 Xib 製作 table view cell，設定cell名稱，並加入label。</p><p>在 ViewController 的 viewDidLoad() 裡註冊 table view cell Xib。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DXduIMh-53WqDOhiBTXWig.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/809/1*354zV0osyNI47WiOM0qtmA.png" /></figure><pre>override func viewDidLoad() {<br>        super.viewDidLoad()<br><br>        tableView.register(UINib(nibName: &quot;DetailTableViewCell&quot;, bundle: nil), forCellReuseIdentifier: &quot;DetailTableViewCell&quot;)<br>}</pre><h4>設定 table view 的 function</h4><p>用MVVM方式撰寫(最後面有解釋撰寫MVVM過程)</p><pre>func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -&gt; Int {<br>      return viewModel?.detailViewModels.count ?? 0<br>    }<br>    <br>    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -&gt; UITableViewCell {<br>        let cell = tableView.dequeueReusableCell(withIdentifier: &quot;DetailTableViewCell&quot;, for: indexPath) as! DetailTableViewCell<br>        let detailVM = viewModel?.detailViewModels[indexPath.row]<br>        cell.setViewModel(viewModel: detailVM!)<br><br>        return cell<br>    }<br><br>    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -&gt; CGFloat {<br>        230<br>    }</pre><h3>Step 4:</h3><p>用 scrollViewDidScroll 方法監聽滑動的距離，並用transform縮放圖片。參數 scaleX &amp; y 分別傳入縮放的「比例」。</p><pre>func scrollViewDidScroll(_ scrollView: UIScrollView) {<br>        let y = scrollView.contentOffset.y<br>        let offsetY = -y/200 //圖片高度200<br>        <br>        if -y &gt; 200 {<br>            headerImageView.transform = CGAffineTransform(scaleX: offsetY, y: offsetY) <br>        }<br>    }</pre><p><a href="https://medium.com/%E5%BD%BC%E5%BE%97%E6%BD%98%E7%9A%84-swift-ios-app-%E9%96%8B%E7%99%BC%E5%95%8F%E9%A1%8C%E8%A7%A3%E7%AD%94%E9%9B%86/83-%E5%88%A9%E7%94%A8-cgaffinetransform-%E7%B8%AE%E6%94%BE-%E4%BD%8D%E7%A7%BB%E5%92%8C%E6%97%8B%E8%BD%89-e061df9ed672">利用 CGAffineTransform 縮放，位移，旋轉和鏡像翻轉</a></p><h4>Reference</h4><p><a href="https://ithelp.ithome.com.tw/articles/10222540">[Day 14] Swift TableView 下拉放大頂部圖片 下拉放大封面照 (上) - iT 邦幫忙::一起幫忙解決難題，拯救 IT 人的一天</a></p><h4>My GitHub</h4><p><a href="https://github.com/Huangjieru/-tableView-">GitHub - Huangjieru/-tableView-</a></p><h3>解說 table view function 的 MVVM</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/296/1*LkxwnYzxYgZLLf2x7ClMoQ.gif" /></figure><h4>方法：</h4><p>將 numbers 陣列資料轉成存入型別為DetailViewModel 的 detailViewModels 陣列裡。</p><pre>let numbers = [0,1,2,3]<br>var detailViewModels = [DetailViewModel]()<br><br>numbers.forEach ({<br>    number in<br>    let viewModel = DetailViewModel()<br>    viewModel.setViewModel(number: number)<br>    detailViewModels.append(viewModel)<br>})<br><br>class DetailViewModel {<br>    var number: Int?<br>    func setViewModel(number: Int) {<br>        self.number = number<br>    }<br>}</pre><h4>應用：</h4><p>cell 要呈現的資料在 numbers 陣列裡。而 numbers 的資料也是每個 cell 要依序呈現的資料。</p><pre>let numbers = [0,1,2,3]</pre><p>在viewDidLoad()讀取解剝的資料。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fdAwaushxmbbQzyIMSftrw.png" /></figure><h4>Controller 的 ViewModel</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oTlJtpehinGMeqFb02pHCQ.png" /></figure><ol><li>建立一個型別為 DetailViewModel 的 Array （var detailViewModels = [DetailViewModel]()）。陣列裡存入 每個 cell 的 ViewModel（DetailViewModel）。</li><li>解剝 (forEach) 資料 numbers。</li></ol><ul><li>解剝時，建立 cell 的 DetailViewModel 實體（detailVM）。</li><li>解剝的資料 (number) 存入 DetailViewModel 類別裡。</li><li>並將每個 cell 的 detailVM 實體存入 detailViewModels 陣列裡。</li></ul><pre>class ViewModel {<br><br>    let numbers = [0,1,2,3]<br>   <br>    var detailViewModels = [DetailViewModel]()<br>    <br>    func load() {<br>        numbers.forEach({ number in<br>            let detailVM = DetailViewModel()<br>            detailVM.setViewModel(number: number)<br>            self.detailViewModels.append(detailVM)<br>        })<br>    }<br>}</pre><h4>Controller</h4><ol><li>當 ViewController 取得 viewModel 時，可以取得 detailViewModels 陣列。</li><li>detailViewModels 陣列的數量也就是 table view section 裡 row 的數量。</li><li>透過indexPath.row取得每個 cell 的 DetailViewModel（detailVM）。</li></ol><pre>class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {<br>    <br>    var viewModel: ViewModel?<br><br>    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -&gt; Int {<br>      return viewModel?.detailViewModels.count ?? 0<br>    }<br>    <br>    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -&gt; UITableViewCell {<br>        let cell = tableView.dequeueReusableCell(withIdentifier: &quot;DetailTableViewCell&quot;, for: indexPath) as! DetailTableViewCell<br>        let detailVM = viewModel?.detailViewModels[indexPath.row]<br>        cell.setViewModel(viewModel: detailVM!)<br>        return cell<br>    }<br>    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -&gt; CGFloat {<br>        230<br>    }<br>}</pre><h4>Cell 的 DetailTableViewCell</h4><p>將剛剛取得的 detailVM 存入 DetailTableViewCell 裡的方法裡，並建立viewModel實體。</p><p>在 DetailTableViewCell 裡有個 setViewModel(viewModel: DetailViewModel)的方法，讓參數(viewModel)設值到屬性(viewModel)，建立viewModel實體。</p><pre>class DetailTableViewCell: UITableViewCell {<br>    <br>    var viewModel: DetailViewModel?<br>    <br>    @IBOutlet weak var numberLabel: UILabel!<br>    <br>    func setViewModel(viewModel: DetailViewModel) {<br>        self.viewModel = viewModel<br>        guard let number = viewModel.number else { return }<br>        self.numberLabel.text = String(number)<br>    } <br>}</pre><h4>Cell 的 ViewModel</h4><p>藉由 cell 的 viewModel（DetailViewModel）將解剝好的資料顯示在table view cell 上。</p><pre>class DetailViewModel {<br><br>    var number: Int?<br>    func setViewModel(number: Int) {<br>        self.number = number<br>    }<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1d0d952468a2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Swift: Images carousel using a collection view with theUnsplash API]]></title>
            <link>https://medium.com/@jieru04/swift-images-carousel-using-a-collection-view-with-theunsplash-api-3f095a0c14b1?source=rss-7f58831db4fb------2</link>
            <guid isPermaLink="false">https://medium.com/p/3f095a0c14b1</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <dc:creator><![CDATA[Jru]]></dc:creator>
            <pubDate>Sun, 28 May 2023 14:05:39 GMT</pubDate>
            <atom:updated>2023-05-29T01:41:56.286Z</atom:updated>
            <content:encoded><![CDATA[<p>使用Unsplash的API串接圖片，並用collection view製作出輪播圖片的效果</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/296/1*KCEyp0y7NjM4cHTiMdtEGw.gif" /></figure><p>接續前面兩篇用假資料作出<a href="https://medium.com/@jieru04/swift-creating-banners-using-a-collection-view-844cc99aab9b">手動輪播</a>和<a href="https://medium.com/@jieru04/swift-banners-with-collection-view-and-timer-function-eb0354712831">自動輪播</a>效果，這次改用Unsplash提供的API串接圖片顯示在 contection view cell上。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fTPIJRmlPhTbfY9uc341Yw.png" /><figcaption><a href="https://unsplash.com/">https://unsplash.com/</a></figcaption></figure><h3>Service</h3><p>這次將向Unsplash發出request請求的程式碼放在同一個service資料夾</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/354/1*wrb2YwXLEFYwPzXR0k-63w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WTrqn4STF1ZCkTuezVeesA.png" /><figcaption><a href="https://unsplash.com/documentation">https://unsplash.com/documentation</a></figcaption></figure><p><strong>APIRequest</strong></p><pre><br>import Foundation<br>import UIKit<br><br>//定義 protocol APIRequest。<br>protocol APIRequest<br>{<br>    associatedtype Response<br>    <br>    var path:String {get}<br>    var queryItems:[URLQueryItem]? {get}<br>    var request:URLRequest {get}<br>    var method:HTTPMethod {get}   <br>}<br><br>extension APIRequest<br>{<br>    var host:String {&quot;api.unsplash.com&quot;}<br>    var queryItems: [URLQueryItem]? {nil}<br>}<br><br>extension APIRequest<br>{<br>    var request:URLRequest{<br>        var components = URLComponents()<br>        components.scheme = &quot;https&quot;<br>        components.host = host<br>        components.path = &quot;/photos&quot; + path<br>        components.queryItems = queryItems<br>        <br>        var requestUrl = URLRequest(url: components.url!)<br>        requestUrl.httpMethod = method.rawValue<br><br>        return requestUrl<br>    }<br>}<br><br>//定義發送 request 的 function sendRequest<br>extension APIRequest where Response:Decodable<br>{<br>    func sendRequest(completion: @escaping (Result&lt;[Response], Error&gt;) -&gt; Void)<br>    {<br>        URLSession.shared.dataTask(with: request) {<br>            data, response, error<br>            in<br>            do{<br>                if let data = data<br>                {<br>                    let decoder = JSONDecoder()<br>                    guard let httpResponse = response as? HTTPURLResponse, 200 ~= httpResponse.statusCode<br>                    else<br>                    {<br>                        if let apiErrorResponse = try? decoder.decode(ErrorResponse.self, from: data)<br>                        {<br>                            completion(.failure(apiErrorResponse))<br>                        }<br>                        return<br>                    }<br>                    let decoded = try decoder.decode([Response].self, from: data)<br>                    completion(.success(decoded))<br>                }<br>                else if let error = error<br>                {<br>                    completion(.failure(error))<br>                }<br>            }<br>            catch<br>            {<br>                completion(.failure(error))<br>            }<br>        }.resume()<br>        <br>    }<br>    <br>}</pre><p><strong>APIService</strong></p><pre>import UIKit<br><br>struct PhotoRequest:APIRequest{<br>    typealias Response = PhotoInfo<br><br>    var path: String {&quot;/random/&quot;}<br>    var method: HTTPMethod {.get}<br>    var queryItems: [URLQueryItem]?{<br>        [<br>            URLQueryItem(name: &quot;count&quot;, value: &quot;5&quot;),<br>            URLQueryItem(name: &quot;client_id&quot;, value: &quot;Your Access Key&quot;)<br>        ]<br>    }<br>}</pre><p><strong>HTTPMethod</strong></p><pre>import Foundation<br>enum HTTPMethod:String{<br>    case get<br>    case post<br>    case put<br>    case delete<br>}</pre><h4>Reference</h4><ul><li><a href="https://medium.com/%E5%BD%BC%E5%BE%97%E6%BD%98%E7%9A%84-swift-ios-app-%E9%96%8B%E7%99%BC%E5%95%8F%E9%A1%8C%E8%A7%A3%E7%AD%94%E9%9B%86/%E6%A8%A1%E4%BB%BF-apple-%E5%AE%98%E6%96%B9%E7%AF%84%E4%BE%8B%E4%B8%B2%E6%8E%A5-rest-api-%E7%9A%84-5-%E7%A8%AE%E5%AF%AB%E6%B3%95-a4d5c04397e7">模仿 Apple 官方範例串接 REST API 的 5 種寫法</a></li><li><a href="https://github.com/AppPeterPan/DemoApiUIKit/tree/main/DemoApiUIKit/service/method%204%20%26%205">DemoApiUIKit/DemoApiUIKit/service/method 4 &amp; 5 at main · AppPeterPan/DemoApiUIKit</a></li></ul><p>Apple 的 Develop in Swift Data Collections 的 Teacher Guided (Xcode 13) Project: <strong>Habits</strong>。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/730/1*7Zc67Yz82pYmxtgomaD0IQ.png" /><figcaption><a href="https://books.apple.com/tw/book/develop-in-swift-data-collections-teacher-guide/id1581183335">https://books.apple.com/tw/book/develop-in-swift-data-collections-teacher-guide/id1581183335</a></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/551/1*ijv41VNtXH4jjmwGJRgj3Q.png" /><figcaption>You can download materials from teacher guide to see the <strong>Habits</strong> project.</figcaption></figure><h3>Model</h3><p><strong>Photo</strong></p><p>串接API結構。我只串接出圖片路徑。</p><pre>import Foundation<br><br>struct PhotoInfo:Codable{<br>    let urls:Urls<br>}<br><br>struct Urls:Codable{<br>    let regular:URL<br>}</pre><p><strong>Error</strong></p><p>遇到錯誤時。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m5jFRydVQPw-1_z0U11qTQ.png" /></figure><pre>import Foundation<br>struct ErrorResponse:Decodable,Error{<br>    let errors:[String]<br>}</pre><h3>View</h3><p>cell可能會有重複(duplicate)使用的情況，用override func prepareForReuse() 將圖片設為 nil。</p><pre>import UIKit<br><br>class BannerCollectionViewCell: UICollectionViewCell {<br>    <br>    @IBOutlet weak var bannerImageView: UIImageView!<br>    //重複使用cell前先清空cell裡的資料<br>    override func prepareForReuse() {<br>        bannerImageView.image = nil<br>    }<br>    //cell樣式：陰影、圓角<br>    func cellConfigurate(cell:BannerCollectionViewCell){<br>        <br>        cell.layer.shadowColor = UIColor.black.cgColor<br>        cell.layer.shadowRadius = 20<br>        cell.layer.shadowOpacity = 0.8<br>        cell.layer.cornerRadius = 20<br>        cell.bannerImageView.contentMode = .scaleAspectFill<br>        cell.bannerImageView.clipsToBounds = true<br>        cell.bannerImageView.layer.cornerRadius = 20<br>        <br>    }<br>}</pre><h3>Extension</h3><p>設置 cell的 identifier。</p><pre>import Foundation<br>extension BannerCollectionViewCell{<br>    static var reuseIdentifier:String {&quot;\(Self.self)&quot;}<br>}</pre><h3>View Controller</h3><pre>import UIKit<br><br>class ViewController: UIViewController,UICollectionViewDelegate,UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {<br>    <br>    @IBOutlet weak var bannerCollectionView: UICollectionView!<br>    <br>    @IBOutlet weak var pageControl: UIPageControl!<br>    <br>    var time:Timer?<br>    //紀錄目前banner播放到第幾個cell<br>    var imageIndex = 0<br>    var photos = [PhotoInfo]()<br>    <br>    override func viewDidLoad() {<br>        super.viewDidLoad()<br>        <br>        bannerCollectionView.delegate = self<br>        bannerCollectionView.dataSource = self<br>        <br>        configureCellSize()<br>        bannerCollectionView.backgroundColor = .systemGray6<br><br>        //抓資料，存入photos陣列裡<br>        PhotoRequest().sendRequest { result in<br><br>            switch result{<br>            case .success(let photos):<br>                    <br>                DispatchQueue.main.async {<br>                    self.photos = photos<br>                    self.photos.append(photos[0])<br><br>                    self.pageControl.numberOfPages = self.photos.count - 1<br>                    self.pageControl.backgroundStyle = .prominent<br>                    self.bannerCollectionView.reloadData()<br>                }<br><br>            case .failure:<br>                break<br>            }<br>        }<br> <br>        //每兩秒輪播下一個圖片<br>        time = Timer.scheduledTimer(timeInterval: 2, target: self, selector: #selector(changeBanner), userInfo: nil, repeats: true)<br>    }<br>    //collection view cell滑動方向<br>    func configureCellSize(){<br>        if let layout = bannerCollectionView.collectionViewLayout as? UICollectionViewFlowLayout{<br>            layout.scrollDirection = .horizontal<br>        }<br>    }<br>    <br>    @objc func changeBanner(){<br>        <br>        var indexPath:IndexPath<br>        <br>        //imageIndex加一轉動圖片到下一張<br>        imageIndex += 1<br><br>        //在banner陣列裡再加入第一筆圖片名稱，當不是最後一筆資料時<br>        if imageIndex &lt; photos.count{<br><br>            indexPath = IndexPath(item: imageIndex, section: 0)<br>            bannerCollectionView.selectItem(at: indexPath, animated: true, scrollPosition: .centeredHorizontally)<br><br>            pageControl.currentPage = imageIndex<br>            //當imageIndex是banner陣列裡的最後一筆資料時，將page control設為0，也就是第一張圖<br>            if imageIndex == photos.count - 1{<br>                pageControl.currentPage = 0<br>            }<br><br>        }else<br>        {<br>            //當banner數量等於banner陣列的最後一筆資料，回到第一筆資料<br>            imageIndex = 0<br>            pageControl.currentPage = 0<br>            indexPath = IndexPath(item: imageIndex, section: 0)<br>            //不要動畫，先回到第一張圖<br>            bannerCollectionView.selectItem(at: indexPath, animated: false, scrollPosition: .centeredHorizontally)<br><br>            //再重新輪播<br>            changeBanner()<br>        }<br>        <br>    }<br>    <br>    <br>    //MARK: - Collection view<br>    func numberOfSections(in collectionView: UICollectionView) -&gt; Int {<br>        1<br>    }<br>    <br>    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -&gt; Int {<br>            return photos.count<br>    }<br>    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -&gt; UICollectionViewCell {<br>        let bannerCollectionViewcell = collectionView.dequeueReusableCell(withReuseIdentifier: BannerCollectionViewCell.reuseIdentifier, for: indexPath) as! BannerCollectionViewCell<br>        let indexPath = photos[indexPath.item]<br>        //cell樣式：陰影、圓角<br>        bannerCollectionViewcell.cellConfigurate(cell: bannerCollectionViewcell)<br>        //抓取圖片<br>        fetchImage(from: indexPath.urls.regular) { image in<br>                DispatchQueue.main.async {<br>                    bannerCollectionViewcell.bannerImageView.image = image<br>                }<br>            }<br><br>            return bannerCollectionViewcell<br>    }<br><br>    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -&gt; CGSize {<br>        return bannerCollectionView.bounds.size<br>    }<br>    <br>    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -&gt; CGFloat {<br>        return 0<br>    }<br> <br>    //抓取圖片<br>    func fetchImage(from url: URL, completion: @escaping (UIImage?)-&gt;Void){<br>            URLSession.shared.dataTask(with: url) { data, response, error in<br>                if let _ = error{<br>                    completion(nil)<br>                }else if let data = data, let image = UIImage(data: data){<br>                    completion(image)<br>                }else{<br>                    completion(nil)<br>                }<br>            }.resume()<br>        }<br>}</pre><h4>My GitHub</h4><p><a href="https://github.com/Huangjieru/banner/tree/Integrate_API">GitHub - Huangjieru/banner at Integrate_API</a></p><blockquote>Übung macht den Meister</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3f095a0c14b1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Swift: Images carousel with a Collection View and Timer Function]]></title>
            <link>https://medium.com/@jieru04/swift-banners-with-collection-view-and-timer-function-eb0354712831?source=rss-7f58831db4fb------2</link>
            <guid isPermaLink="false">https://medium.com/p/eb0354712831</guid>
            <category><![CDATA[banners]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios-development]]></category>
            <category><![CDATA[timer]]></category>
            <dc:creator><![CDATA[Jru]]></dc:creator>
            <pubDate>Thu, 25 May 2023 08:47:05 GMT</pubDate>
            <atom:updated>2023-05-28T14:59:56.580Z</atom:updated>
            <content:encoded><![CDATA[<p>[Auto-Scrolling]自動輪播</p><p>Go to see → <a href="https://medium.com/@jieru04/swift-creating-banners-using-a-collection-view-844cc99aab9b">Manual-scrolling手動滑動輪播效果</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/296/1*bC40nPH2JwcVh8sQh8djsg.gif" /></figure><h4>介紹</h4><p>使用元件：collection view, image view, page control</p><p>使用函數: scheduledTimer(timeInterval:target:selector:, userInfo: repeats:), selectItem(at:animated:scrollPosition:)</p><h4>輪播效果製作</h4><p><strong>一、向右輪播到最後一張圖片時，會往左拉，回到第一張。</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l96S96g1iUfX_yIrIlTW6Q.gif" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/294/1*X28aezZbFWkJy-FarXra7g.png" /><figcaption>最後一筆山景圖硬拉回第一筆樹林圖</figcaption></figure><pre><br>import UIKit<br><br>class ViewController: UIViewController,UICollectionViewDelegate,UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {<br>    <br>    @IBOutlet weak var bannerCollectionView: UICollectionView!<br>    <br>    @IBOutlet weak var pageControl: UIPageControl!<br>    <br>    var time:Timer?<br>    //紀錄目前banner播放到第幾個cell<br>    var imageIndex = 0<br>    var banners = [&quot;1&quot;,&quot;2&quot;,&quot;3&quot;]<br>    <br>    override func viewDidLoad() {<br>        super.viewDidLoad()<br>        bannerCollectionView.delegate = self<br>        bannerCollectionView.dataSource = self<br>        <br>        configureCellSize()<br>        <br>        //每兩秒輪播下一個圖片<br>        time = Timer.scheduledTimer(timeInterval: 2, target: self, selector: #selector(changeBanner), userInfo: nil, repeats: true)<br>        <br>    }<br>    <br>    func configureCellSize(){<br>        if let layout = bannerCollectionView.collectionViewLayout as? UICollectionViewFlowLayout{<br>            layout.scrollDirection = .horizontal<br>            <br>        }<br>    }<br>    <br>    @objc func changeBanner(){<br>        <br>        //imageIndex加一轉動圖片到下一張<br>        imageIndex += 1<br>        if imageIndex == banners.count{<br>            imageIndex = 0<br>        }<br>        //用imageIndex去產生一個indexPath<br>        let indexPath = IndexPath(item: imageIndex, section: 0)<br>        //讓collectionView去選indexPath<br>        bannerCollectionView.selectItem(at: indexPath, animated: true, scrollPosition: .centeredHorizontally)<br>        <br>    }<br>    <br>    <br>    //MARK: - Collection view<br>    func numberOfSections(in collectionView: UICollectionView) -&gt; Int {<br>        1<br>    }<br>    <br>    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -&gt; Int {<br>        banners.count<br>    }<br>    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -&gt; UICollectionViewCell {<br>        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: &quot;BannerCollectionViewCell&quot;, for: indexPath) as! BannerCollectionViewCell<br>        let indexPath = banners[indexPath.item]<br>        cell.bannerImageView.contentMode = .scaleAspectFill<br>        cell.bannerImageView.image = UIImage(named: &quot;\(indexPath)&quot;)<br>        return cell<br>        <br>    }<br>    <br>    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -&gt; CGSize {<br>        return bannerCollectionView.bounds.size<br>    }<br>    <br>    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -&gt; CGFloat {<br>        return 0<br>    }<br>}<br><br></pre><p><strong>二、向右輪播到最後一張圖時，繼續向右播第一張圖</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/435/1*oXX-0F0jU5IawmV3F2CMrg.png" /></figure><ol><li>先在儲存圖片的banners陣列裡多加最後一筆資料，新增的資料就是陣列裡的第一筆資料。</li></ol><pre>var banners = [&quot;1&quot;,&quot;2&quot;,&quot;3&quot;,&quot;1&quot;]</pre><p>2. 用imageIndex記錄圖片為第幾張，並帶入selectItem 函式，將圖片顯示在cell所屬的位置上。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/706/1*SS9Q4nHDGBdgMkbeAU8uEQ.png" /><figcaption><a href="https://developer.apple.com/documentation/uikit/uicollectionview/1618057-selectitem">https://developer.apple.com/documentation/uikit/uicollectionview/1618057-selectitem</a></figcaption></figure><p>當跑到最後一張圖時，也就是剛剛自行新增的最後一筆資料，設定imageIndex為 <strong>0</strong>，selectItem動畫效果設為 <strong>false</strong>，並重新呼叫自己changeBanner()。</p><pre>import UIKit<br><br>class ViewController: UIViewController,UICollectionViewDelegate,UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {<br>    <br>    @IBOutlet weak var bannerCollectionView: UICollectionView!<br>    <br>    @IBOutlet weak var pageControl: UIPageControl!<br>    <br>    var time:Timer?<br>    //紀錄目前banner播放到第幾個cell<br>    var imageIndex = 0<br>    var banners = [&quot;1&quot;,&quot;2&quot;,&quot;3&quot;,&quot;1&quot;]<br>    <br>    override func viewDidLoad() {<br>        super.viewDidLoad()<br>        bannerCollectionView.delegate = self<br>        bannerCollectionView.dataSource = self<br>        <br>        configureCellSize()<br>        <br>        pageControl.numberOfPages = banners.count - 1<br>        pageControl.backgroundStyle = .prominent<br>        <br>        //每兩秒輪播下一個圖片<br>        time = Timer.scheduledTimer(timeInterval: 2, target: self, selector: #selector(changeBanner), userInfo: nil, repeats: true)<br>        <br>    }<br>    <br>    func configureCellSize(){<br>        if let layout = bannerCollectionView.collectionViewLayout as? UICollectionViewFlowLayout{<br>            layout.scrollDirection = .horizontal<br>            <br>        }<br>    }<br>    <br>    @objc func changeBanner(){<br>        <br>        var indexPath:IndexPath<br>        <br>        //imageIndex加一轉動圖片到下一張<br>        imageIndex += 1<br><br>        //在banner陣列裡再加入第一筆圖片名稱，當不是最後一筆資料時<br>        if imageIndex &lt; banners.count{<br><br>            //用imageIndex去產生一個indexPath<br>            indexPath = IndexPath(item: imageIndex, section: 0)<br>            //讓collectionView去選indexPath<br>            bannerCollectionView.selectItem(at: indexPath, animated: true, scrollPosition: .centeredHorizontally)<br>            <br>            pageControl.currentPage = imageIndex<br>            //當imageIndex是banner陣列裡的最後一筆資料時，將page control設為0，是第一張圖也是第一個page control圈圈<br>            if imageIndex == banners.count - 1{<br>                pageControl.currentPage = 0<br>            }<br>            <br>        }<br>        else<br>        {<br>            //當banner數量等於banner陣列的最後一筆資料，回到第一筆資料，page control也回到第一個圈<br>            imageIndex = 0<br>            pageControl.currentPage = 0<br>            indexPath = IndexPath(item: imageIndex, section: 0)<br>            //不要動畫先回到第一張圖<br>            bannerCollectionView.selectItem(at: indexPath, animated: false, scrollPosition: .centeredHorizontally)<br>            <br>            //再重新輪播<br>            changeBanner()<br>        }<br>        <br>    }<br>    <br>    <br>    //MARK: - Collection view<br>    func numberOfSections(in collectionView: UICollectionView) -&gt; Int {<br>        1<br>    }<br>    <br>    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -&gt; Int {<br>        banners.count<br>    }<br>    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -&gt; UICollectionViewCell {<br>        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: &quot;BannerCollectionViewCell&quot;, for: indexPath) as! BannerCollectionViewCell<br>        let indexPath = banners[indexPath.item]<br>        cell.bannerImageView.contentMode = .scaleAspectFill<br>        cell.bannerImageView.image = UIImage(named: &quot;\(indexPath)&quot;)<br>        return cell<br>        <br>    }<br>    <br>    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -&gt; CGSize {<br>        return bannerCollectionView.bounds.size<br>    }<br>    <br>    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -&gt; CGFloat {<br>        return 0<br>    }<br><br>}<br><br></pre><h4>Reference</h4><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F6McxEYvHglg%3Fstart%3D280%26feature%3Doembed%26start%3D280&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D6McxEYvHglg&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F6McxEYvHglg%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/8e85ea8171de284da52764f343595515/href">https://medium.com/media/8e85ea8171de284da52764f343595515/href</a></iframe><h4>My GitHub</h4><p><a href="https://github.com/Huangjieru/banner">GitHub - Huangjieru/banner</a></p><blockquote>Übung macht den Meister</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eb0354712831" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Swift: Images carousel using a collection view]]></title>
            <link>https://medium.com/@jieru04/swift-creating-banners-using-a-collection-view-844cc99aab9b?source=rss-7f58831db4fb------2</link>
            <guid isPermaLink="false">https://medium.com/p/844cc99aab9b</guid>
            <category><![CDATA[page-control]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[banners]]></category>
            <category><![CDATA[collectionview]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <dc:creator><![CDATA[Jru]]></dc:creator>
            <pubDate>Wed, 24 May 2023 03:04:12 GMT</pubDate>
            <atom:updated>2023-05-28T15:01:01.927Z</atom:updated>
            <content:encoded><![CDATA[<p>[Manual-scrolling]手動版輪播效果</p><p>Go to see → <a href="https://medium.com/@jieru04/swift-banners-with-collection-view-and-timer-function-eb0354712831">Auto-Scrolling 自動輪播</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/296/1*0-tLc4mKwCKpq7cJR3lO5w.gif" /></figure><h4>介紹</h4><p>使用元件：collection view, image view, page control</p><p>排版設計：AutoLayout</p><h4>製作過程</h4><ol><li>將Collection View、Image View、page control元件加到 viewController的 storyboard 裡。</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/663/1*s4c6S6LeseZ60szCd0zwxA.png" /></figure><p>2. 用AutoLayout排版要記得將 collection view 的 Estimate Size 改為 None!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/516/1*aUcEGHn1q2yYxAiXJTinAg.png" /></figure><p>page control不要放在collection view裡面，才不會跟著banner一起滑動。AutoLayout排版時先設定水平和垂值對齊，在去條整垂直(Y)的高度。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/958/1*L_CGEWLScNuOoFYOjNeuOQ.png" /></figure><p>3. 加入CollectionView Cell檔案，並設置 cell 的 identifier名稱。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/956/1*WTXyzbksC_PlFr1YLG6XHg.png" /></figure><p>拉imageView的IBOutlet到collectionViewCell裡。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/731/1*e5nnRB9ze673u2yPEXSMQQ.png" /></figure><p>4. 在Accets裡加入圖片。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/787/1*TiRHODfk59f2avXrkSRu0Q.png" /></figure><p>5. ViewController裡撰寫程式碼</p><pre><br>import UIKit<br><br>class ViewController: UIViewController,UICollectionViewDelegate,UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {<br>    <br>    @IBOutlet weak var bannerCollectionView: UICollectionView!<br>    <br>    @IBOutlet weak var pageControl: UIPageControl!<br>    <br>    var banners = [&quot;1&quot;,&quot;2&quot;,&quot;3&quot;]<br>    <br>    override func viewDidLoad() {<br>        super.viewDidLoad()<br>        bannerCollectionView.delegate = self<br>        bannerCollectionView.dataSource = self<br>        <br>        configureCellSize()<br>        <br>    }<br>    <br>    func configureCellSize(){<br>        if let layout = bannerCollectionView.collectionViewLayout as? UICollectionViewFlowLayout{<br>            layout.scrollDirection = .horizontal         <br>        }<br>    }<br>    <br>    func numberOfSections(in collectionView: UICollectionView) -&gt; Int {<br>        1<br>    }<br>    <br>    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -&gt; Int {<br>        banners.count<br>    }<br>    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -&gt; UICollectionViewCell {<br>        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: &quot;BannerCollectionViewCell&quot;, for: indexPath) as! BannerCollectionViewCell<br>        let indexPath = banners[indexPath.item]<br>        cell.bannerImageView.contentMode = .scaleAspectFill<br>        cell.bannerImageView.image = UIImage(named: &quot;\(indexPath)&quot;)<br>        return cell<br>        <br>    }<br>    <br>    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -&gt; CGSize {<br>        <br>        return bannerCollectionView.bounds.size<br>    }<br>    <br>    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -&gt; CGFloat {<br>        return 0<br>    }<br>    <br>    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {<br>        let currentPage = ceil(scrollView.contentOffset.x /  scrollView.bounds.size.width)<br>        pageControl.currentPage = Int(currentPage)<br>        pageControl.backgroundStyle = .prominent<br>        pageControl.numberOfPages = banners.count <br>    }<br>}</pre><h4>Reference</h4><p><strong>Banner tutorial</strong></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FrXkemZojlW8&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DrXkemZojlW8&amp;image=http%3A%2F%2Fi.ytimg.com%2Fvi%2FrXkemZojlW8%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/9876db99e6516a7cc72bb4efa2916bce/href">https://medium.com/media/9876db99e6516a7cc72bb4efa2916bce/href</a></iframe><p><strong>Page control style</strong></p><ul><li><a href="https://medium.com/%E5%BD%BC%E5%BE%97%E6%BD%98%E7%9A%84-swift-ios-app-%E9%96%8B%E7%99%BC%E5%95%8F%E9%A1%8C%E8%A7%A3%E7%AD%94%E9%9B%86/ios-14-%E9%80%B2%E5%8C%96%E7%9A%84-page-control-f097af2801a6">iOS 14 進化的 page control</a></li><li><a href="https://medium.com/%E5%BD%BC%E5%BE%97%E6%BD%98%E7%9A%84-swift-ios-app-%E9%96%8B%E7%99%BC%E6%95%99%E5%AE%A4/%E4%BD%9C%E6%A5%AD-50-collectionview-scrollview-pagecontrol-%E5%88%87%E6%8F%9B%E8%88%87%E7%B8%AE%E6%94%BE%E7%85%A7%E7%89%87-6b6d128e1c6c">作業#50 CollectionView+ScrollView+PageControl-切換與縮放照片</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=844cc99aab9b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Chat with AI — part 3]]></title>
            <link>https://medium.com/@jieru04/chat-with-ai-part-3-5368629e1560?source=rss-7f58831db4fb------2</link>
            <guid isPermaLink="false">https://medium.com/p/5368629e1560</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[app-development]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Jru]]></dc:creator>
            <pubDate>Fri, 21 Apr 2023 03:52:22 GMT</pubDate>
            <atom:updated>2023-04-21T03:52:22.365Z</atom:updated>
            <content:encoded><![CDATA[<h3>Chat with AI — part 3</h3><p>Store the data in Firebase</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/360/1*opO4M3Ghw_JAd8PtsntHNg.gif" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ncA1TT9Lt6dWy73rkevFFw.png" /></figure><h3>Part3 — Features:</h3><ul><li><strong>Add CocoaPods → install Firebase SDK</strong></li><li><strong>Create a project in Firebase</strong></li><li><strong>Store the register account in the Firebase Authentication</strong></li><li><strong>Log out the account</strong></li><li><strong>Store &amp; load messages in Firebase Realtime Database</strong></li><li><strong>Store &amp; load a profile picture in Firebase Storage</strong></li></ul><p>Go to see:</p><p>→ <a href="https://medium.com/%E5%BD%BC%E5%BE%97%E6%BD%98%E7%9A%84-swift-ios-app-%E9%96%8B%E7%99%BC%E6%95%99%E5%AE%A4/swift-app-chat-with-ai-dafd50abd0a5">Part1</a>: Access ChatGPT’s API.</p><p>→ <a href="https://medium.com/@jieru04/chat-with-ai-part-2-dfd15e60ea54">Part2</a>: Create views for login and registration.</p><blockquote><strong>Add CocoaPods — Firebase</strong></blockquote><p>I added the key words pod‘Firebase/Core’, pod‘Firebase/Auth’, pod‘Firebase/Database’ , pod ‘Firebase/Storage’ in the Podfile. Then I run the command pod install using the terminal. Finally, I opened the project with the path of extension .xcworkspace to keep doing my project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/649/1*IBTZQD9xea-YHZt1GjkuvA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/246/1*TxjBGVgsoH6KYpIFfpIpBQ.png" /></figure><blockquote><strong>Create a project in Firebase</strong></blockquote><p><a href="https://medium.com/%E5%BD%BC%E5%BE%97%E6%BD%98%E7%9A%84-swift-ios-app-%E9%96%8B%E7%99%BC%E5%95%8F%E9%A1%8C%E8%A7%A3%E7%AD%94%E9%9B%86/%E5%BB%BA%E7%AB%8B-firebase-%E5%B0%88%E6%A1%88-fbd6d19808c3">建立 Firebase 專案</a></p><blockquote><strong>Store the register account in the Firebase Authentication</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t3WiVpVL1-SjwjYdoG3Bkw.png" /></figure><p>The new user creates an account, and the account information is stored in the Firebase database. The steps on how to create an account can be found in the following article below.</p><p><a href="https://medium.com/%E5%BD%BC%E5%BE%97%E6%BD%98%E7%9A%84-swift-ios-app-%E9%96%8B%E7%99%BC%E5%95%8F%E9%A1%8C%E8%A7%A3%E7%AD%94%E9%9B%86/%E5%88%A9%E7%94%A8-firebase-%E5%AF%A6%E7%8F%BE-ios-app-%E7%9A%84%E7%99%BB%E5%85%A5%E5%8A%9F%E8%83%BD-cf1795ccec00">利用 Firebase 實現 iOS App 的登入註冊功能</a></p><h4>MVVM</h4><p>I created a new file called DatabaseManager.swift , which is used to connect the program between the view and model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/947/1*KPPJdLPVuJhOSQoIWLSSVQ.png" /></figure><pre>import Foundation<br>import FirebaseDatabase<br>import FirebaseStorage<br><br>struct ChatAppUser{<br>    let firstName:String<br>    let lastName:String<br>    let emailAddress:String<br><br>    //computed property<br>    var safeEmail:String{<br>        var safeEmail = emailAddress.replacingOccurrences(of: &quot;.&quot;, with: &quot;-&quot;)<br>        safeEmail = safeEmail.replacingOccurrences(of: &quot;@&quot;, with: &quot;-&quot;)<br>        return safeEmail<br>    }<br>    let profilePictureUrl:String?<br>}<br><br>struct Message{<br>    let account:String<br>    let userMessage:String<br>    let chatgptMessage:String<br>    //computed property<br>    var safeEmail:String{<br>        var safeEmail = account.replacingOccurrences(of: &quot;.&quot;, with: &quot;-&quot;)<br>        safeEmail = safeEmail.replacingOccurrences(of: &quot;@&quot;, with: &quot;-&quot;)<br>        return safeEmail<br>    }<br>}<br><br>//final class: this class cannot be subclassed called<br>final class DatabaseManager{<br>    //singleton<br>    static let shared = DatabaseManager()<br>    //從數據庫讀取或寫入數據realtime database<br>    private let databaseReference:DatabaseReference =  Database.database().reference()<br>    //上傳檔案到storage<br>    private let storageReference:StorageReference = Storage.storage().reference()<br>}<br><br>//MARK: - Account Management<br>extension DatabaseManager{<br>    //if the user email not exist<br>    public  func userExists(with email: String,<br>                            completion: @escaping ((Bool)-&gt;Void))<br>    {<br>        //not contain &#39;.&#39; &#39;#&#39; &#39;$&#39; &#39;[&#39; or &#39;]&#39;<br>        var safeEmail = email.replacingOccurrences(of: &quot;.&quot;, with: &quot;-&quot;)<br>        safeEmail = safeEmail.replacingOccurrences(of: &quot;@&quot;, with: &quot;-&quot;)<br>        <br>        databaseReference.child(&quot;User&quot;).child(safeEmail).observeSingleEvent(of: .value) { snapshot in<br>            <br>            guard snapshot.value as? String != nil else {<br>              completion(false)<br>                return<br>            }<br>            completion (true)<br>        }<br>    }<br>    <br>    ///Inserts new user to database<br>    public func insertUser(with user:ChatAppUser)<br>    {<br>        databaseReference.child(&quot;User&quot;).child(user.safeEmail).setValue(<br>            [<br>            &quot;first_name&quot;: user.firstName,<br>            &quot;last_name&quot;: user.lastName,<br>            &quot;profile&quot;:user.profilePictureUrl<br>            ]<br>        )<br>    }<br>    <br>    ///Insert conversations to database<br>    public func insertContent(with user:Message)<br>    {<br>        let message:[String:Any] =<br>        [<br>                &quot;userMessage&quot;: user.userMessage,<br>                &quot;chatgptMessage&quot;:user.chatgptMessage<br>        ]<br><br>        let date = Date()<br>        <br>        databaseReference.child(&quot;User&quot;).child(user.safeEmail).child(&quot;conversations&quot;).child(&quot;\(date)&quot;).setValue(message)<br><br>    }<br>   ///Insert picture to database <br>   public func uploadPhoto(image:UIImage?, completion:@escaping (Result&lt;URL, Error&gt;)-&gt; Void)<br>    {<br>        let fileReference = storageReference.child(UUID().uuidString + &quot;.jpg&quot;)<br>        if let imageData = image?.jpegData(compressionQuality: 0.7)<br>        {<br>            fileReference.putData(imageData, metadata: nil)<br>            { result in<br>                switch result<br>                {<br>                    case .success:<br>                    fileReference.downloadURL(completion: completion)<br>                    case .failure(let error):<br>                        completion(.failure(error))<br>                }<br>            }<br>        }<br>    }<br>    <br>    public func loadConversations(email:String, completion:@escaping (DataSnapshot)-&gt;Void){<br>        var safeEmail = email.replacingOccurrences(of: &quot;.&quot;, with: &quot;-&quot;)<br>        safeEmail = safeEmail.replacingOccurrences(of: &quot;@&quot;, with: &quot;-&quot;)<br>        databaseReference.child(&quot;User&quot;).child(safeEmail).child(&quot;conversations&quot;).observeSingleEvent(of:.value)<br>        { snapshot in<br>            guard snapshot.children.allObjects as? [DataSnapshot] != nil else{<br>                print(&quot;no data in Firebase&quot;)<br>                return<br>            }<br>           completion(snapshot)<br>        }<br>    }<br>    public func loadProfile(email:String, completion:@escaping (DataSnapshot?)-&gt; Void){<br>        var safeEmail = email.replacingOccurrences(of: &quot;.&quot;, with: &quot;-&quot;)<br>        safeEmail = safeEmail.replacingOccurrences(of: &quot;@&quot;, with: &quot;-&quot;)<br>        databaseReference.child(&quot;User&quot;).child(safeEmail).child(&quot;profile&quot;).observeSingleEvent(of: .value) { snapshot in<br>            guard snapshot.children.allObjects as? [DataSnapshot] != nil else{<br>                print(&quot;no data in Firebase&quot;)<br>                return<br>            }<br>            completion(snapshot)<br>        }<br>    }<br>}</pre><h4>Register</h4><p>I made a new account and store it in Firebase.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l40SrEgtw2zSwdE2EsE4pw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/858/1*LlZ2zFR6pZxzqJW39_He0w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/712/1*KcO_yVLeAawAajJkAOgWiQ.png" /></figure><pre>import FirebaseAuth<br><br>class RegisterViewController: UIViewController {<br><br>      override func viewDidLoad() {<br>             super.viewDidLoad()<br>            registerButton.addTarget(self, action: #selector(registerButtonTapped), for: .touchUpInside)<br>      }<br>      <br>        //按下register按鈕時確認輸入的資料是否完整<br>        @objc private func registerButtonTapped(){<br>        firstName.resignFirstResponder()<br>        lastName.resignFirstResponder()<br>        emailField.resignFirstResponder()<br>        passwordField.resignFirstResponder()<br>        <br>        guard let firstName = firstName.text, let lastName = lastName.text, let email = emailField.text, let password = passwordField.text, !firstName.isEmpty, !lastName.isEmpty, !email.isEmpty, !password.isEmpty, password.count &gt;= 6 else {<br>            alertUserLoginError()<br>            return<br>        }<br>        // Firebase log in<br>        DatabaseManager.shared.userExists(with: email,completion:<br>        { [weak self] exists in<br>            <br>            guard let strongSelf = self else {<br>                return<br>            }<br>            //user already exists<br>            guard !exists  else{<br>                //alert帳號已存在<br>                strongSelf.alertUserLoginError(message:&quot;This email address already exists.&quot;)<br>                return<br>            }<br>                FirebaseAuth.Auth.auth().createUser(withEmail: email, password: password) { authResult, error in<br>                    <br>                    guard authResult != nil, error == nil else {<br>                        print(&quot;Error creating user:\(String(describing: error?.localizedDescription))&quot;)<br>                        return<br>                    }<br><br>                    //update the user profile picture<br>                      ....略....<br>                       //The program will be showen in the &quot;Store a profile picture in Storage Firebase&quot; section<br><br>                    //insert the user&#39;s information in the database<br>                    DatabaseManager.shared.insertUser(with: ChatAppUser(firstName: firstName, lastName: lastName, emailAddress: email))<br>                    <br>                    self?.navigationController?.dismiss(animated: false)<br>                    <br>                }<br>        })<br><br>    }<br>    <br>      private func alertUserLoginError(message:String = &quot;Please enter all information to create a new account&quot;){<br>        let alert = UIAlertController(title: &quot;Oops!&quot;, message: message, preferredStyle: UIAlertController.Style.alert)<br>        alert.addAction(UIAlertAction(title: &quot;Dismiss&quot;, style: .cancel))<br>        present(alert, animated: true)<br>        <br>    }<br>}</pre><p>When the user presses the continue button , they can continue to type data into the text field.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*N7ftC2HMAC8oyP8OzJdzjQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*s15qCdV4plXkaqYLnIhNQQ.png" /></figure><pre>extension RegisterViewController:UITextFieldDelegate{<br><br>    func textFieldShouldReturn(_ textField: UITextField) -&gt; Bool {<br>        switch textField{<br>        case firstName:<br>            lastName.becomeFirstResponder()<br>        case lastName:<br>            emailField.becomeFirstResponder()<br>        case emailField:<br>            passwordField.becomeFirstResponder()<br>        case passwordField:<br>            registerButtonTapped()<br>        default:<br>            return true<br>        }<br>        return true<br>    }<br>}</pre><h4>Login</h4><p>You can test the newly registered account by signing in through Firebase. If the user has successfully signed up for an account, they can use their credentials to log in.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FNd5NqHRUZgz8eVGmdXdng.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pPqP8czIQHruPmObMH4jgQ.png" /></figure><pre>import Firebase<br><br>class LoginViewController: UIViewController {<br><br>    override func viewDidLoad() {<br>           super.viewDidLoad()<br>          loginButton.addTarget(self, action: #selector(loginButtonTapped), for: .touchUpInside)<br>    }<br>    <br>    //按下login按鈕時確認輸入的資料是否完整<br>    @objc private func loginButtonTapped()<br>    {<br>        //按下login按鈕後，不會出現鍵盤<br>        emailField.resignFirstResponder()<br>        passwordField.resignFirstResponder()<br>        //判斷輸入是否符合規定<br>        guard let email = emailField.text, let password = passwordField.text, !email.isEmpty, !password.isEmpty, password.count &gt;= 6 else {<br>            alertUserLoginError(message: &quot;Please enter all information to log in&quot;)<br>            return<br>        }<br>        //確認是否已有帳號<br>        DatabaseManager.shared.userExists(with: email)<br>        { [weak self] exists in<br>            print(&quot;exists:\(exists)&quot;)<br>            //帳號已存在<br>            guard !exists else{<br>               return<br>            }<br>            // Firebase log in<br>            Firebase.Auth.auth().signIn(withEmail: email, password: password)<br>            { [weak self] authResult, error in<br>                <br>                guard let strongSelf = self else{<br>                    return<br>                }<br>                <br>                guard let result = authResult, error == nil else{<br>                    self?.alertUserLoginError(message: &quot;Please make a new account.&quot;)<br>                    print(&quot;Failed:\(String(describing: error?.localizedDescription)) and failed to log in with email: \(email)&quot;)<br>                    return<br>                }<br>                let user = result.user<br>                print(&quot;Success, logged in User(成功登入): \(String(describing: user.email))&quot;)<br>           <br>                //Check whether the user is logged in or not.<br>                if let user = Auth.auth().currentUser<br>                {<br>                    print(&quot;logged in(已登入):\(user.uid),\(String(describing: user.email)),\(String(describing: user.photoURL))&quot;)<br>                }<br>                //Receive the login status changes接收登入狀態改變的通知<br>                FirebaseAuth.Auth.auth().addStateDidChangeListener<br>                { auth, user in<br>                    if let user = user<br>                    {<br>                        print(&quot;\(String(describing: user)) login(要登入)&quot;)<br>  <br>                        //Dismiss the view 登入成功後退掉畫面<br>                        strongSelf.navigationController?.dismiss(animated: true)<br>                    }else{<br>                        print(&quot;not login&quot;)<br>                    }<br>                }<br>                <br>            }<br>        <br>        }<br>    }<br>        <br>    func alertUserLoginError(message:String){<br>        let alert = UIAlertController(title: &quot;Oops!&quot;, message: message, preferredStyle: UIAlertController.Style.alert)<br>        alert.addAction(UIAlertAction(title: &quot;Dismiss&quot;, style: .cancel))<br>        present(alert, animated: true)<br>        <br>    }<br>}</pre><h4>Check whether the user has logged in or not</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*_wg8vGeKTm3a4K07WIQhew.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/795/1*Qrky2dzObd5oGmo2z1oX4Q.png" /></figure><p><strong>ChatViewController</strong> → Firstly, you need to import FirebaseAuth. In the main view controller, ChatViewController, I wrote the method that checks whether the user has logged in or not when the view appears. If the user has not logged in, the Login view will appear. On the other hand, if the user has already logged in, the data stored in Firebase will be downloaded and appeared in chat bubble.</p><p>Before downloading the data from Firebase, I clear the content property, which is responsible for storing the messages sent by the user and ChatGPT’s responses, to ensure it is empty.</p><pre>import FirebaseAuth<br><br>class ChatViewController: UIViewController {<br><br>      override func viewWillAppear(_ animated: Bool) {<br>        super.viewWillAppear(animated)<br><br>        validateAuth()<br>    }<br>    <br>    //判斷是否登入<br>    private func validateAuth(){<br>        self.content.removeAll()<br>        if FirebaseAuth.Auth.auth().currentUser == nil<br>        {<br>            let vc = LoginViewController()<br>            let nav = UINavigationController(rootViewController: vc)<br>            nav.modalPresentationStyle = .fullScreen<br>            present(nav, animated: false)<br>        }<br>        else<br>        {<br>            //download conversations data from firebase<br>            let currentUserEmail = Auth.auth().currentUser?.email ?? &quot;&quot;<br>            DatabaseManager.shared.loadConversations(email: currentUserEmail)<br>            { [weak self] snapshot in<br><br>                self?.content.removeAll()<br>                <br>                if let allSnapshot = snapshot.children.allObjects as? [DataSnapshot]<br>                {<br>                    for message in allSnapshot<br>                    {<br>                        let message = message.value as? [String:Any]<br>                        let userMessage = message?[&quot;userMessage&quot;]<br>                        let chatgptMessage = message?[&quot;chatgptMessage&quot;]<br><br>                        self?.content.append(Content(name: .user, text: userMessage as! String))<br>                        self?.content.append(Content(name: .chatgpt, text: chatgptMessage as! String))<br>                        DispatchQueue.main.async {<br>                            self?.tableView.reloadData()<br>                            //讓句子出現在最底層的對話中<br>                            let contentCount = (self?.content.count ?? 1 ) - 1<br>                            let indexPath = IndexPath(row: contentCount, section: 0)<br>                            self?.tableView.scrollToRow(at: indexPath, at: .bottom, animated: true)<br>                        }<br>                                                <br>                    }<br>         <br>                }<br>                <br>            }<br>            //Check the profile pircture 確認是否有大頭照的路徑<br>            ....略....<br>            //The program will be showen in the &quot;Store a profile picture in Storage Firebase&quot; section<br><br>            print(&quot;download data from firebase&quot;)<br>        }<br>    }<br>}</pre><h4>Dismiss the view</h4><p><strong>RegisterViewController</strong> → After pressing the register button and the view controller dismiss.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IUSp1Dv6JF3f3qviIQzuAg.png" /></figure><p><strong>LoginViewController</strong> → After pressing the log in button and logging in successfully, the login view controller is dismissed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qX3oLUW3_fiquevG5niqHw.png" /></figure><p><em>Tip</em>: <em>when you want to restart the simulator, you can choose Device → Erase all content and Settings on tool bar to clear all caches.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/1*BS10YqXHh7fQzyFdDViriA.png" /></figure><blockquote><strong>Log out the account</strong></blockquote><p>The logout button is located in the upper right corner of the chat view. When the user logs out, the messages — which are stored in the content property and displayed in the chat bubble — will be cleared.</p><pre>class ChatViewController: UIViewController { <br><br>     var content = [Content]()<br><br>     override func viewDidLoad() {<br>         super.viewDidLoad()<br>        navigationItem.rightBarButtonItem = UIBarButtonItem(title: &quot;Logout&quot;, style: .done, target: self, action: #selector(logout))<br>          <br>      }<br>    @objc private func logout(){<br>        do{<br>            try FirebaseAuth.Auth.auth().signOut()<br>            content.removeAll()<br>            let vc = LoginViewController()<br>            let navi = UINavigationController(rootViewController: vc)<br>            navi.modalPresentationStyle = .fullScreen<br>            present(navi, animated: false)<br>        }<br>        catch{<br>            print(&quot;登出失敗\(error)&quot;)<br>        }<br>    }<br>}</pre><blockquote><strong>Store messages in Firebase Realtime Database</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/296/1*5dBuDd9gjT0rgHnZ4iXFOQ.gif" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W1D5-1w-Q-TxJg__1yKluA.png" /></figure><h4>Insert conversation messages into Firebase Realtime Database</h4><p>When the user presses the sent button, the message will not only be saved in the content property but also in Firebase.</p><pre>//MARK: - Send Message<br>    //按下傳送按鈕<br>class ChatViewController: UIViewController {<br><br>    var content = [Content]()<br>    var openAPIResponse:OpenAPIResponse?<br><br>    @IBAction func sendMessage(_ sender: UIButton) {<br>        let userMessage = userMessageTextField.text ?? &quot;no message&quot;<br>            //將輸入的訊息加進content陣列裡<br>        content.append(Content(name: .user, text: userMessage))<br>        <br>            //抓chatgpt API<br>            APICaller.shared.fetchChatGPTAPI(prompt: userMessage)<br>            { [weak self]<br>                openAPIResponse<br>                in<br>                DispatchQueue.main.async<br>                {<br>                    self?.openAPIResponse = openAPIResponse<br>                    let choicesText = openAPIResponse.choices[0].text<br><br>                    self?.content.append(Content(name: .chatgpt, text: choicesText ))<br>                    <br>                    //存入database<br>                    let currentUserEmail = Auth.auth().currentUser?.email<br>                     var safeEmail = currentUserEmail?.replacingOccurrences(of: &quot;.&quot;, with: &quot;-&quot;)<br>                     safeEmail = safeEmail?.replacingOccurrences(of: &quot;@&quot;, with: &quot;-&quot;)<br>                    DatabaseManager.shared.insertContent(with: Message(account: safeEmail ?? &quot;no user account&quot;, userMessage: userMessage, chatgptMessage: choicesText ))<br><br>                    self?.tableView.reloadData() //更新資料<br>                    //讓句子出現在最底層的對話中<br>                    let contentCount = (self?.content.count ?? 1) - 1<br>                    let indexPath = IndexPath(row: contentCount, section: 0)<br>                    self?.tableView.scrollToRow(at: indexPath, at: .bottom, animated: true)<br>                    <br>                }<br>                <br>            }<br><br>            userMessageTextField.text = &quot;&quot; //按下傳送按鈕後，textField輸入前先清空文字<br>            self.tableView.reloadData() //按下傳送按鈕，將傳入的文字更新table資料並顯示在畫面上<br>            view.endEditing(true) //按下傳送按鈕後退鍵盤<br>            //句子出現在最底層的對話中<br>            let indexPath = IndexPath(row: content.count-1, section: 0)<br>            self.tableView.scrollToRow(at: indexPath, at: .bottom, animated: true)<br>        }<br>}</pre><h4><strong>Download data from Firebase Realtime Database</strong></h4><p>The data is loaded when the user log into the app.</p><pre>import UIKit<br>import FirebaseAuth<br>import Firebase<br><br>class ChatViewController: UIViewController {<br><br>      override func viewWillAppear(_ animated: Bool) {<br>              super.viewWillAppear(animated)<br>              <br>              validateAuth()<br>          }<br>          <br>          //判斷是否登入<br>          private func validateAuth(){<br>            if{ ....略....}<br>            else{<br><br>              //download conversations data from firebase<br>              let currentUserEmail = Auth.auth().currentUser?.email ?? &quot;&quot;<br>              DatabaseManager.shared.loadConversations(email: currentUserEmail)<br>              { [weak self] snapshot in<br>                  self?.content.removeAll()<br>                  <br>                  if let allSnapshot = snapshot.children.allObjects as? [DataSnapshot]<br>                  {<br>                      for message in allSnapshot<br>                      {<br>                          let message = message.value as? [String:Any]<br> <br>                          let userMessage = message?[&quot;userMessage&quot;]<br>                          let chatgptMessage = message?[&quot;chatgptMessage&quot;]<br>  <br>                          self?.content.append(Content(name: .user, text: userMessage as! String))<br>                          self?.content.append(Content(name: .chatgpt, text: chatgptMessage as! String))<br>                          <br>                          DispatchQueue.main.async {<br>                              self?.tableView.reloadData()<br>                              //讓句子出現在最底層的對話中<br>                              let contentCount = (self?.content.count ?? 1 ) - 1<br>                              let indexPath = IndexPath(row: contentCount, section: 0)<br>                              self?.tableView.scrollToRow(at: indexPath, at: .bottom, animated: true)<br>                          }<br>                                                  <br>                      }<br>           <br>                  }<br>                  <br>              }<br>          }<br>}</pre><h4><strong>Display the messages in the chat bubble</strong></h4><pre>/MARK: - TableView<br>extension ChatViewController:UITableViewDelegate,UITableViewDataSource{<br>    <br>    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -&gt; Int {<br>        return content.count<br>    }<br>    <br>    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -&gt; UITableViewCell {<br>        let showContent = content[indexPath.row]<br>   <br>        if showContent.name == .chatgpt<br>            {<br>                let chatgptCell = tableView.dequeueReusableCell(withIdentifier: &quot;chatgptCell&quot;) as! ChatgptTableViewCell<br><br>                chatgptCell.chatgptTextView.text = showContent.text<br>                chatgptCell.chatgptLabel.text = showContent.name.rawValue<br>                chatgptCell.chatgptImageView.image = UIImage(named: &quot;chatgpt&quot;)<br>                chatgptCell.updateChatGPTUI()<br>                <br>                return chatgptCell<br>            }<br>        else{<br>                let userCell = tableView.dequeueReusableCell(withIdentifier: &quot;userCell&quot;) as! UserTableViewCell<br><br>                userCell.userLabel.text = showContent.name.rawValue<br>                userCell.userTextView?.text = showContent.text<br>                <br>                //downloade the profile picture from Firebase Storage<br>                    ...略...<br><br>                userCell.updateUserUI()<br>                <br>                    return userCell<br>                }<br>    }<br><br>}</pre><p><strong><em>Reference</em></strong></p><p><a href="https://ithelp.ithome.com.tw/m/articles/10259439">iT 邦幫忙::一起幫忙解決難題，拯救 IT 人的一天</a></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FqsBDL7fT8Mg%3Flist%3DPL5PR3UyfTWvdlk-Qi-dPtJmjTj-2YIMMf&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DqsBDL7fT8Mg&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FqsBDL7fT8Mg%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/15681608bdc23f7bfb1afdc224ffc1c7/href">https://medium.com/media/15681608bdc23f7bfb1afdc224ffc1c7/href</a></iframe><blockquote><strong>Store a profile picture in Firebase Storage</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sT-wM0dNT_vg861hT4ue7w.png" /></figure><h4>Upload the profile picture</h4><p><strong>DatabaseManager:</strong></p><p>When the user presses the register button, the user’s information, including their profile picture, will be saved in the Firebase database. The profile picture will be given a random name and given a URL path before being saved in Firebase Storage.</p><pre><br>final class DatabaseManager{<br>    //singleton<br>    static let shared = DatabaseManager()<br>    //從數據庫讀取或寫入數據realtime database<br>    private let databaseReference:DatabaseReference =  Database.database().reference()<br>    //上傳檔案到storage<br>    private let storageReference:StorageReference = Storage.storage().reference()<br>}<br><br>extension DatabaseManager{<br><br>///Inserts new user to database<br>    public func insertUser(with user:ChatAppUser)<br>    {<br>        databaseReference.child(&quot;User&quot;).child(user.safeEmail).setValue(<br>            [<br>            &quot;first_name&quot;: user.firstName,<br>            &quot;last_name&quot;: user.lastName,<br>            &quot;profile&quot;:user.profilePictureUrl<br>            ]<br>        )<br>    }<br><br>    ///Insert picture to database<br>   public func uploadPhoto(image:UIImage?, completion:@escaping (Result&lt;URL, Error&gt;)-&gt; Void)<br>    {<br>        let fileReference = storageReference.child(UUID().uuidString + &quot;.jpg&quot;)<br>        if let imageData = image?.jpegData(compressionQuality: 0.7)<br>        {<br>            fileReference.putData(imageData, metadata: nil)<br>            { result in<br>                switch result<br>                {<br>                    case .success:<br>                    fileReference.downloadURL(completion: completion)<br>                    case .failure(let error):<br>                        completion(.failure(error))<br>                }<br>            }<br>        }<br>    }<br><br>}</pre><p><strong>RegisterViewController:</strong></p><p>This program is written to execute the upload of the user’s information, including their profile picture’s path, when they press the register button.</p><pre>//按下register按鈕時確認輸入的資料是否完整<br>    @objc private func registerButtonTapped(){<br><br>    .... 略 ....<br><br>    //上傳註冊資料、照片到realtime database<br>    DatabaseManager.shared.uploadPhoto(image: self?.iconImageView.image) { result in<br>        switch result{<br>        case .success(let url):<br>            let imageUrlString = url.absoluteString<br>            <br>            //entry the database<br>            DatabaseManager.shared.insertUser(with: ChatAppUser(firstName: firstName, lastName: lastName, emailAddress: email,profilePictureUrl: imageUrlString))<br>    <br>        case .failure(let error):<br>            print(error)<br>        }<br>    }<br><br>}</pre><h4>Download &amp; show the profile picture</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*ByzQLTYhQ3WzheyRWQXZ8A.png" /></figure><p><strong>ChatViewController:</strong></p><p>Firstly, I checked if a profile picture’s URL path exists when the user logs into the app.</p><pre>class ChatViewController: UIViewController {<br><br>    var havePicture = false<br><br>    private func validateAuth(){<br><br>    ....略....<br><br>    //確認是否有大頭照的路徑<br>      DatabaseManager.shared.loadProfile(email: currentUserEmail) { [weak self] snapShot in<br>          if snapShot?.value as? String != nil{<br>              self?.havePicture = true<br>          }<br>      }<br>    }<br>}</pre><p>If a profile picture’s URL path is stored in Firebase Realtime Database, it will be loaded, and the user’s profile picture will show up. Otherwise, a system picture will be displayed on the profile.</p><pre>extension ChatViewController:UITableViewDelegate,UITableViewDataSource{<br>        <br>            ...略...<br>    <br>    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -&gt; UITableViewCell {<br>        let showContent = content[indexPath.row]<br>   <br>        if showContent.name == .chatgpt<br>            {<br>               ...略...<br>              //ChatGPT&#39;s messages are displayed in the chat bubble.<br>            }<br>        else{<br>              let userCell = tableView.dequeueReusableCell(withIdentifier: &quot;userCell&quot;) as! UserTableViewCell<br><br>              userCell.userLabel.text = showContent.name.rawValue<br>              userCell.userTextView?.text = showContent.text<br>            <br>            //download a profile picture from Firebase Storage.<br>            if self.havePicture == true{<br>                let currentEmail = Auth.auth().currentUser?.email ?? &quot;&quot;<br>                DatabaseManager.shared.loadProfile(email: currentEmail)<br>                { snapShot in<br>                    if let value = snapShot?.value as? String{                        <br>                        let pathUrl = URL(string: value)!<br>                        URLSession.shared.dataTask(with: pathUrl) { data, response, error in<br>                            guard let data = data, error == nil else{<br>                                return<br>                            }<br>                            DispatchQueue.main.async {<br>                                userCell.userImageView.image = UIImage(data: data)<br>                            }<br>                            print(&quot;大頭照路徑：\(pathUrl)&quot;)<br>                        }.resume()<br>                    }<br>                }<br>            }<br>            else{<br>                userCell.userImageView.image = UIImage(systemName: &quot;person.circle&quot; )<br>            }<br>                userCell.updateUserUI()<br>            <br>                return userCell<br>            }<br>    }<br>}</pre><p><strong><em>Reference</em></strong></p><p><a href="https://medium.com/%E5%BD%BC%E5%BE%97%E6%BD%98%E7%9A%84-swift-ios-app-%E9%96%8B%E7%99%BC%E5%95%8F%E9%A1%8C%E8%A7%A3%E7%AD%94%E9%9B%86/firebase-%E7%9A%84%E6%AA%94%E6%A1%88%E5%AD%98%E5%8F%96-f79a86e656b7">Firebase 的檔案存取</a></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FHmr8PsG9E2w%3Flist%3DPL5PR3UyfTWvdlk-Qi-dPtJmjTj-2YIMMf&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DHmr8PsG9E2w&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FHmr8PsG9E2w%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/437695b585e12a378e2ce15359fa0ec0/href">https://medium.com/media/437695b585e12a378e2ce15359fa0ec0/href</a></iframe><blockquote><strong>My GitHub</strong></blockquote><p><a href="https://github.com/Huangjieru/ChatWithAI/tree/DataStorage">GitHub - Huangjieru/ChatWithAI at DataStorage</a></p><blockquote>Übung macht den Meister.</blockquote><blockquote><strong>Reference</strong></blockquote><ul><li><a href="https://medium.com/%E5%BD%BC%E5%BE%97%E6%BD%98%E7%9A%84-swift-ios-app-%E9%96%8B%E7%99%BC%E5%95%8F%E9%A1%8C%E8%A7%A3%E7%AD%94%E9%9B%86/%E9%96%8B%E7%99%BC-firebase-cloud-firestore-%E7%9A%84-ios-app-fe38d6ad70a7">開發 Firebase Cloud Firestore 的 iOS App</a></li><li><a href="https://medium.com/%E5%BD%BC%E5%BE%97%E6%BD%98%E7%9A%84-swift-ios-app-%E9%96%8B%E7%99%BC%E6%95%99%E5%AE%A4/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></li><li><a href="https://medium.com/@cwlai.unipattern/app%E9%96%8B%E7%99%BC-%E4%BD%BF%E7%94%A8swift-21-2-firebase-%E6%96%B0%E5%A2%9E-7992eb05d797">[APP開發-使用Swift] 21–2. Firebase — 新增</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5368629e1560" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Chat with AI — part 2]]></title>
            <link>https://medium.com/@jieru04/chat-with-ai-part-2-dfd15e60ea54?source=rss-7f58831db4fb------2</link>
            <guid isPermaLink="false">https://medium.com/p/dfd15e60ea54</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Jru]]></dc:creator>
            <pubDate>Thu, 06 Apr 2023 08:52:06 GMT</pubDate>
            <atom:updated>2023-04-21T03:57:15.663Z</atom:updated>
            <content:encoded><![CDATA[<h3>Chat with AI — part 2</h3><p>Login or Register a new account</p><p><em>→ </em><a href="https://medium.com/%E5%BD%BC%E5%BE%97%E6%BD%98%E7%9A%84-swift-ios-app-%E9%96%8B%E7%99%BC%E6%95%99%E5%AE%A4/swift-app-chat-with-ai-dafd50abd0a5"><em>Part 1</em></a><em>: Connect ChatGPT’s API</em></p><p><em>→</em><a href="https://medium.com/@jieru04/chat-with-ai-part-3-5368629e1560"><em> part 3</em></a><em>: Store the data in Firebase</em></p><h3><strong>Part 2</strong></h3><p>I used the video tutorials to set up my login and register view controller in my app.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Fg7ipElQVpgU%3Flist%3DPL5PR3UyfTWvdlk-Qi-dPtJmjTj-2YIMMf&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3Dg7ipElQVpgU&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2Fg7ipElQVpgU%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/571e0b38a03671af21a534141cf8b2b8/href">https://medium.com/media/571e0b38a03671af21a534141cf8b2b8/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FCftU33ZNjAU%3Flist%3DPL5PR3UyfTWvdlk-Qi-dPtJmjTj-2YIMMf&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DCftU33ZNjAU&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FCftU33ZNjAU%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/596826f790c3ba72801660382dce2120/href">https://medium.com/media/596826f790c3ba72801660382dce2120/href</a></iframe><h3><strong>Features:</strong></h3><ul><li><strong>Add CocoaPods → pod init</strong></li><li><strong>Add login and register view controllers</strong></li><li><strong>Take a picture or choose a picture from album when registering</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/296/1*ZVbY49Ve3A0iJtPUTBxHEw.gif" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LgFyHYtzgtzMY4DuImlEpA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tiwWxbs_zoOc1zkUv5UJmw.png" /></figure><blockquote>Add CocoaPods</blockquote><p>To create a Podfile in your project directory using the terminal, you need to navigate to the project directory and run the command pod init . Once you’ve done this, you should be able to see the newly created Podfile in your project file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/503/1*VySuMqjddzgqUrjwwFqY9w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/234/1*_BhBCsE-uPayeLhJMSPeOA.png" /></figure><p><strong><em>Reference</em></strong></p><p>install CocoaPods</p><ul><li><a href="https://www.appcoda.com.tw/cocoapods/">CocoaPods 簡介 : 如何輕鬆管理 Swift / Objective-C 的類庫</a></li><li><a href="https://medium.com/@h86991868/%E4%BD%BF%E7%94%A8cocoapods%E4%BE%86%E7%AE%A1%E7%90%86%E7%AC%AC%E4%B8%89%E6%96%B9%E5%A5%97%E4%BB%B6-69dc00de9d62">使用cocoaPods來管理第三方套件</a></li></ul><p>Delete CocoaPods</p><p><a href="https://ithelp.ithome.com.tw/articles/10295469?sc=iThelpR">[鐵人賽 Day 09] Swift CocoaPods 初入門-3 - iT 邦幫忙::一起幫忙解決難題，拯救 IT 人的一天</a></p><blockquote>LoginViewController</blockquote><p>To chat with ChatCPT, the user must first log in to the app.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LgFyHYtzgtzMY4DuImlEpA.png" /></figure><p>I have set up UI objects on a scroll view, which is placed on the view.</p><pre>import UIKit<br><br>class LoginViewController: UIViewController {<br><br>    private let scrollView:UIScrollView = {<br>        let scrollView = UIScrollView()<br>        scrollView.clipsToBounds = true //剪裁超出的部分。在 UIScrollView 中，默認是true<br>        return scrollView<br>    }()<br>    <br>    private let iconImageView:UIImageView = {<br>        let imageView = UIImageView()<br>        imageView.image = UIImage(named: &quot;chatBubbleIcon&quot;)<br>        imageView.contentMode = .scaleAspectFit<br>        return imageView<br>    }()<br>    <br>    private let emailField:UITextField = {<br>        let field = UITextField()<br>        field.autocapitalizationType = .none<br>        field.autocorrectionType = .no //測你所輸入的文字<br>        field.keyboardType = .emailAddress //適用輸入 Email 的鍵盤<br>        field.returnKeyType = .continue //鍵盤上的 return改成continune<br>        field.layer.cornerRadius = 15<br>        field.layer.borderWidth = 2<br>        field.layer.borderColor = UIColor.lightGray.cgColor<br>        field.placeholder = &quot;Email Address&quot;<br>        field.leftView = UIView(frame: CGRect(x: 0, y: 0, width: 10, height: 0))//讓輸入的文字不會與邊框太貼近，text field 的左邊加上想呈現的內容-&gt;形成左邊padding空間變大10<br>        field.leftViewMode = .always //永遠顯示<br>        field.backgroundColor = .white //輸入背景變白色<br>       return field<br>    }()<br>    <br>    private let passwordField:UITextField = {<br>        let field = UITextField()<br>        field.autocapitalizationType = .none<br>        field.autocorrectionType = .no<br>        field.returnKeyType = .done //鍵盤上的 return改成done<br>        field.layer.cornerRadius = 15<br>        field.layer.borderWidth = 2<br>        field.layer.borderColor = UIColor.lightGray.cgColor<br>        field.placeholder = &quot;Password...&quot;<br>        field.leftView = UIView(frame: CGRect(x: 0, y: 0, width: 10, height: 0))//讓輸入的文字不會與邊框太貼近，text field 的左邊加上想呈現的內容-&gt;形成左邊padding空間變大10<br>        field.leftViewMode = .always //永遠顯示<br>        field.backgroundColor = .white //輸入背景變白色<br>        field.isSecureTextEntry = true<br>       return field<br>    }()<br>    <br>    private let loginButton: UIButton = {<br>       let button = UIButton()<br>        button.setTitle(&quot;Log In&quot;, for: .normal)<br>        button.backgroundColor = .link<br>        button.setTitleColor(.white, for: .normal)<br>        button.layer.cornerRadius = 12<br>        button.titleLabel?.font = .systemFont(ofSize: 20, weight: .bold)<br>        return button<br>    }()<br>    <br>    private let registerButton:UIButton = {<br>        let button = UIButton()<br>        button.setTitle(&quot;Register&quot;, for: .normal)<br>        button.setTitleColor(.link, for: .normal)<br>        button.titleLabel?.font = .systemFont(ofSize: 17, weight: .semibold)<br>        <br>        return button<br>    }()<br><br>    override func viewDidLoad() {<br>        super.viewDidLoad()<br><br>        view.backgroundColor = .white<br>        title = &quot;Log In&quot;<br><br>        // Add subview<br>        view.addSubview(scrollView)<br>        scrollView.addSubview(iconImageView)<br>        scrollView.addSubview(emailField)<br>        scrollView.addSubview(passwordField)<br>        scrollView.addSubview(loginButton)<br>        scrollView.addSubview(registerButton)<br>    }<br>}</pre><p>Then I created a new file and specified the coordinates , width and height on the view.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/729/1*9MnetVN-ElyJmptlE6-j7A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ykgs9khwhuMC-50ytui0gA.png" /></figure><pre>import Foundation<br>import UIKit<br><br>extension UIView{<br>    <br>    public var width:CGFloat{<br>        return self.frame.size.width<br>    }<br>    public var height:CGFloat{<br>        return self.frame.size.height<br>    }<br>    public var top:CGFloat{<br>        return self.frame.origin.y<br>    }<br>    public var bottom:CGFloat{<br>        return self.frame.origin.y + self.frame.size.height<br>    }<br>    public var left:CGFloat{<br>        return self.frame.origin.x<br>    }<br>    public var right:CGFloat{<br>        return self.frame.origin.x + self.frame.size.width<br>    }<br>}</pre><p>Once the app has finished loading the viewDidLoad() method, the UI objects are laid out in the viewDidLayoutSubviews() method.</p><pre>import UIKit<br><br>class LoginViewController: UIViewController {<br><br>    override func viewDidLayoutSubviews() {<br>        super.viewDidLayoutSubviews()<br><br>        scrollView.frame = view.bounds //設置extensions檔案<br><br>        let imageSize = view.width/3 <br><br>        iconImageView.frame = CGRect(x: (scrollView.width-imageSize)/2,<br>                                     y: 20,<br>                                     width: imageSize,<br>                                     height: imageSize)<br>        emailField.frame = CGRect(x: 40,<br>                                  y: iconImageView.bottom + 40,<br>                                  width: scrollView.width-80,<br>                                  height: 50)<br>        passwordField.frame = CGRect(x: 40,<br>                                  y: emailField.bottom + 20,<br>                                  width: scrollView.width-80,<br>                                  height: 50)<br>        loginButton.frame = CGRect(x: 40,<br>                                  y: passwordField.bottom + 30,<br>                                  width: scrollView.width-80,<br>                                  height: 50)<br>        registerButton.frame.origin = CGPoint(x: view.center.x - 50, <br>                                              y: loginButton.bottom + 30)<br>        registerButton.frame.size = CGSize(width: 100, height: 30)<br>    }<br>}</pre><p>When the user taps the login button, the app checks if the text fields are empty or if the password is less than 6 characters. If the user does not enter the correct format, an alert will pop up to prompt them to correct their input.</p><pre>import UIKit<br><br>class LoginViewController: UIViewController {  <br><br>      override func viewDidLoad() {<br>              super.viewDidLoad()<br>      <br>              loginButton.addTarget(self, action: #selector(loginButtonTapped), for: .touchUpInside)<br>      <br>      }<br>      <br>        //按下login按鈕時確認輸入的資料是否完整<br>          @objc private func loginButtonTapped(){<br>              //按下login按鈕後，不會出現鍵盤<br>              emailField.resignFirstResponder()<br>              passwordField.resignFirstResponder()<br>              //判斷輸入是否符合規定<br>              guard let email = emailField.text, let password = passwordField.text, !email.isEmpty, !password.isEmpty, password.count &gt;= 6 else {<br>                  alertUserLoginError()<br>                  return<br>              }<br>              // Firebase log in<br>          }<br>          func alertUserLoginError(){<br>              let alert = UIAlertController(title: &quot;Oops!&quot;, message: &quot;Please enter all information to log in&quot;, preferredStyle: UIAlertController.Style.alert)<br>              alert.addAction(UIAlertAction(title: &quot;Dismiss&quot;, style: .cancel))<br>              present(alert, animated: true)<br>              <br>          }<br>}</pre><p>After the user finishes entering their email and taps the continue button on the keyboard, the user can proceed to enter their password. Once the password is completed, the user can press done button on the keyboard and to log in to their account.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QTi7Y7hSVv2H8YE8H5Z6lg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IajZrChcVNJuUlOeXMKZQg.png" /></figure><pre> override func viewDidLoad() {<br>        super.viewDidLoad()<br><br>        emailField.delegate = self<br>        passwordField.delegate = self<br>}<br><br>extension LoginViewController:UITextFieldDelegate<br>{<br>    func textFieldShouldReturn(_ textField: UITextField) -&gt; Bool <br>    {<br><br>        //使用者按下鍵盤上continue按鈕，可以繼續輸入密碼<br>        if textField == emailField{<br>            passwordField.becomeFirstResponder() //focus on password<br>        }<br>        //輸入密碼後按下鍵盤上的done等於按下登入按鈕<br>        else if textField == passwordField{<br>            loginButtonTapped() <br>        }<br>        return true<br>    }<br>}</pre><p>The user can create a new account by tapping the Register button located below the Log In button.</p><pre>override func viewDidLoad() {<br>        super.viewDidLoad()<br>        <br>        //按下login按鈕下方的註冊也可以連到與右上角按鈕同一個註冊畫面<br>        registerButton.addTarget(RegisterViewController(), action: #selector(didTapRegister), for: .touchUpInside)<br>       <br>    }<br><br>    @objc private func didTapRegister(){<br>        let registerVC = RegisterViewController()<br>        registerVC.title = &quot;Register Account&quot;<br>        navigationController?.pushViewController(registerVC, animated: true)<br>    }</pre><blockquote>RegisterViewController</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RzG1wPki9UtGL89ce8Uxbw.png" /></figure><p>The RegisterViewController’s program is similar to the LoginViewController’s, but with the addition of the firstName and lastName properties. Additionally, the name of the Log In button has been changed to Register and the didTapRegister() method has been removed. The function that checks if the user has correctly entered all the required text fields has also been modified.</p><pre>import UIKit<br><br>class RegisterViewController: UIViewController {<br>    <br>    private let scrollView:UIScrollView = {<br>        let scrollView = UIScrollView()<br>        scrollView.clipsToBounds = true //剪裁超出的部分。在 UIScrollView 中，它的默認true <br>        return scrollView<br>    }()<br>    <br>    private let iconImageView:UIImageView = {<br>        let imageView = UIImageView()<br>        imageView.image = UIImage(systemName: &quot;person.circle&quot;)<br>        imageView.tintColor = .gray<br>        imageView.contentMode = .scaleAspectFill<br>        imageView.layer.masksToBounds = true //imageView.clipsToBounds = true效果相同(裁切)<br>        imageView.layer.borderWidth = 3<br>        imageView.layer.borderColor = UIColor.link.cgColor<br>        return imageView<br>    }()<br>    <br>    private let firstName:UITextField = {<br>        let field = UITextField()<br>        field.autocapitalizationType = .none<br>        field.autocorrectionType = .no<br>        field.returnKeyType = .continue<br>        field.layer.cornerRadius = 15<br>        field.layer.borderWidth = 2<br>        field.layer.borderColor = UIColor.lightGray.cgColor<br>        field.placeholder = &quot;First Name&quot;<br>        field.leftView = UIView(frame: CGRect(x: 0, y: 0, width: 10, height: 0))<br>        field.leftViewMode = .always<br>        field.backgroundColor = .white<br>        return field<br>    }()<br>    <br>    private let lastName:UITextField = {<br>        let field = UITextField()<br>        field.autocapitalizationType = .none<br>        field.autocorrectionType = .no<br>        field.returnKeyType = .continue<br>        field.layer.cornerRadius = 15<br>        field.layer.borderWidth = 2<br>        field.layer.borderColor = UIColor.lightGray.cgColor<br>        field.placeholder = &quot;Last Name&quot;<br>        field.leftView = UIView(frame: CGRect(x: 0, y: 0, width: 10, height: 0))<br>        field.leftViewMode = .always<br>        field.backgroundColor = .white<br>        return field<br>    }()<br>    <br>    private let emailField:UITextField = {<br>        let field = UITextField()<br>        field.autocapitalizationType = .none<br>        field.autocorrectionType = .no //測你所輸入的文字，列出相依性高的單字們(https://ithelp.ithome.com.tw/articles/10220888)<br>        field.keyboardType = .emailAddress //適用輸入 Email 的鍵盤<br>        field.returnKeyType = .continue //鍵盤上的 return改成continune<br>        field.layer.cornerRadius = 15<br>        field.layer.borderWidth = 2<br>        field.layer.borderColor = UIColor.lightGray.cgColor<br>        field.placeholder = &quot;Email Address&quot;<br>        field.leftView = UIView(frame: CGRect(x: 0, y: 0, width: 10, height: 0))//加大輸入的空間，不要貼在框邊上。text field 的左邊加上想呈現的內容-&gt;形成左邊padding空間變大10<br>        field.leftViewMode = .always //永遠顯示<br>        field.backgroundColor = .white //輸入背景變白色<br>        return field<br>    }()<br>    <br>    private let passwordField:UITextField = {<br>        let field = UITextField()<br>        field.autocapitalizationType = .none<br>        field.autocorrectionType = .no<br>        field.returnKeyType = .done //鍵盤上的 return改成done<br>        field.layer.cornerRadius = 15<br>        field.layer.borderWidth = 2<br>        field.layer.borderColor = UIColor.lightGray.cgColor<br>        field.placeholder = &quot;Password...&quot;<br>        field.leftView = UIView(frame: CGRect(x: 0, y: 0, width: 10, height: 0))//加大輸入的空間，不要貼在框邊上。text field 的左邊加上想呈現的內容-&gt;形成左邊padding空間變大10<br>        field.leftViewMode = .always //永遠顯示<br>        field.backgroundColor = .white //輸入背景變白色<br>        field.isSecureTextEntry = true<br>        return field<br>    }()<br>    <br>    private let registerButton: UIButton = {<br>       let button = UIButton()<br>        button.setTitle(&quot;Register&quot;, for: .normal)<br>        button.backgroundColor = .link<br>        button.setTitleColor(.white, for: .normal)<br>        button.layer.cornerRadius = 12<br>//        button.layer.masksToBounds = true //CALayer的属性<br>        button.titleLabel?.font = .systemFont(ofSize: 20, weight: .bold)<br>        return button<br>    }()<br>    <br>    override func viewDidLoad() {<br>        super.viewDidLoad()<br><br>        view.backgroundColor = .white<br>        title = &quot;Register Account&quot;<br><br>        registerButton.addTarget(self, action: #selector(registerButtonTapped), for: .touchUpInside)<br><br>        <br>        // Add subview<br>        view.addSubview(scrollView)<br>        scrollView.addSubview(iconImageView)<br>        scrollView.addSubview(firstName)<br>        scrollView.addSubview(lastName)<br>        scrollView.addSubview(emailField)<br>        scrollView.addSubview(passwordField)<br>        scrollView.addSubview(registerButton)<br><br>    }<br>    <br>    override func viewDidLayoutSubviews() {<br>        super.viewDidLayoutSubviews()<br><br>        scrollView.frame = view.bounds<br><br>        let imageSize = view.width/3<br><br>        iconImageView.frame = CGRect(x: (scrollView.width-imageSize)/2,<br>                                     y: 20,<br>                                     width: imageSize + 20,<br>                                     height: imageSize + 20)<br>        iconImageView.layer.cornerRadius = iconImageView.width/2 //圓形頭像<br><br>        firstName.frame = CGRect(x: 40,<br>                                  y: iconImageView.bottom + 40,<br>                                  width: scrollView.width-80,<br>                                  height: 50)<br>        lastName.frame = CGRect(x: 40,<br>                                  y: firstName.bottom + 20,<br>                                  width: scrollView.width-80,<br>                                  height: 50)<br>        emailField.frame = CGRect(x: 40,<br>                                  y: lastName.bottom + 20,<br>                                  width: scrollView.width-80,<br>                                  height: 50)<br>        passwordField.frame = CGRect(x: 40,<br>                                     y: emailField.bottom + 20,<br>                                     width: scrollView.width-80,<br>                                     height: 50)<br>        <br>        registerButton.frame = CGRect(x: 40,<br>                                     y: passwordField.bottom + 20,<br>                                     width: scrollView.width-80,<br>                                     height: 50)<br>    }<br>    //按下register按鈕時確認輸入的資料是否完整<br>    @objc private func registerButtonTapped(){<br>        firstName.resignFirstResponder()<br>        lastName.resignFirstResponder()<br>        emailField.resignFirstResponder()<br>        passwordField.resignFirstResponder()<br>        <br>        guard let firstName = firstName.text, let lastName = lastName.text, let email = emailField.text, let password = passwordField.text, !firstName.isEmpty, !lastName.isEmpty, !email.isEmpty, !password.isEmpty, password.count &gt;= 6 else {<br>            alertUserLoginError()<br>            return<br>        }<br>        // Firebase log in<br>    }<br>    func alertUserLoginError(){<br>        let alert = UIAlertController(title: &quot;Oops!&quot;, message: &quot;Please enter all information to create a new account&quot;, preferredStyle: UIAlertController.Style.alert)<br>        alert.addAction(UIAlertAction(title: &quot;Dismiss&quot;, style: .cancel))<br>        present(alert, animated: true)<br>        <br>    }<br>    <br>}</pre><p>The textField extension has been modified so that the user can continue filling out the next text field by pressing the continue button on the keyboard.</p><pre>class RegisterViewController: UIViewController {<br> <br>  override func viewDidLoad() {<br>          super.viewDidLoad()<br>  <br>          firstName.delegate = self<br>          lastName.delegate = self<br>          emailField.delegate = self<br>          passwordField.delegate = self<br>      }<br>}<br>  <br>extension RegisterViewController:UITextFieldDelegate{<br>    func textFieldShouldReturn(_ textField: UITextField) -&gt; Bool <br>{<br>        switch textField<br>        {<br>          case firstName:<br>              lastName.becomeFirstResponder()<br>          case lastName:<br>              emailField.becomeFirstResponder()<br>          case emailField:<br>              passwordField.becomeFirstResponder()<br>          case passwordField:<br>              registerButtonTapped()<br>          default:<br>              return true<br>        }<br>        return true<br>    }<br>}</pre><h4>Take a picture or choose form a album</h4><p>The user can tap the profile picture to add a picture from the their album or taking a picture.</p><pre>import PhotosUI //PhPickerViewController<br><br>class RegisterViewController: UIViewController {<br><br>    override func viewDidLoad() {<br>        super.viewDidLoad()<br><br>        //點選imageView跳出選單可選擇照相或從相簿選照片<br>        iconImageView.isUserInteractionEnabled = true<br>        scrollView.isUserInteractionEnabled = true<br><br>        let gesture = UITapGestureRecognizer(target: self, action: #selector(didTapChangeProfilePic))<br>        iconImageView.addGestureRecognizer(gesture)<br>    }<br><br>    //點選imageView跳出選單(sheet)<br>    @objc private func didTapChangeProfilePic(){<br>        print(&quot;Change pic called&quot;)<br>        presentPhotoActionSheet()<br>    }<br>}</pre><p>The action sheet will appear, giving the user the option to choose how they want to select a picture, as shown in the picture below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D4dgjqm49hE5u6xDrsNBVQ.png" /></figure><pre>extension RegisterViewController:UIImagePickerControllerDelegate, UINavigationControllerDelegate,PHPickerViewControllerDelegate<br>{<br>    //跳出選單<br>    func presentPhotoActionSheet(){<br>        let actionSheet  = UIAlertController(title: &quot;Profile Picture&quot;, message: &quot;How would you like to select a picture?&quot;, preferredStyle: .actionSheet)<br>        actionSheet.addAction(UIAlertAction(title: &quot;Cancel&quot;, style: .cancel))<br>        actionSheet.addAction(UIAlertAction(title: &quot;Take Photo&quot;, style: .default,handler: { [weak self] _ in<br>            self?.presentCamer()<br>        }))<br>        actionSheet.addAction(UIAlertAction(title: &quot;Choose Photo&quot;, style: .default,handler: { [weak self] _ in<br>            self?.presentPhotoPicker()<br>        }))<br>        present(actionSheet, animated: true)<br>    }<br><br>      .....略.....<br>}</pre><p>Add the privacy rules</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MUkoOT91R3TdxEUOnUmZ7w.png" /></figure><ol><li>Take a picture</li></ol><p>Conform the UIImagePickerControllerDelegate, UINavigationControllerDelegate protocol</p><pre>extension RegisterViewController:UIImagePickerControllerDelegate, UINavigationControllerDelegate,PHPickerViewControllerDelegate<br>{<br>    .....略.....<br><br>    //tak a picture<br>    func presentCamer(){<br>        let vc = UIImagePickerController()<br>        vc.sourceType = .camera<br>        vc.delegate = self<br>        vc.allowsEditing = true<br>        present(vc, animated: true)<br>    }<br><br>    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {<br>        print(info)<br>        guard let selectedImage = info[UIImagePickerController.InfoKey.editedImage] as? UIImage else {return} //編輯過後的照片<br>        self.iconImageView.image = selectedImage<br>    }<br><br>    func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {<br>        picker.dismiss(animated: true)<br>    }<br><br>}   </pre><p>2. Choose a photo from the album</p><p>Don’t forget to import PhotosUI and conform the PHPickerViewControllerDelegate protocol.</p><pre>extension RegisterViewController:UIImagePickerControllerDelegate, UINavigationControllerDelegate,PHPickerViewControllerDelegate<br>{<br>      .....略.....<br>      <br>    func presentPhotoPicker(){<br>        var configuration = PHPickerConfiguration()<br>        configuration.filter = .images //PHPickerConfiguration 的 filter 預設為 nil，代表可以選擇照片跟影片。<br>        configuration.selectionLimit = 1 //預設只能選一張照片(此行可寫可不寫)<br>        let picker = PHPickerViewController(configuration: configuration) //預設只能選一張照片<br>        picker.delegate = self<br>        present(picker, animated: true)<br>    }<br><br><br>    //相簿選一張照片<br>    func picker(_ picker: PHPickerViewController, didFinishPicking results: [PHPickerResult])<br>    {<br>        picker.dismiss(animated: true)<br>        <br>        let itemProviders = results.map { $0.itemProvider } //選擇照片的結果在帶在型別 [PHPickerResult] 的參數 results 裡，從 PHPickerResult 的 itemProvider 可載入選擇的照片，得到型別 [NSItemProvider] 的 array。<br>        //使用者選擇的照片數量。先檢查 itemProviders.first 是否有值。loadObject(ofClass:completionHandler:) 載入照片<br>        if let itemProvider = itemProviders.first, itemProvider.canLoadObject(ofClass: UIImage.self)<br>        {<br>            let previousImage = self.iconImageView.image<br>            itemProvider.loadObject(ofClass: UIImage.self)<br>            {<br>                [weak self] image, error<br>                in<br>                DispatchQueue.main.async<br>                {<br>                    guard let self = self, let image = image as? UIImage, self.iconImageView.image == previousImage else {return}<br>                    self.iconImageView.image = image<br>                }<br>            }<br>        }<br>    }<br><br>}</pre><p>Reference — PHPickerViewController</p><p><a href="https://medium.com/%E5%BD%BC%E5%BE%97%E6%BD%98%E7%9A%84-swift-ios-app-%E9%96%8B%E7%99%BC%E5%95%8F%E9%A1%8C%E8%A7%A3%E7%AD%94%E9%9B%86/ios-14-%E6%8F%90%E4%BE%9B%E5%A4%9A%E9%81%B8%E7%85%A7%E7%89%87%E5%8A%9F%E8%83%BD%E7%9A%84-phpickerviewcontroller-d9733d203222">iOS 14 提供多選照片功能的 PHPickerViewController</a></p><blockquote>My GitHub</blockquote><p><a href="https://github.com/Huangjieru/ChatWithAI/tree/Login%26Register">GitHub - Huangjieru/ChatWithAI at Login&amp;Register</a></p><blockquote>Übung macht den Meister</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dfd15e60ea54" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Swift App —  Chat with AI]]></title>
            <link>https://medium.com/peter-pan-swift-ios-class/swift-app-chat-with-ai-dafd50abd0a5?source=rss-7f58831db4fb------2</link>
            <guid isPermaLink="false">https://medium.com/p/dafd50abd0a5</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[chatgpt]]></category>
            <category><![CDATA[ios-develop]]></category>
            <dc:creator><![CDATA[Jru]]></dc:creator>
            <pubDate>Sat, 11 Mar 2023 08:42:09 GMT</pubDate>
            <atom:updated>2023-04-21T04:06:52.467Z</atom:updated>
            <content:encoded><![CDATA[<h3>Swift App — Chat with AI</h3><p>[Part 1] Let’s ask ChatGPT some questions using Swift through ChatGPT’s API.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1KmcNsD5wJjQKvTQ4w7nmA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/296/1*ZHvS96DNHWm5kjiP5bQdxw.gif" /></figure><h4><strong>Part 1 — Features:</strong></h4><ul><li><strong>Connect ChatGPT’s API</strong></li><li><strong>Define a struct type</strong></li><li><strong>Create XIB files</strong></li><li><strong>Adjust the position of the keyboard when it covers a text field</strong></li><li><strong>Dismiss the keyboard → <em>textFieldShouldReturn(_ textField:), touchesBegan(_ touches:, with event: ), endEditing(_ force:)</em></strong></li></ul><p>Go to see:</p><p><em>→ </em><a href="https://medium.com/@jieru04/chat-with-ai-part-2-dfd15e60ea54"><em>Part 2</em></a><em>: Create views for login and registration</em></p><p><em>→ </em><a href="https://medium.com/@jieru04/chat-with-ai-part-3-5368629e1560"><em>Part 3</em></a><em>: Store the data in Firebase</em></p><p>There are a variety of APIs offered by ChatGPT, and I have connected <strong>Completions</strong> <strong>API</strong> on my project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7E-noT-1sIgvVkNcFOMvLg.png" /></figure><h4><strong><em>MVVM</em></strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/270/1*DRKacvSSJRIXt7x48u8cqQ.png" /></figure><blockquote><strong>View</strong></blockquote><h4><strong>Main.Storyboard</strong></h4><p>I placed the Table View, textField, button on the main storyboard, and then put the textField and button into a stack view.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/662/1*6v-qCW1g5je8PRafCcu0VQ.png" /></figure><h4><strong>XIB file</strong></h4><p>I create two XIB files, one for the user’s cell and another for the ChatGPT’s cell, in order to define different layouts for each cell and manage them separately.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/375/1*EOX4Sxl5TO9yCM7sDwP6_A.png" /></figure><ol><li>A XIB file is created alongside when creating a new file.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/724/1*ZpUvM7YVMUv1ldiTKOP1dg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/733/1*4OT2zsciXyIKRAb3purmuw.png" /><figcaption>to choose Cocoa Touch Class &amp; click create XIB file</figcaption></figure><p>2. Then you’ll get two files: TableViewCell.xib, TableViewCell</p><p>TableViewCell.xib: to set UI objects.</p><p>TableViewCell: to program, to connect @UBOutlet</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/321/1*xneqssT31BNqTB1tBrGyvQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*6bu2YEQJ8THAevGdgDpYYw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2kPDG6cokuMKh6QjnUPzLg.png" /></figure><p>3. Identify the cell</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PE7euxb1mlau3byJi9oztw.png" /><figcaption>identifier of ChatGPT’s cell</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O5pZpoG7KbEQwAlNShMkPw.png" /><figcaption>identifier of User’s cell</figcaption></figure><p>4. Connect @UBOutlet and design UI</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/837/1*m30R-PMKxOopX3os3Pexuw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/821/1*f4E1YeGnZwb3pbQzvt5uAQ.png" /></figure><p>4. Add the two XIB files in the main ViewController (ChatViewController)</p><pre>override func viewDidLoad() {<br>        super.viewDidLoad()<br>        <br>         ...略...<br>        <br>        let chatgptTableViewCellXib = UINib(nibName: &quot;ChatgptTableViewCell&quot;, bundle: nil)<br>        tableView.register(chatgptTableViewCellXib, forCellReuseIdentifier: &quot;chatgptCell&quot;)<br>        let userTableViewCellXib = UINib(nibName: &quot;UserTableViewCell&quot;, bundle: nil)<br>        tableView.register(userTableViewCellXib, forCellReuseIdentifier: &quot;userCell&quot;)<br>        <br>    }</pre><h4>Auto Layout</h4><p>Text bubbles adjust their size dynamically based on the length of the text within them.</p><p>ChatGPTCell:</p><p>The <strong>trailing</strong> and <strong>bottom</strong> constraints set with a relation value that is <strong>greater than or equal</strong> to the size of the superview.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TAWL5aoZp062CiZWMyrTGg.png" /></figure><p>UserCell:</p><p>The <strong>leading</strong> and <strong>bottom</strong> constraints set with a relation value that is <strong>greater than or equal</strong> to the size of the superview.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4ATHN7yiCP0YfFDElu4xaw.png" /></figure><p>Do not check the scrolling enabled checkbox and allow the text view to adjust automatically based on the text length.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/957/1*GAjxVkSLbtTUo0w20D_Oeg.png" /></figure><blockquote><strong>Model</strong> — Content.swift</blockquote><p>I opened a new file and wrote the model for the request and response from chatGPT API.</p><p>Here is a document of API. ☞ <a href="https://platform.openai.com/docs/api-reference/introduction">ChatGPT API documentation</a></p><pre>struct OpenAPIParameters:Encodable{<br>    let model:String = &quot;text-davinci-003&quot;<br>    let prompt:String<br>    let temperature:Double = 0.8<br>    let max_tokens = 3000<br><br>}<br>struct OpenAPIResponse:Decodable{<br>    let choices:[Choices]<br>}<br>struct Choices:Decodable{<br>    let text:String<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/363/1*6agmmKlhAPKiDC5-HA1x7g.png" /><figcaption><a href="https://platform.openai.com/docs/api-reference/completions">Completions API</a></figcaption></figure><p>And I also wrote a model that can be used with on other functions.</p><pre>enum Name:String{<br>    case chapgpt = &quot;ChatGPT&quot;<br>    case user = &quot;Me&quot;<br>}<br><br>struct Content{<br>    let name:Name<br>    let text:String<br>}</pre><blockquote><strong>ViewModel</strong> — APICaller.swift</blockquote><p>Firstly, you need to register and then obtain a API key for authentication.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ah0F_2cDYmA3VURVjXsDxA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SPZXi7CEJTQg2ho0W-7Lfw.png" /><figcaption>to get API key</figcaption></figure><p>Next, I established a connection to the API using JSON.</p><pre>import Foundation<br><br>struct APICaller{<br>    static let shared = APICaller()<br>    private let apiKey = &quot;Your API key&quot;<br>    private let baseURL:URL = URL(string: &quot;https://api.openai.com/v1/&quot;)!<br>    <br>    func fetchChatGPTAPI(prompt:String,completion:@escaping(OpenAPIResponse)-&gt;Void)<br>    {<br>        let completionsURL = APICaller.shared.baseURL.appending(component: &quot;completions&quot;)<br>        var request = URLRequest(url: completionsURL)<br>        request.httpMethod = &quot;POST&quot;<br>        request.setValue(&quot;application/json&quot;, forHTTPHeaderField: &quot;Content-Type&quot;)<br>        request.setValue(&quot;Bearer \(APICaller.shared.apiKey) &quot;, forHTTPHeaderField: &quot;Authorization&quot;)<br>        let openAIBody = OpenAPIParameters(prompt: prompt)<br>        request.httpBody = try? JSONEncoder().encode(openAIBody)<br>        <br>        URLSession.shared.dataTask(with: request) <br>        {<br>          data, response, error <br>          in<br>          if let data = data<br>          {<br>              do<br>              {<br>                  let jsonDecoder = JSONDecoder()<br>                  jsonDecoder.keyDecodingStrategy = .convertFromSnakeCase<br>                  let openAPIResponse = try jsonDecoder.decode(OpenAPIResponse.self, from: data)<br>//                    print(openAPIResponse)<br>                  completion(openAPIResponse)<br>              }<br>              catch<br>              {<br>                  print(error)<br>              }<br>          }<br>        }.resume()<br>    }<br>}</pre><p><strong><em>Reference</em></strong></p><p><a href="https://medium.com/%E5%BD%BC%E5%BE%97%E6%BD%98%E7%9A%84-swift-ios-app-%E9%96%8B%E7%99%BC%E5%95%8F%E9%A1%8C%E8%A7%A3%E7%AD%94%E9%9B%86/%E6%A8%A1%E4%BB%BF-apple-%E5%AE%98%E6%96%B9%E7%AF%84%E4%BE%8B%E4%B8%B2%E6%8E%A5-json-api-%E5%AE%9A%E7%BE%A9-function-%E5%9E%8B%E5%88%A5%E7%9A%84-completion-%E5%8F%83%E6%95%B8-%E4%BD%BF%E7%94%A8-result-type-9b058c77df5d">模仿 Apple 官方範例串接 JSON API，定義 function 型別的 completion 參數 &amp; 使用 Result type</a></p><blockquote><strong>Controller</strong> — ChatViewController</blockquote><ol><li>to request/ response from API</li></ol><p>When the user sends a text message by pressing send button, the message will store in content array and then is added to a TableView. ChatGPT will then response to the message via an API, and the response will stored in content array and displayed in the TableView.</p><p>The content array store both the user’s message and ChatGPT’s responses. To display each message in its own cell, the TableView uses the sender’s <strong>name</strong> as a reference.</p><p>After adding a new message to the content array, you must call reloadData() to update the TableView. To ensure that the newest message is visible, you can use the scrollToRow(at:,at:,animated:) function to scroll at the bottom of the TableView.</p><pre>import UIKit<br><br>class ChatViewController: UIViewController {<br><br>    @IBOutlet weak var userMessageTextField: UITextField!<br>    @IBOutlet weak var tableView: UITableView!<br><br>    var content = [Content]()<br>    var openAPIResponse:OpenAPIResponse?<br><br>    override func viewDidLoad() {<br>        super.viewDidLoad()<br><br>        tableView.delegate = self<br>        tableView.dataSource = self<br>        userMessageTextField.delegate = self<br>    }<br><br>    //按下傳送按鈕<br>    @IBAction func sendMessage(_ sender: UIButton) {<br>        //將輸入的訊息加進content陣列裡<br>        content.append(Content(name: .user, text: userMessageTextField.text ?? &quot;&quot;))<br>        //按下傳送按鈕後，抓取API資料<br>        APICaller.shared.fetchChatGPTAPI(prompt: userMessageTextField.text ?? &quot;&quot;)<br>        { [weak self]<br>            openAPIResponse<br>            in<br>            DispatchQueue.main.async<br>            {<br>                self?.openAPIResponse = openAPIResponse<br>                let choicesText = openAPIResponse.choices[0].text<br> //              print(choicesText)<br>                self?.content.append(Content(name: .chapgpt, text: choicesText))<br>                self?.tableView.reloadData() //更新資料<br>                //讓句子出現在最底層的對話中<br>                let contentCount = (self?.content.count ?? 1) - 1<br>                let indexPath = IndexPath(row: contentCount, section: 0)<br>                self?.tableView.scrollToRow(at: indexPath, at: .bottom, animated: true)<br>            }<br>            <br>        }<br>        userMessageTextField.text = &quot;&quot; //按下傳送按鈕後，textField輸入前先清空文字<br>        self.tableView.reloadData() //按下傳送按鈕，將傳入的文字更新table資料並顯示在畫面上<br>        view.endEditing(true) //按下傳送按鈕後退鍵盤<br>        //句子出現在最底層的對話中<br>        let indexPath = IndexPath(row: content.count-1, section: 0)<br>        self.tableView.scrollToRow(at: indexPath, at: .bottom, animated: true)<br>    }<br>    <br>}<br><br>//MARK: - TableView<br>extension ChatViewController:UITableViewDelegate,UITableViewDataSource<br>{<br>    <br>    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -&gt; Int {<br>        return content.count<br>    }<br>    <br>    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -&gt; UITableViewCell <br>    {<br><br>      let showContent = content[indexPath.row]<br>          if showContent.name == .chapgpt<br>          {<br>              let chatgptCell = tableView.dequeueReusableCell(withIdentifier: &quot;chatgptCell&quot;) as! ChatgptTableViewCell<br>//                print(showContent.name.rawValue)<br>              chatgptCell.chatgptTextView.text = showContent.text<br>              chatgptCell.chatgptLabel.text = showContent.name.rawValue<br>              chatgptCell.chatgptImageView.image = UIImage(named: &quot;chatgpt&quot;)<br>              chatgptCell.updateChatGPTUI()<br>              <br>              return chatgptCell<br>          }<br>          else<br>          {<br>              let userCell = tableView.dequeueReusableCell(withIdentifier: &quot;userCell&quot;) as! UserTableViewCell<br>//                print(showContent.name.rawValue)<br>              userCell.userLabel.text = showContent.name.rawValue<br>              userCell.userTextView?.text = showContent.text<br>              userCell.userImageView.image = UIImage(systemName: &quot;person.crop.circle&quot;)<br>              userCell.updateUserUI()<br>              return userCell<br>          }<br>    }<br>}</pre><p>2. when the keyboard covers the textField</p><p>I added the text field and button into a stack view and placed it at the bottom of the view. However, when the user types a message, the keyboard can cover the text field. To prevent this, I implemented a feature that moves the entire view up when keyboard appears, ensuring that the text field remains visible to the user.</p><p>I have defined a property called stackViewBottomConstraint that stores the bottom of a stack view position. This position will be adjusted upward when the keyboard appears.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/957/1*rxklwSSQr1hC1nvsMVdIHA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/956/1*Zid3KqQVdm4ip8u_wknnKQ.png" /><figcaption>stackViewBottomConstraint</figcaption></figure><p>I have also obtained two additional values: keyboardHeight, which represents the height of the keyboard, and keyboardTopY , which is the top position of the keyboard.</p><p>A property stackViewBottomY is to store the bottom position of the stack view, and bottomSpace is the remaining space below the stack view.</p><p>If the stackViewBottomY is greater than the keyboardTopY , it means that the stack view is currently being covered by the keyboard. To adjust for this, the stack view must be moved up by a distance equal to the keyboardHeight , to ensure that it remains visible and does not overlap with the keyboard.</p><p>To adjust the position of the stackViewBottomConstraint , I subtract a half of the bottomSpace value from it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/748/1*aLR1F1wRJ-CN82JrO-eweQ.png" /></figure><pre>import UIKit<br><br>class ChatViewController: UIViewController {<br><br>    @IBOutlet weak var userMessageTextField: UITextField!<br>    @IBOutlet weak var stackView: UIStackView!<br>    @IBOutlet weak var stackViewBottomConstraint: NSLayoutConstraint!<br>   <br>    override func viewDidLoad() {<br>        super.viewDidLoad()<br><br>        userMessageTextField.delegate = self<br>          <br>        setupKeyboard()<br>    }<br>    <br><br>    //鍵盤觀察器<br>   private func setupKeyboard()<br>   {<br>       NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: UIResponder.keyboardWillShowNotification, object: nil)<br>       NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name: UIResponder.keyboardWillHideNotification, object: nil)       <br>   }<br><br>    @objc func keyboardWillShow(notification:NSNotification)<br>    {<br>        //print(&quot;鍵盤彈出通知\(notification)&quot;)<br><br>        if let keyboardFrame = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] ?? 0) as? NSValue  <br>        {<br>            <br>            //取得鍵盤高度（CGFloat)<br>            let keyboardSize = keyboardFrame.cgRectValue<br>            let keyboardHeight = keyboardSize.height<br>        <br>            //鍵盤上方Y的位置<br>            let keyboardTopY =  self.view.frame.size.height - keyboardHeight    <br><br>            //stackView下方Y的位置<br>            let stackViewBottomY = stackView.frame.origin.y + stackView.frame.size.height<br>            <br>            //畫面最下方剩餘的高度<br>            let bottomSpace = self.view.frame.height - stackViewBottomY<br><br>            //假設要輸入的地方被鍵盤遮住(鍵盤位置高於輸入框)<br>            if keyboardTopY &lt; stackViewBottomY<br>            {<br>                stackViewBottomConstraint.constant = keyboardHeight - bottomSpace/2<br>            }<br>        }    <br>    }<br><br>    @objc func keyboardWillHide(){<br>      stackViewBottomConstraint.constant = 0<br>    }<br>}</pre><p>3. Dismiss the keyboard</p><p>The user can dismiss the keyboard by pressing the return button on the keyboard.</p><pre>//MARK: - TextField<br>extension ChatViewController:UITextFieldDelegate{<br>   <br>    func textFieldShouldReturn(_ textField: UITextField) -&gt; Bool {<br>        textField.resignFirstResponder() //return退鍵盤<br>    }    <br>}</pre><p>The keyboard can also be dismissed by touching the speech bubble.</p><pre>//按textView可以退鍵盤<br>    override func touchesBegan(_ touches: Set&lt;UITouch&gt;, with event: UIEvent?) {<br>        tableView.endEditing(true)<br>    }</pre><p><strong><em>Reference</em></strong></p><ul><li><a href="https://johncodeos.com/how-to-move-view-with-keyboard-in-ios-using-swift/">How to move View with Keyboard in iOS using Swift | John Codeos - Blog with Free iOS &amp; Android Development Tutorials</a></li><li><a href="https://medium.com/%E5%BD%BC%E5%BE%97%E6%BD%98%E7%9A%84-swift-ios-app-%E9%96%8B%E7%99%BC%E6%95%99%E5%AE%A4/episode-95-%E8%81%8A%E5%A4%A9%E5%AE%A4%E7%95%AB%E9%9D%A2-table-view-text-view-%E6%90%AD%E9%85%8D-autolayout-be346dc90f2f">Episode 95— 聊天室畫面：Table View &amp; Text View 搭配 AutoLayout</a></li></ul><p>There are several areas where further improvements can be made. For example, we could create a speech bubble as shown in the below attached image. Additionally, we could connect the Firebase API to store the message, allowing retrieval of chat data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/193/1*SMyMQuhNCfQX8iM_vjU8zQ.png" /><figcaption>speech bubble</figcaption></figure><p>Hopefully, I have expressed the content of the article clearly. I have asked for ChatGPT’s help in correcting the grammar of the article.😎</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/725/1*BAm_1ug-Cy1fqlDwpt6lYg.png" /><figcaption>Good Job ChatGPT!😆</figcaption></figure><p><strong>My GitHub</strong></p><p><a href="https://github.com/Huangjieru/ChatWithAI">GitHub - Huangjieru/ChatWithAI</a></p><p><strong>Reference</strong></p><p><em>Projects</em></p><ul><li><a href="https://medium.com/%E5%BD%BC%E5%BE%97%E6%BD%98%E7%9A%84%E8%A9%A6%E7%85%89-%E5%8B%87%E8%80%85%E7%9A%84-100-%E9%81%93-swift-ios-app-%E8%AC%8E%E9%A1%8C/63-%E6%83%85%E6%AD%8C%E5%B0%8D%E5%94%B1%E7%9A%84%E8%81%8A%E5%A4%A9%E5%AE%A4%E7%95%AB%E9%9D%A2-cell-%E7%9A%84-auto-layout-53697c2ad80c">#63 情歌對唱的聊天室畫面 —  cell 的 auto layout</a></li><li><a href="https://medium.com/%E5%BD%BC%E5%BE%97%E6%BD%98%E7%9A%84-swift-ios-app-%E9%96%8B%E7%99%BC%E6%95%99%E5%AE%A4/63-%E6%83%85%E6%AD%8C%E5%B0%8D%E5%94%B1%E7%9A%84%E8%81%8A%E5%A4%A9%E5%AE%A4%E7%95%AB%E9%9D%A2-can-you-feel-the-love-tonight-9c6270ad1ec4">#63 情歌對唱的聊天室畫面：Can You Feel The Love Tonight</a></li></ul><p><em>Access chatGPT’s openAPI</em></p><ul><li><a href="https://medium.com/%E5%BD%BC%E5%BE%97%E6%BD%98%E7%9A%84-swift-ios-app-%E9%96%8B%E7%99%BC%E6%95%99%E5%AE%A4/%E6%8A%8A-openai-chatgpt-%E6%90%AC%E5%88%B0-ios-%E4%B8%8A-148bc2b1221b">把 OpenAI 的 ChatGPT 搬到 iOS 上</a></li><li><a href="https://medium.com/%E5%BD%BC%E5%BE%97%E6%BD%98%E7%9A%84-swift-ios-app-%E9%96%8B%E7%99%BC%E5%95%8F%E9%A1%8C%E8%A7%A3%E7%AD%94%E9%9B%86/%E5%92%8C-openai-chatgpt-%E8%81%8A%E8%81%8A%E6%84%9B%E6%83%85%E7%A8%8B%E5%BC%8F-%E7%94%A8-swift-%E4%B8%B2%E6%8E%A5-openai-api-23fd69c55635">和 OpenAI ChatGPT 聊聊天 &amp; 用 Swift 串接 OpenAI API</a></li></ul><blockquote>Übung macht den Meister.</blockquote><p>→ Go to <a href="https://medium.com/@jieru04/chat-with-ai-part-2-dfd15e60ea54">Part 2</a>: log in /register &amp; take a photo/ choose a picture</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dafd50abd0a5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/peter-pan-swift-ios-class/swift-app-chat-with-ai-dafd50abd0a5">Swift App —  Chat with AI</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: Add, Edit, Delete — part3]]></title>
            <link>https://medium.com/peter-pan-swift-ios-class/swift-add-edit-delete-part3-6a0924075ca1?source=rss-7f58831db4fb------2</link>
            <guid isPermaLink="false">https://medium.com/p/6a0924075ca1</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[swift-programming]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Jru]]></dc:creator>
            <pubDate>Sat, 17 Dec 2022 14:29:46 GMT</pubDate>
            <atom:updated>2023-03-14T02:52:54.210Z</atom:updated>
            <content:encoded><![CDATA[<h3>Swift: Add, Edit, Delete — part3</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/494/1*3OttX91nmfsYSIpNh1XHPQ.png" /></figure><blockquote>App features</blockquote><p>part1:</p><ul><li>add, edit, delete content → to record items in document directory or UserDefaults</li><li><a href="https://medium.com/@jieru04/swift-add-edit-delete-part1-651f6a50499e">https://medium.com/@jieru04/swift-add-edit-delete-part1-651f6a50499e</a></li></ul><p>part2:</p><ul><li>choose photo with photo album/ take picture with camera → UIImagePickerController</li><li><a href="https://medium.com/@jieru04/swift-add-edit-delete-part2-d63b7fcc4cc0">https://medium.com/@jieru04/swift-add-edit-delete-part2-d63b7fcc4cc0</a></li></ul><p>part3:</p><ul><li>choose a store and comment → UIPickerView</li><li>pick date</li><li>dismiss keyboard</li></ul><h4>UIPickerView</h4><p>There are two place that I use UIPickerView : Store and Comment.</p><p>And also create a tool bar aboveUIPickerView that have Done button and cancel button on it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/296/1*rTKJFwmk2K9mDOiQlnfo4w.gif" /></figure><pre>class EditTableViewController: UITableViewController, UITextFieldDelegate {<br><br>      var pkvStore:UIPickerView!<br>      var pkvComment:UIPickerView!<br>    <br>      let storeArray = [&quot;&quot;,&quot;7-11&quot;,&quot;Family&quot;,&quot;Hi-Life&quot;,&quot;OK&quot;]<br>      let commentArray = [&quot;&quot;,&quot;🤩&quot;,&quot;😐&quot;,&quot;😥&quot;,&quot;🤔&quot;]<br><br>      @IBOutlet weak var storeTextField: UITextField!<br>      @IBOutlet weak var commentTextField: UITextField!<br><br>      override func viewDidLoad() {<br>            super.viewDidLoad()<br><br>            //顯示建立的滾輪<br>            createPickerView()<br>      }<br><br>      //建立的滾輪<br>      func createPickerView(){<br>        <br>         //滾輪上done,cancel按鈕設計另外寫在TextField檔案裡的setKeyboardButton()<br>        <br>        //選擇店家滾輪<br>        pkvStore = UIPickerView()<br>        pkvStore.delegate = self<br>        pkvStore.dataSource = self<br>        pkvStore.tag = 1 //此處的tag編碼與store在storyboard的textField的tag編碼相同<br>        //將輸入store欄位的鍵盤替換為滾輪 //inputView 是 text filed 輸入時從下方冒出的輸入區塊<br>        storeTextField.inputView = pkvStore  <br>        //滾輪上方加上done,cancel按鈕     <br>        storeTextField.setKeyboardButton()<br>        <br>        <br>        //選擇評論滾輪<br>        pkvComment = UIPickerView()<br>        pkvComment.delegate = self<br>        pkvComment.dataSource = self<br>        pkvComment.tag = 4<br>        commentTextField.inputView = pkvComment //鍵盤替換為滾輪<br>        commentTextField.setKeyboardButton() //滾輪上方加上done,cancel按鈕<br>        <br>    }<br>}</pre><p>tag is instance property and it can use to identify objects in the application by setting a value.</p><p><a href="https://developer.apple.com/documentation/uikit/uiview/1622493-tag">Apple Developer Documentation</a></p><p>To extend EditTableViewController functionality that conform UIPickerViewDelegate and UIPickerViewDataSource protocol.</p><pre>extension EditTableViewController:UIPickerViewDelegate,UIPickerViewDataSource{<br>    //有幾個滾輪<br>    func numberOfComponents(in pickerView: UIPickerView) -&gt; Int {<br>        return 1<br>    }<br>    //一個滾輪裡有幾行(row)<br>    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -&gt; Int {<br>        switch pickerView.tag{<br>        case 1:<br>            return storeArray.count<br>        case 4:<br>            return commentArray.count<br>        default:<br>            return 0 //隨便給值 因為不會飽到default段<br>        }<br>        <br>    }<br>    //滾輪裡顯示陣列資料<br>    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -&gt; String? {<br>        switch pickerView.tag{<br>        case 1:<br>            return storeArray[row]<br>        case 4:<br>            return commentArray[row]<br>        default:<br>            return &quot;Nothing&quot;<br>        }<br>        <br>    }<br>    //滾輪滾動到特定位置時TextField顯示該文字<br>    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {<br>        switch pickerView.tag{<br>        case 1:<br>            storeTextField.text = storeArray[row]<br>        case 4:<br>            commentTextField.text = commentArray[row]<br>        default:<br>            break<br>        }<br>        <br>    }<br> <br>}</pre><p><strong>Tool bar:</strong></p><ul><li>to extend UITextField functionality.</li><li>EditTableViewController have to conform UITextFieldDelegete protocol.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/328/1*X5JQuvqyb4_eiLtF4J6Kzw.png" /></figure><pre>import Foundation<br>import UIKit<br><br>extension UITextField{<br>    func setKeyboardButton(){<br>        //設計滾輪<br>        //初始化pickerView上方的toolBar<br>        let toolbar = UIToolbar()<br>        toolbar.sizeToFit()<br>        toolbar.barTintColor = .systemMint<br>        //透明<br>        //toolbar.isTranslucent = true<br>        let doneButton = UIBarButtonItem(barButtonSystemItem: .done, target: nil, action: #selector(doneButtonTap))<br>        let spaceButton = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)//彈性的拉開與cancel之間的距離<br>        let cancelButton = UIBarButtonItem(barButtonSystemItem: .cancel, target: nil, action: #selector(cancelButtonTap))<br>        //doneButton顏色<br>        doneButton.tintColor = .white<br>        //cancelButton顏色<br>        cancelButton.tintColor = .white<br>        //doneButton顯示在toolbar上<br>        toolbar.setItems([doneButton,spaceButton,cancelButton], animated: true)<br>        //inputAccessoryView 是輸入區塊上方的輔助區塊<br>        self.inputAccessoryView = toolbar<br><br>    }<br>  //按下按鈕後退選擇器<br>        @objc func doneButtonTap(){<br>            self.endEditing(true)<br>        }<br>        @objc func cancelButtonTap(){<br>            self.endEditing(true)<br>        }<br>}</pre><h4>DatePicker</h4><p>to create datePicker</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/296/1*WEmb2q6hRdf6FzR_R6cWLQ.gif" /></figure><pre>@IBOutlet weak var datePicker: UIDatePicker!<br><br> override func viewDidLoad() {<br>        super.viewDidLoad()<br><br>        //顯示日期選擇<br>        createDatePicker()<br>}<br><br>    //建立日期選擇器<br>    func createDatePicker(){<br>        <br>        //選擇日期時的呈現樣式<br>        datePicker.datePickerMode = .date<br>        datePicker.preferredDatePickerStyle = .compact<br>        <br>        datePicker.locale = .autoupdatingCurrent<br>        //預設為今天<br>        datePicker.date = .now<br>       <br>    }</pre><h4>Keyboard</h4><p>To show number of keyboard type.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/296/1*dQmwwsE0AMBnSEBksn_Bqw.gif" /></figure><pre>@IBOutlet weak var priceTextField: UITextField!<br><br> override func viewDidLoad() {<br>        super.viewDidLoad()<br><br>        //數字鍵盤及上方Tabbar<br>        priceTextField.keyboardType = .numberPad<br>        priceTextField.setKeyboardButton() // set toolbar above keyboard which can dismiss keyboard.<br>}<br><br><br></pre><p><strong>Dismiss keyboard</strong></p><p>There are three ways to dismiss keyboard.</p><ol><li>create <strong>tool bar </strong>and<strong> </strong>to set Done or Cancel button on above keyboard.</li><li>press “return” key on the keyboard.</li></ol><ul><li>to create IBAction and event chooseDid End On Exit .</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/296/1*ENc3JVhqC2DCkvPSPtqOeg.gif" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/290/1*ta7wKTDV8W8B5Sd3qIK8Gw.png" /></figure><pre>@IBAction func dismissItemKeyboard(_ sender: Any) {<br>    }</pre><p>3. to tap any place on the view to resign the keyboard.</p><pre>    override func viewDidLoad() {<br>        super.viewDidLoad()<br><br>      //點背景退鍵盤及PickerView<br>        dismissKeyboardFromBackground()<br>    }<br><br>    //點背景退鍵盤<br>    func dismissKeyboardFromBackground(){<br>        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(dismissKeyboard))<br>        //tapGesture.cancelsTouchesInView = false //如果有didSelectRowAt會造成衝突，有didSelectRowAt在把cancelsTouchesInView變成false即可<br>        tableView.addGestureRecognizer(tapGesture)<br>    }<br><br>    @objc func dismissKeyboard(){<br>        self.tableView.endEditing(true)<br>    }</pre><blockquote>Reference</blockquote><p>UIPickerView</p><ul><li><a href="https://medium.com/%E5%BD%BC%E5%BE%97%E6%BD%98%E7%9A%84-swift-ios-app-%E9%96%8B%E7%99%BC%E6%95%99%E5%AE%A4/how-to-use-uipickerview-in-swift-525d72aa513d">#How to use UIPickerView in Swift</a></li><li><a href="https://medium.com/%E5%BD%BC%E5%BE%97%E6%BD%98%E7%9A%84-swift-ios-app-%E9%96%8B%E7%99%BC%E6%95%99%E5%AE%A4/pickerview%E7%B7%B4%E7%BF%92-eb5309ae21d0">PickerView練習</a></li></ul><p>Dismiss Keyboard</p><ul><li><a href="https://medium.com/%E5%BD%BC%E5%BE%97%E6%BD%98%E7%9A%84-swift-ios-app-%E9%96%8B%E7%99%BC%E6%95%99%E5%AE%A4/dismiss-the-numberpad-keyboard-type-62d0bbec5a25">Dismiss the numberPad keyboard Type</a></li><li><a href="https://medium.com/%E5%BD%BC%E5%BE%97%E6%BD%98%E7%9A%84-swift-ios-app-%E9%96%8B%E7%99%BC%E5%95%8F%E9%A1%8C%E8%A7%A3%E7%AD%94%E9%9B%86/uitextfield-%E9%BB%9E%E9%81%B8-return-%E9%8D%B5%E6%94%B6%E9%8D%B5%E7%9B%A4%E7%9A%84%E6%96%B9%E6%B3%95-f99769370d46">UITextField 點選 return 鍵收鍵盤的方法</a></li><li><a href="https://medium.com/%E5%BD%BC%E5%BE%97%E6%BD%98%E7%9A%84-swift-ios-app-%E9%96%8B%E7%99%BC%E6%95%99%E5%AE%A4/swift-keyboard-%E9%8D%B5%E7%9B%A4%E5%B0%8F%E4%BA%8B%E6%83%85-a4b2a16c87d1">Swift KeyBoard 鍵盤小事情</a></li><li><a href="https://juejin.cn/post/6844904113407262734">iOS 触控事件 UITouch 和手势识别 UIGestureRecognizer</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6a0924075ca1" width="1" height="1" alt=""><hr><p><a href="https://medium.com/peter-pan-swift-ios-class/swift-add-edit-delete-part3-6a0924075ca1">Swift: Add, Edit, Delete — part3</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>