<?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 CY’s Programming Journey on Medium]]></title>
        <description><![CDATA[Stories by CY’s Programming Journey on Medium]]></description>
        <link>https://medium.com/@chiayenlin_31230?source=rss-b5b0c3dc8e10------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*B6rgVxpkkviMAa6ALBqG_w@2x.jpeg</url>
            <title>Stories by CY’s Programming Journey on Medium</title>
            <link>https://medium.com/@chiayenlin_31230?source=rss-b5b0c3dc8e10------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 14:43:19 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@chiayenlin_31230/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[#43 Drinks Order APP 訂飲料 − Part 2]]></title>
            <link>https://medium.com/peter-pan-swift-ios-class/43-drinks-order-app-%E8%A8%82%E9%A3%B2%E6%96%99-part-2-bd84b1f98234?source=rss-b5b0c3dc8e10------2</link>
            <guid isPermaLink="false">https://medium.com/p/bd84b1f98234</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[api]]></category>
            <dc:creator><![CDATA[CY’s Programming Journey]]></dc:creator>
            <pubDate>Fri, 23 Jun 2023 08:45:51 GMT</pubDate>
            <atom:updated>2023-07-06T06:46:28.190Z</atom:updated>
            <content:encoded><![CDATA[<h4>with AirTable API</h4><p><strong><em>繼上一篇 Drinks Order APP 訂飲料 − Part 1</em></strong></p><p><a href="https://medium.com/@chiayenlin_31230/42-drinks-order-app-%E8%A8%82%E9%A3%B2%E6%96%99-part-1-fb4d8fc392dd">#42 Drinks Order APP 訂飲料 − Part 1</a></p><p><strong><em>本篇將介紹：</em></strong></p><blockquote><strong>選擇甜度時，使用 Picker View 搭配 Tool Bar</strong></blockquote><blockquote><strong>利用 sheetPresentationController</strong> <strong>顯示特定高度的 Topping Table View Controller</strong></blockquote><blockquote><strong>輸入備註欄位時，讓畫面自動向上捲動，防止鍵盤遮住 Text Field</strong></blockquote><blockquote><strong>確認訂單後利用 navigation controller 返回 menu</strong></blockquote><blockquote><strong>透過 AirTable 串接 Rest API，包含上傳新訂單(API POST)，讀取訂單(API GET)，刪除訂單(API DELETE)</strong></blockquote><blockquote><strong>選擇甜度時，使用 Picker View 搭配 Tool Bar</strong></blockquote><p>當點選 Text Field 時，把原本應該出現的鍵盤，變成 Picker View 搭配 Tool Bar 可以取消與選擇。</p><p>首先把 Picker View 跟 Tool Bar 加入要顯示的 controller 的 Exit 下面， Tool Bar 裡可以加入其他 Bar Button Item 以及用 Fixed Space Bar Button Item 隔開。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/261/1*OfMIXcagfJ2NfGjbhmwrDQ.png" /></figure><p>之後在 controller 上面會多出 Picker View 跟 Tool Bar</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pF5v8V783sZW1cSG_87eqA.png" /></figure><p>之後把 Picker View 、Tool Bar 拉好 IBOutlet，兩個 Bar Button Item 拉好 IBAction，就可以從程式控制它們了</p><p>記得讓 Order View Controller 當 Picker View 的 dataSource 跟 delegate</p><p>在 viewDidLoad 裡輸入下面兩行，讓點選 sugarLevel Text Field 時，本來會出現的鍵盤被 Picler View 跟 Tool Bar取代</p><pre>        sugarLevel.inputView = pickerView<br>        sugarLevel.inputAccessoryView = toolBar</pre><p>接下來，用 UIPickerViewDataSource 決定 Picker View 呈現出來得樣子</p><pre>extension OrderViewController: UIPickerViewDataSource {<br>    func numberOfComponents(in pickerView: UIPickerView) -&gt; Int {<br>        1<br>    }<br>    <br>    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -&gt; Int {<br>        sugarLevels.count<br>    }<br>}</pre><p>用 UIPickerViewDelegate 裡的 <strong>function pickerView titleForRow</strong> 設定點選時的功能</p><pre>extension OrderViewController: UIPickerViewDelegate {<br>    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -&gt; String? {<br>        sugarLevels[row].rawValue<br>    }<br>}</pre><p>點選 sugar Text Field 時顯示 Picker View</p><pre>    @IBAction func sugarTextField(_ sender: Any) {<br>        view.becomeFirstResponder()<br>    }</pre><p>兩個 Bar Button Item，分別顯示 Cancel 跟 Done，<br>點 Cancel 時利用 view.editing(true) 收回 Picker View；<br>點 Done 時讓 sugarLevel Text Field 顯示選取的選項</p><pre>    //tap Cancel button to dismiss picker view<br>    @IBAction func pressCancel(_ sender: Any) {<br>        view.endEditing(true)<br>    }<br>    //tap Done button to show the selection on sugarLevel Text Field and dismiss picker view<br>    @IBAction func pressDone(_ sender: Any) {<br>        let row = pickerView.selectedRow(inComponent: 0)<br>        sugarLevel.text = sugarLevels[row]<br>        view.endEditing(true)<br>    }</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*KEvOwpH40QsH3qIkqoDQjg.gif" /></figure><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/97-uipickerview-%E7%B7%B4%E7%BF%92-42d71c5e298c">#97 UIPickerView 練習</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/37-%E9%9A%A8%E6%A9%9F%E5%9C%96%E7%89%87api-%E9%80%B2%E9%9A%8E%E7%89%88uipickervier-c990b5ed2309">#37 隨機圖片API ＆進階版 UIPickerVier</a></li></ul><blockquote><strong>選擇配料時，顯示特定高度的 table view</strong></blockquote><p>當選擇配料時，要顯示<strong>自訂高度</strong>的 ToppingTableViewController 也是用到 <strong>sheetPresentationController</strong>，只是高度是選擇<strong> .custom </strong>就可以自訂想要的高度，這裡是設定 300</p><pre>    @IBSegueAction func showTopping(_ coder: NSCoder) -&gt; ToppingTableViewController? {<br>        let controller = ToppingTableViewController(coder: coder)<br>        if let sheetPresentationController = controller?.sheetPresentationController {<br>            sheetPresentationController.detents = [.custom(resolver: { _ in<br>                300<br>            })]<br>        }<br>        return controller<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/ios-15-%E7%8C%B6%E6%8A%B1%E7%90%B5%E7%90%B6%E5%8D%8A%E9%81%AE%E9%9D%A2-%E9%A1%AF%E7%A4%BA%E4%B8%80%E5%8D%8A%E7%9A%84-sheet-%E7%95%AB%E9%9D%A2-b13448a76cb0">只顯示部分高度的 sheet 畫面</a></p><p>顯示的配料可以不選，但最多只能選兩樣，將會被儲存到 selectedToppings array，注意在取消已選取的配料時，同時<strong>移除</strong> selectedToppings array 項目，會需要用到 array 的 function <strong>.firstIndex(where: ) </strong>找到在 selectedToppings array 裡的 index，之後就可以刪除該項目。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/375/1*-_ITpksQ8xvGZ81OzHqEXg.png" /></figure><p>程式碼會寫在 func tableView <strong>didSelectedRowAt</strong> 裡，同時每次點選就會改變topping check 的 Bool 值</p><pre>        let row = indexPath.row<br>        //add toppings<br>        if selectedToppings.count &lt; 2, toppings[row].check == false {<br>            <br>            toppings[row].check = true<br>            selectedToppings.append(toppings[row])<br>            <br>            //remove topping<br>        } else if toppings[row].check == true {<br>            <br>            toppings[row].check = false<br>            let name = toppings[row].toppingName<br>            <br>            //finding the index of the same topping<br>            if let index = selectedToppings.firstIndex(where: {<br>                $0.toppingName.contains(name) }) {<br>                selectedToppings.remove(at: index)<br>            }<br>        }<br>        <br>        tableView.reloadData()</pre><p>最後，也要把資料傳回前一頁，在前一頁要顯示已選取的配料以及讀取改變 check Bool 值的 toppings ，使再次進入配料選單時顯示已選取的項目，看起來更自然些。</p><pre>        let name = Notification.Name(&quot;topping changed&quot;)<br>        NotificationCenter.default.post(name: name, object: nil, userInfo: [<br>            &quot;selectedToppings&quot; : selectedToppings,<br>            &quot;toppings&quot;: toppings<br>        ])</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*IIP1k8Bq04MSKGXzx3KyEQ.gif" /></figure><p><a href="https://www.tutorialspoint.com/how-to-find-the-index-of-a-list-item-in-swift">How to find the index of a list item in Swift</a></p><blockquote><strong>輸入備註欄位時，讓畫面自動向上捲動，防止鍵盤遮住 Text Field</strong></blockquote><p>要做到鍵盤出現時畫面自動上移，避免遮住 Text Field 的功能，需要用到 <strong>scroll view</strong> 及其<strong>屬性 contentInset</strong>，contentInset 可在 scroll view 的四個邊與其他元件之間增加距離，而距離也可以自訂。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/744/1*hpwCY6euzWamlq6AHkudbg.png" /></figure><p>搭配用 NotificationCenter 接收每次<strong>鍵盤出現</strong>(包含鍵盤尺寸訊息)以及<strong>消失</strong>時在程式裡<strong>發出的訊息</strong>，就能知道何時畫面該向上推移以及回復原位</p><pre>    func registerForKeyboardNotifications() {<br>        NotificationCenter.default.addObserver(self,selector: #selector(keyboardWasShown(_:)),name: UIResponder.keyboardDidShowNotification,object: nil)<br>        NotificationCenter.default.addObserver(self,selector: #selector(keyboardWillBeHidden(_:)),name: UIResponder.keyboardWillHideNotification,object: nil)<br>    }<br>    <br>    @objc func keyboardWasShown(_ notificiation: NSNotification) {<br>        guard let info = notificiation.userInfo,<br>              let keyboardFrameValue = info[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue else { return }<br><br>        let keyboardFrame = keyboardFrameValue.cgRectValue<br>        let keyboardSize = keyboardFrame.size<br>        <br>        let movingDistance = keyboardSize.height-(view.frame.size.height-scrollView.frame.maxY)<br>        <br>        scrollView.contentInset = UIEdgeInsets(top: 0.0, left: 0.0, bottom: movingDistance, right: 0.0)<br>    }<br>    <br>    @objc func keyboardWillBeHidden(_ notification: NSNotification) {<br>        scrollView.contentInset = UIEdgeInsets.zero<br>    }</pre><p>先算出要推移的距離，存入常數 movingDistance</p><pre> let keyboardFrame = keyboardFrameValue.cgRectValue<br> let keyboardSize = keyboardFrame.size<br>        <br> let movingDistance = keyboardSize.height-(view.frame.size.height-scrollView.frame.maxY)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*DPIKnchroylYsuTlpcDdmQ.gif" /></figure><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-contentinset-%E8%AE%93%E9%8D%B5%E7%9B%A4%E5%87%BA%E7%8F%BE%E6%99%82-scroll-view-%E8%87%AA%E5%8B%95%E4%B8%8A%E7%A7%BB-687ab82990f7">利用 contentInset 讓鍵盤出現時 scroll view 自動上移</a></p><blockquote><strong>透過 AirTable 串接 Rest API，包含上傳新訂單(API POST)，讀取訂單(API GET)，刪除訂單(API DELETE)</strong></blockquote><p>這裡一樣<strong><em>參考 Apple 官方範例，</em></strong>利用<strong><em> Result type </em></strong>來串接 Rest API。</p><p>新增一個 class OrderController，裡面定義 static var shared 方便在別的 controller 也能呼叫。把<strong>上傳新訂單(API POST)，讀取訂單(API GET)，刪除訂單(API DELETE) </strong>都寫成function。</p><pre>class OrderController {<br>    <br>    static let shared = OrderController()<br>    <br>    private let apiValue = &quot;Bearer key12345678R&quot;<br>    <br>    func fetchOrderList(comletion: @escaping (Result&lt;[OrderRecord], Error&gt;) -&gt; Void) {<br>        <br>        guard let url = URL(string: &quot;https://api.airtable.com/v0/appBBoJvZRrxzj09q/Order?sort[][field]=time&amp;sort[][direction]=desc&quot;) else {return}<br>        var request = URLRequest(url: url)<br>        <br>        request.httpMethod = &quot;GET&quot;<br>        request.setValue(apiValue, forHTTPHeaderField: &quot;Authorization&quot;)<br>        <br>        URLSession.shared.dataTask(with: request) { data, response, error in<br>            <br>            if let error {<br>                comletion(.failure(error))<br>            } else if let data {<br>                do {<br>                    let decoder = JSONDecoder()<br>                    let getOrder = try decoder.decode(GetOrder.self, from: data)<br>                    comletion(.success(getOrder.records))<br>                } catch {<br>                    comletion(.failure(error))<br>                }<br>            }<br>        }.resume()<br>    }<br>    <br>    func postOrder(createOrder: CreateOrder.Record, completion: @escaping (Result&lt;Response, Error&gt;) -&gt; Void) {<br>        <br>        guard let url = URL(string: &quot;https://api.airtable.com/v0/appBBoJvZRrxzj09q/Order&quot;) else {return}<br>        var request = URLRequest(url: url)<br>        <br>        request.httpMethod = &quot;POST&quot;<br>        request.setValue(&quot;application/json&quot;, forHTTPHeaderField: &quot;Content-Type&quot;) <br>        request.setValue(apiValue, forHTTPHeaderField: &quot;Authorization&quot;) <br>        <br>        let newOrder = createOrder<br>        <br>        let encoder = JSONEncoder()<br>    <br>        request.httpBody = try? encoder.encode(newOrder)<br>        <br>        URLSession.shared.dataTask(with: request) { data, response, error in<br>            <br>            if let error {<br>                completion(.failure(error))<br>            } else if let data {<br>                do {<br>                    let decoder = JSONDecoder()<br>                    let response = try decoder.decode(Response.self, from: data)<br>                    completion(.success(response))<br>                } catch {<br>                    completion(.failure(error))<br>                }<br>            }<br>        }.resume()<br>    }<br>    <br>    func deleteOrder(deleteID: String) {<br>        <br>        guard let url = URL(string: &quot;https://api.airtable.com/v0/appBBoJvZRrxzj09q/Order/\(deleteID)&quot;) else {return}<br>        var request = URLRequest(url: url)<br>        <br>        request.httpMethod = &quot;DELETE&quot;<br>        request.setValue(apiValue, forHTTPHeaderField: &quot;Authorization&quot;)<br>        <br>        URLSession.shared.dataTask(with: request) { data, response, error in<br>            if let httpResponse = response as? HTTPURLResponse {<br>                print(&quot;🟡httpResponse.statusCode&quot;, httpResponse.statusCode)<br>            }<br>            if let data {<br>                print(&quot;🟢content&quot;,String(data: data, encoding: .utf8)!)<br>            }<br>        }.resume()<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/%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><p><strong><em>· 新增訂單</em></strong></p><p>呼叫 OrderController.shared.postOrder</p><pre>       OrderController.shared.postOrder(createOrder: createOderContent) { result in<br>           switch result {<br>           case .success(let response):<br>               print(response)<br>           case .failure(let error):<br>               print(error)<br>          }<br>      }</pre><p>最後，當完成新訂單時，希望頁面<strong>自動返回 menu 頁面</strong>，頁面前有加入 n<strong>avigation controller</strong> 所以可用 <strong>popToRootViewController</strong> 返回</p><pre>self.navigationController?.popToRootViewController(animated: true)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_cY2rB1G0x2BkzNJCDhGnQ.gif" /><figcaption>create order</figcaption></figure><p><strong><em>· 讀取訂單</em></strong></p><p>可以先清空資料，然後呼叫 OrderController.shared.fetchOrderList</p><pre>    func renewDate() {<br>        <br>        //empty orderRecords and table view first<br>        self.orderRecords = []<br>        self.tableView.reloadData()<br>       <br>        OrderController.shared.fetchOrderList { result in<br>            <br>            switch result {<br>            case .success(let orderRecords):<br>                self.orderRecords = orderRecords<br>                DispatchQueue.main.async {<br>                    self.tableView.reloadData()<br>                }<br>            case .failure(let error):<br>                print(error)<br>            }<br>        }<br>    }</pre><p>顯示在 Order List Table View Controller 裡</p><pre>    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -&gt; Int {<br>        // #warning Incomplete implementation, return the number of rows<br>        orderRecords.count<br>    }<br>    <br>    fileprivate func configuration(_ cell: OrderListTableViewCell) {<br>        cell.frameImageView.layer.cornerRadius = 10<br>        cell.frameImageView.layer.borderWidth = 4<br>        cell.frameImageView.layer.borderColor = CGColor(red: 147/255, green: 189/255, blue: 197/255, alpha: 1)<br>    }<br>    <br>    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -&gt; UITableViewCell {<br>        guard let cell = tableView.dequeueReusableCell(withIdentifier: &quot;\(OrderListTableViewCell.self)&quot;, for: indexPath) as? OrderListTableViewCell else {<br>            fatalError(&quot;dequeueReusableCell OrderListTableViewCell failed&quot;)<br>        }<br>        <br>        let row = indexPath.row<br>        <br>        cell.nameLabel.text = &quot;#\(row+1) &quot;+orderRecords[row].fields.name<br>        cell.toppingLabel.text = orderRecords[row].fields.toppings<br>        cell.sizeLabel.text = orderRecords[row].fields.size+&quot; x &quot;+orderRecords[row].fields.quantity.description<br>        cell.iceLevelLabel.text = orderRecords[row].fields.iceLevel<br>        cell.sugarLavelLabel.text = orderRecords[row].fields.sugarLevel<br>        cell.noteLabel.text = orderRecords[row].fields.note<br>        cell.timeLabel.text = orderRecords[row].fields.time<br>        <br>        configuration(cell)<br>        <br>        return cell<br>    }</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*DrSYFTB7ARbKXi_NABBOrg.gif" /></figure><p><strong><em>· 刪除訂單</em></strong></p><p>呼叫 OrderController.shared.deleteOrder</p><p>寫進刪除表格的 func tableView commit editingStyle ，原本的 array 也要移除該筆資料、表格要更新</p><pre>override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {<br>        <br>    let id = orderRecords[indexPath.row].id<br>        <br>    OrderController.shared.deleteOrder(deleteID: id)<br>        <br>    orderRecords.remove(at: indexPath.row)<br>        <br>    tableView.deleteRows(at: [indexPath], with: .automatic)<br>        <br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0wo291EmJSQ2WlyxEa79Wg.gif" /><figcaption>delete order</figcaption></figure><p><strong>GitHub：</strong></p><p><a href="https://github.com/Ryan-CY/OrderDrink">GitHub - Ryan-CY/OrderDrink: Rest API (GET, POST, DELET) Practice</a></p><p><strong>Reference ：</strong></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/%E4%BD%A0%E5%87%BA%E5%8A%9B%E5%AF%AB-app-%E6%88%91%E5%87%BA%E9%8C%A2%E8%AB%8B%E9%A3%B2%E6%96%99-6a9ac14a2a22">#20 訂飲料 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/29-%E9%A3%B2%E6%96%99app-%E4%BE%86%E6%9D%AF%E4%BA%94%E6%A1%90%E8%99%9F%E5%90%A7-9c47e3b72660">#29 飲料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/%E8%A8%82%E9%A3%B2%E6%96%99app-%E5%8F%AF%E4%B8%8D%E5%8F%AF-976c3b8c13bf">訂飲料App｜可不可｜</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bd84b1f98234" width="1" height="1" alt=""><hr><p><a href="https://medium.com/peter-pan-swift-ios-class/43-drinks-order-app-%E8%A8%82%E9%A3%B2%E6%96%99-part-2-bd84b1f98234">#43 Drinks Order APP 訂飲料 − Part 2</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[#42 Drinks Order APP 訂飲料 − Part 1]]></title>
            <link>https://medium.com/peter-pan-swift-ios-class/42-drinks-order-app-%E8%A8%82%E9%A3%B2%E6%96%99-part-1-fb4d8fc392dd?source=rss-b5b0c3dc8e10------2</link>
            <guid isPermaLink="false">https://medium.com/p/fb4d8fc392dd</guid>
            <category><![CDATA[api]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[CY’s Programming Journey]]></dc:creator>
            <pubDate>Fri, 23 Jun 2023 08:31:56 GMT</pubDate>
            <atom:updated>2023-07-06T06:40:26.008Z</atom:updated>
            <content:encoded><![CDATA[<h4>with AirTable API</h4><h4>APP 功能部分：</h4><p>🌟 登入時顯示完整 menu</p><p>🌟 可以點選飲料類別，僅顯示該類別的商品</p><p>🌟 可輸入關鍵字查詢特定商品名稱，顯示符合的商品</p><p>🌟訂購畫面可以調整甜度、冰塊、配料、大小、數量以及輸入備註</p><p>🌟 按下訂購按鈕後，顯示確認視窗，選擇返回或是上傳訂單</p><p>🌟 可查看已訂購訂單頁面，可刪除訂單</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1-4F85I-_zu87zwlWQBIPg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zJFKhYX5jdpHlbrc4lf91g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LqNzVtixxoN3krwIH1BVFw.png" /></figure><h4>Demo：</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*firBDpRunFS6fn4H4kNORg.gif" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*GTi37X1mwZ_1q-fb6qHD1Q.gif" /><figcaption>Left: create order; Right: delete order</figcaption></figure><p><strong><em>本篇將介紹：</em></strong></p><blockquote><strong>在 AirTable 建立menu，以及訂單，共兩份表單</strong></blockquote><blockquote><strong>透過 AirTable 產生 API，閱讀 API 文件</strong></blockquote><blockquote><strong>參考 Apple 官方範例，利用 Result type 串接 Rest API</strong></blockquote><blockquote><strong>使用 segue 切換下一頁畫面及 prepare 傳資料到下一頁</strong></blockquote><blockquote><strong>利用 sheetPresentationController</strong> <strong>顯示一半高度的 Category table view controller</strong></blockquote><blockquote><strong>使用 NotificationCenter 傳送出資料訊息以及在上一頁接收資料</strong></blockquote><blockquote><strong>利用 dismiss 返回上一頁</strong></blockquote><blockquote><strong>在 AirTable 建立 menu 跟 order 列表</strong></blockquote><p>menu 的來源是參考新加坡當地的手搖品牌 <em>LiHo</em>(發音像福建話的你好)</p><p><a href="https://tommybenton.com/liho-menu/">LiHO Tea Menu &amp; Pricelist in Singapore Update 2023</a></p><p>在 AirTable 新增一個登入帳戶，一步步的建立資料，一開始有點困惑，當建立好訂單列表的項目時，但還沒有內容，這樣就好了嗎？<br>是的，訂單列表起初就只有項目，也就完成了。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*309vI2vqsvTewL5FJ151yg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I82D2tP_nNflwvcEmOIq8w.png" /><figcaption>menu and order lists in AirTable</figcaption></figure><blockquote><strong>透過 AirTable 產生 API，閱讀 API 文件</strong></blockquote><p>建立好資料後，還需要取得API Key 跟閱讀 API 文件，點選右上角的帳戶圖示，然後選擇 Developer hub</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4qXGj5mJJK_wbz9gEgcByA.png" /></figure><p>然後取的專屬的 token 或是 API key。之後點選 Web API documentation 進入 API 文件的說明頁面</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GkurI_-ltO_uSgReQP3krw.png" /></figure><p>在頁面下方可以看到現有已建立的資料</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iIonLWWd0A9ZZDsAhyYJpg.png" /></figure><p>點選後就會出現 API 文件的說明頁面，在左邊可以看到之前建立好的列表名稱 menu 跟 order，它們下面的子項目分別說明應用在 API method 上 request 的使用方式。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y3noGvbCpe6hyXnNMA7ctQ.png" /></figure><p>耐心閱讀資料，知道如何使用就可以進入程式的部分了。</p><p>reference:</p><p><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/135-%E5%88%A9%E7%94%A8-airtable-%E9%96%8B%E7%99%BC-ios-app-%E6%AF%94%E6%96%B9%E9%9B%BB%E5%BD%B1-app-db88fc3bf6c2">#135 利用 Airtable 開發 iOS App，比方電影 App</a></p><blockquote><strong>參考 Apple 官方範例，利用 Result type 串接 Rest API</strong></blockquote><p>會用到 Result type 的寫法，例如當使用到 try? 時，若執行結果有錯誤發生，則會變成 nil，不會回傳 error ，自然也不知道原因；因此 Apple 在 “ Develop in Swift Data Collections 12 ” 裡使用了 Result type 的寫法，為的就是請求無法被滿足時，還能回傳錯誤。</p><p>Result type，是 Apple 寫好的 enum，包含兩個 case ：.success(Success) 跟 .failure(Failure)，當我們在定義Result時，它的 associated value 會用到 generic。</p><p><a href="https://developer.apple.com/documentation/swift/result">Result | Apple Developer Documentation</a></p><p>取得在 AirTable 上的 menu，</p><p>建立 Class MenuController 讀取資料及上傳資料到 AirTable，裡面定義 static var shared 方便在別的 controller 也能呼叫。</p><pre>class MenuController {<br>    <br>    static let shared = MenuController()<br>    private let apiValue = &quot;Bearer 12345678R&quot;<br>    <br>    func fetchMenu(urlString: String, completion: @escaping (Result&lt;[Record], Error&gt;) -&gt; Void) {<br>        <br>        guard let url = URL(string: urlString) else {return}<br>        <br>        var request = URLRequest(url: url)<br>        request.setValue(apiValue, forHTTPHeaderField: &quot;Authorization&quot;)<br>        URLSession.shared.dataTask(with: request) { data, response, error in<br>            if let error {<br>                completion(.failure(error))<br>            } else if let data {<br>                let decoder = JSONDecoder()<br>                do {<br>                    let getMenu = try decoder.decode(GetMenu.self, from: data)<br>                    completion(.success(getMenu.records))<br>                } catch {<br>                    completion(.failure(error))<br>                }<br>            }<br>        }.resume()<br>    }<br>    <br>    enum MenuItemError: Error, LocalizedError {<br>        case imageDataMissing<br>    }<br>    <br>    func fetchImage(url: URL, completion: @escaping (Result&lt;UIImage, Error&gt;) -&gt; Void) {<br>        URLSession.shared.dataTask(with: url) { data, response, error in<br>            if let error {<br>                completion(.failure(error))<br>            } else if let data,<br>                      let photo = UIImage(data: data) {<br>                completion(.success(photo))<br>            } else {<br>                completion(.failure(MenuItemError.imageDataMissing))<br>            }<br>        }.resume()<br>    }<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/%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><p>這裡得做法是呈現在 view controller 裡的 collection view</p><p>在 view controller 裡，呼叫 MenuController 的 fetchMenu function，一開始顯示所有商品</p><pre>    var records = [Record]()<br>    var presentItems = [Record]()<br>    var categories = [&quot;All Products&quot;]<br>    var urlString = &quot;https://api.airtable.com/v0/appBBoJvZRrxzj09q/Menu?sort%5B0%5D%5Bfield%5D=category&amp;sort%5B0%5D%5Bdirection%5D=desc&quot;<br>    <br>    func update(records: [Record]) {<br>        self.records = records<br>        presentItems = records<br>        collectionView.reloadData()<br>        getCategory()<br>    }<br>    <br>    func initializeUI() {<br>        MenuController.shared.fetchMenu(urlString: urlString) { result in<br>            <br>            switch result {<br>            case .success(let records):<br>                DispatchQueue.main.async {<br>                    self.update(records: records)<br>                }<br>            case .failure(let error):<br>                print(error)<br>            }<br>        }<br>    }</pre><p>view controller 裡，用 collection view 呈現出商品</p><pre>extension MenuViewController: UICollectionViewDataSource {<br>    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -&gt; Int {<br>        presentItems.count<br>    }<br>    <br>    fileprivate func configuration(_ cell: MenuCollectionViewCell) {<br>        cell.activityIndicator.hidesWhenStopped = true<br>        cell.activityIndicator.startAnimating()<br>        <br>        cell.itemPhoto.image = nil //clear images<br>        <br>        cell.frameImageView.layer.cornerRadius = 10<br>        cell.frameImageView.layer.borderWidth = 4<br>        cell.frameImageView.layer.borderColor = CGColor(red: 147/255, green: 189/255, blue: 197/255, alpha: 1)<br>    }<br>    <br>    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -&gt; UICollectionViewCell {<br>        <br>        guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: &quot;\(MenuCollectionViewCell.self)&quot;, for: indexPath) as? MenuCollectionViewCell else {fatalError(&quot;dequeueReusableCell MenuCollectionViewCell failed&quot;)}<br>        <br>        configuration(cell)<br>        <br>        let presentItem = presentItems[indexPath.row]<br>        <br>        cell.itemName.text = presentItem.fields.name<br>        cell.itemPrice.text = &quot;\(presentItem.fields.price)&quot;<br>        <br>        if let imageURL = presentItem.fields.image.first?.url {<br>            <br>            MenuController.shared.fetchImage(url: imageURL) {[weak self] result in<br>                guard let self else {return}<br>                <br>                switch result {<br>                case .success(let photo):<br>                    DispatchQueue.main.async {<br>                        cell.itemPhoto.image = photo<br>                        cell.activityIndicator.stopAnimating()<br>                    }<br>                    <br>                case .failure(let failure):<br>                    print(failure)<br>                }<br>            }<br>        }<br>        return cell<br>    }<br>}</pre><p>在擷取影像(fetchImage)的部分，利用 <strong><em>capture list</em></strong> 搭配 <strong>weak</strong> ，在 closure 裡的開頭加入 <strong>[weak self]</strong> ，若是 view controller 消失時，一併停止取得影像，<strong>減少不必要的記憶體使用</strong>。這裡的 self 代表所在的 view controller。</p><p>之後在搭配 <strong>Search Bar</strong> 跟 <strong>Categories</strong> 就可以<strong>篩選想要呈現的商品</strong></p><h4>Search Bar − 搜尋特定商品</h4><p>先讓 MenuViewController 當 search Bar 的 delegate，用到 Search bar delegate 的func searchBar(UISearchBar, textDidChange: String)</p><p>裡面搭配 for-in 跟 if，把符合名稱的商品存入 presentItems 裡，重新呈現出來。</p><pre>extension MenuViewController: UISearchBarDelegate {<br>    func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {<br>        presentItems = []<br>        collectionView.reloadData()<br>        <br>        if searchText.isEmpty == true {<br>            presentItems = records<br>            categoryButton.setTitle(&quot;All Products&quot;, for: .normal)<br>        } else {<br>            categoryButton.setTitle(&quot;Filtered&quot;, for: .normal)<br>            <br>            for record in records {<br>                if record.fields.name.lowercased().contains(searchText.lowercased()) {<br>                    presentItems.append(record)<br>                }<br>            }<br>        }<br>        collectionView.reloadData()<br>        <br>    }<br>    //tap return to dismiss keyboard<br>    func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {<br>        view.endEditing(true)<br>    }<br>    <br>    //tap view to dismiss keyboatrd<br>    override func touchesEnded(_ touches: Set&lt;UITouch&gt;, with event: UIEvent?) {<br>        view.endEditing(true)<br>    }<br>}</pre><ul><li><a href="https://developer.apple.com/documentation/uikit/uisearchbardelegate">UISearchBarDelegate | Apple Developer Documentation</a></li><li><a href="https://www.hangge.com/blog/cache/detail_562.html">Swift - 搜索条（UISearchBar）的用法</a></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*b-9Msa3n4RO1ZvvluAyf9Q.gif" /></figure><blockquote><strong>使用 segue 切換下一頁畫面及 prepare 傳資料到下一頁</strong></blockquote><p>先在 MenuViewController 建立一個 function，裡面用 for-in 把所有商品的類別組成一個array</p><pre>func getCategory() {<br>        for record in records {<br>            let category = record.fields.category.first!<br>            if categories.contains(category) == false {<br>                categories.append(category)<br>            }<br>        }<br>        print(categories)<br>    }</pre><p>印出會得到這樣得結果</p><p><strong>[“All Products”, “Cheezho”, “MiLK TEA”, “Brew Tea”, “Red Bull”, “FRUiTEA”, “Choco / Coffe”, “FRESH MiLK TEA / OAT MiLK TEA”, “Superhei-ro Unite”]</strong></p><p>現在要傳遞得資料有了</p><p>定義一個 table view controller 型別為 CategoryTableViewController，目的是顯示所有商品的類別。在上一頁新增按鈕用 segue 連接，去切換畫面，在搭配 class UIViewController 底下的 func prepare 就可以同時傳遞資料。</p><p>要傳遞的頁面間需要有同樣型別的屬性，就可以傳遞資料；依據目的地的不同，傳遞不同的資料。</p><p>另一個目的地是 OrderViewController 是顯示點飲料細節的畫面。</p><pre>    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {<br>        <br>        if let destination = segue.destination as? CategoryTableViewController {<br>            <br>            destination.categories = categories<br>            <br>        } else if let destination = segue.destination as? OrderViewController,<br>                  let item = collectionView.indexPathsForSelectedItems?.first?.item {<br>            destination.record = presentItems[item]<br>        }<br>    }</pre><blockquote><strong>在選擇飲料類別，顯示一半高度的 Category table view controller</strong></blockquote><p>在下一頁 Category Table View Controller 顯示 Categories array，當點選 Category 按鈕時顯示該頁面。</p><p>特別的是，想要 Category Table View Controller 顯示特定高度，從 iOS 15 開始可使用 sheetPresentationController 負責控制用 present 顯示畫面及 sheetPresentationController 的 detents 設定頁面的高度，拉 IBSegueAction function 在裡面定義：</p><pre>    @IBSegueAction func showCategotyTableViewController(_ coder: NSCoder) -&gt; UITableViewController? {<br>        <br>        let controller = CategoryTableViewController(coder: coder)<br>        <br>        if let sheetPresentationController = controller?.sheetPresentationController {<br>            sheetPresentationController.detents = [.medium()]<br>        }<br>        return controller<br>    }</pre><p>高度有.large、.medium跟.custom 可以選</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*4b7VfdeZhHsQiAbGqgUpoA.gif" /></figure><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-15-%E7%8C%B6%E6%8A%B1%E7%90%B5%E7%90%B6%E5%8D%8A%E9%81%AE%E9%9D%A2-%E9%A1%AF%E7%A4%BA%E4%B8%80%E5%8D%8A%E7%9A%84-sheet-%E7%95%AB%E9%9D%A2-b13448a76cb0">只顯示部分高度的 sheet 畫面</a></p><blockquote><strong>使用 NotificationCenter 傳送出資料訊息以及在上一頁接收資料</strong></blockquote><p>Category Table View Controller 顯示出來後，當特定 cell 被點選時，利用 NotificationCenter.default<strong>.post</strong> 傳送被選擇的 category。</p><pre>    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {<br>        <br>        let row = indexPath.row<br>        <br>        let category = categories[row]<br>        <br>        let name = Notification.Name(&quot;selected category&quot;)<br>        NotificationCenter.default.post(name: name, object: nil, userInfo: [<br>            &quot;category&quot; : category<br>        ])<br>        <br>        dismiss(animated: true)<br>    }</pre><p>希望點選 cell 後<strong>自動返回</strong>上一頁，用 present 進入下一頁，所以用 <strong>dismiss</strong> 返回上一頁。</p><p>在 MenuViewController 用 NotificationCenter.default.<strong>addObserver</strong> 接收資料，特別注意其<strong>參數 selector </strong>必須是 <strong>objc function。</strong></p><p>一樣是用 for-in 跟 if 把符合 Category 的商品加入 presentItems array 重新顯示出來。</p><pre>    func selectedCategory() {<br>        let name = Notification.Name(&quot;selected category&quot;)<br>        NotificationCenter.default.addObserver(self, selector: #selector(categoryChanged), name: name, object: nil)<br>    }<br>    <br>    @objc func categoryChanged(noti: Notification) {<br>        <br>        presentItems = []<br>        collectionView.reloadData()<br>        <br>        if let userInfo = noti.userInfo,<br>           let category = userInfo[&quot;category&quot;] as? String {<br>            <br>            categoryButton.setTitle(category, for: .normal)<br>            <br>            if category == &quot;All Products&quot; {<br>                presentItems = records<br>            } else {<br>                for record in records {<br>                    if record.fields.category.first == category {<br>                        presentItems.append(record)<br>                    }<br>                }<br>            }<br>        }<br>        collectionView.reloadData()<br>    }</pre><p>最後把 func selectedCategory( ) 寫進 viewDidLoad 裡</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*xDxKLppIuWyYfffUgdkROA.gif" /></figure><p><a href="https://developer.apple.com/documentation/foundation/notificationcenter">NotificationCenter | Apple Developer Documentation</a></p><p><strong>訂飲料 Part 2：</strong></p><p><a href="https://medium.com/@chiayenlin_31230/43-drinks-order-app-%E8%A8%82%E9%A3%B2%E6%96%99-part-2-bd84b1f98234">#43 Drinks Order APP 訂飲料 − Part 2</a></p><p><strong>GitHub：</strong></p><p><a href="https://github.com/Ryan-CY/OrderDrink">GitHub - Ryan-CY/OrderDrink: Rest API (GET, POST, DELET) Practice</a></p><p><strong>Reference ：</strong></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/%E4%BD%A0%E5%87%BA%E5%8A%9B%E5%AF%AB-app-%E6%88%91%E5%87%BA%E9%8C%A2%E8%AB%8B%E9%A3%B2%E6%96%99-6a9ac14a2a22">#20 訂飲料 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/%E8%A8%82%E9%A3%B2%E6%96%99app-%E5%8F%AF%E4%B8%8D%E5%8F%AF-976c3b8c13bf">訂飲料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/29-%E9%A3%B2%E6%96%99app-%E4%BE%86%E6%9D%AF%E4%BA%94%E6%A1%90%E8%99%9F%E5%90%A7-9c47e3b72660">#29 飲料App來杯五桐號吧！</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fb4d8fc392dd" width="1" height="1" alt=""><hr><p><a href="https://medium.com/peter-pan-swift-ios-class/42-drinks-order-app-%E8%A8%82%E9%A3%B2%E6%96%99-part-1-fb4d8fc392dd">#42 Drinks Order APP 訂飲料 − Part 1</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[#41 Music Player 音樂播放器]]></title>
            <link>https://medium.com/peter-pan-swift-ios-class/41-music-player-%E9%9F%B3%E6%A8%82%E6%92%AD%E6%94%BE%E5%99%A8-f18797aad292?source=rss-b5b0c3dc8e10------2</link>
            <guid isPermaLink="false">https://medium.com/p/f18797aad292</guid>
            <category><![CDATA[api]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[CY’s Programming Journey]]></dc:creator>
            <pubDate>Fri, 28 Apr 2023 20:54:02 GMT</pubDate>
            <atom:updated>2023-06-21T17:35:31.155Z</atom:updated>
            <content:encoded><![CDATA[<h4>進階版</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UEfgdyggRbjgJd5hz98Sbw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eDXiDFvWmMGHe4figIHy-g.png" /></figure><h4>作業來源：</h4><p><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/94-%E6%A8%A1%E4%BB%BF-ios-%E7%9A%84-music-app-%E8%A3%BD%E4%BD%9C%E6%83%85%E6%AD%8C%E9%BB%9E%E5%94%B1%E6%A9%9F-acacd22d8928">#94 模仿 iOS 的 Music App 製作情歌點唱機(音樂播放器)</a></p><h4><strong>APP 功能部分：</strong></h4><p><strong>🌟 利用 AVPlayer 播放音樂</strong></p><p><strong>🌟 包含播放鍵，暫停鍵，下一首，上一首</strong></p><p><strong>🌟 調整音量</strong></p><p><strong>🌟 播完一首歌後，自動播放下一首歌</strong></p><p><strong>🌟 可滑動調整 &amp; 顯示歌曲播放的時間</strong></p><p><strong>🌟 播放時間快進5秒、倒退5秒</strong></p><p><strong>🌟 背景播放音樂</strong></p><p>🌟 <strong>重覆播放多首歌，單曲循環</strong></p><p><strong>🌟 隨機播放，順序播放</strong></p><h4>技術部分：</h4><p><strong>🌟 串接 iTunes API</strong></p><p><a href="https://developer.apple.com/library/archive/documentation/AudioVideo/Conceptual/iTuneSearchAPI/index.html">Overview</a></p><p><strong>🌟 UISearchBar</strong></p><p><strong>🌟 ViewController + CollectionView</strong></p><p><strong>🌟 AVPlayer()</strong></p><p><strong>🌟 prepare function</strong></p><p><strong>🌟 NotificationCenter</strong></p><p><strong>🌟 AVPlayer.Observing the Playback Time</strong></p><blockquote><strong>輸入歌手搜尋音樂</strong></blockquote><p>想要做到的效果是：利用 <strong>UISearchBar </strong>輸入歌手或團體，然後結合到 <strong>API get 的 function 的參數</strong>，去找出 iTunes 上符合的資料。</p><p>首先，要先讓 ViewController <strong>繼承 UISearchBarDelegate</strong>。之後就可以使用它的 function ，例如：</p><pre>func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {<br>    // 在此處處理搜索操作<br>}</pre><p>說明：注意其內部參數 searchText ，使用者在輸入字串時被始用</p><pre>func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {<br>    // 在此處顯示搜索結果<br>}</pre><p>說明：在使用者按下搜索時會執行這個 function。這裡只用到這個 function</p><pre>extension SearchViewController: UISearchBarDelegate {<br>    <br>    func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {<br>        <br>        if searchBar.text != &quot;&quot; {<br>            fetchMusic(term: searchBar.text ?? &quot;&quot;)<br>            view.endEditing(true)<br>            collectionView.reloadData()<br>        }<br>    }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/295/1*GlnVHQfSo-AxoYRZ7fFirA.gif" /></figure><blockquote><strong>利用 AVPlayer 播放音樂、包含播放鍵、暫停鍵、下一首、上一首、隨機 button，點選將隨機播放一首歌、調整音量</strong></blockquote><p>可以參考基本版文章：</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/30-music-player-%E9%9F%B3%E6%A8%82%E6%92%AD%E6%94%BE%E5%99%A8-29974f038544">#30 Music Player 音樂播放器</a></p><p>特別注意<strong>調整音量</strong>的部分，若是沒有特別設定一開使的音量則音量會是100%(就是1)。</p><p>希望一開始音量為50%，所以是設成0.5 (音量型別是Float，範圍是0~1)</p><blockquote><strong>播完一首歌後，自動重覆播放多首歌 or 單曲循環播放</strong></blockquote><p>運用到 <strong>NotificationCenter.default.addObserver，</strong>判斷Button的圖示決定要單曲播放或是下一首，搭配 <strong>AVPlayerItemDidPlayToEndTime</strong> 歌曲播放完的通知，寫在 viewDidLoad 裡</p><pre>NotificationCenter.default.addObserver(forName: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: nil, queue: .main) { _ in<br>            <br>            if self.repeatButton.imageView?.image == UIImage(systemName: &quot;repeat&quot;) {<br>                //自動播放下一首<br>                self.player.pause()<br>                self.index = (self.index + 1) % self.musics.count<br>                self.currentTime = 0<br>                self.playMusic()<br>            } else if self.repeatButton.imageView?.image == UIImage(systemName: &quot;repeat.1&quot;) {<br>                self.player.pause()<br>                self.currentTime = 0<br>                self.playMusic()<br>            }<br>        }</pre><p>Button 的 IBAction function</p><pre>    @IBAction func pressRepeat(_ sender: Any) {<br>        if repeatButton.imageView?.image == UIImage(systemName: &quot;repeat&quot;) {<br>            repeatButton.setImage(UIImage(systemName: &quot;repeat.1&quot;), for: .normal)<br>        } else {<br>            repeatButton.setImage(UIImage(systemName: &quot;repeat&quot;), for: .normal)<br>        }<br>    }</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/295/1*kZIX8ToOwZRcZ2z7WxJ-Sg.gif" /></figure><blockquote><strong>可滑動調整 &amp; 顯示歌曲播放的時間</strong></blockquote><h4>✨ Observing the Playback Time</h4><pre>func addPerioedTimeObserver() {<br>        <br>    let timeScale = CMTimeScale(NSEC_PER_SEC)<br>    let time = CMTime(seconds: 1, preferredTimescale: timeScale)<br>        <br>    self.timeObserverToken = player.addPeriodicTimeObserver(forInterval: time, queue: .main, using: { _ in<br>            <br>        self.currentTime = self.player.currentTime().seconds<br>        self.timeConfiguration()<br>            <br>    })<br>}</pre><p>然後把function addPeriodTimeObserver()放在播放的 function 裡</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/718/1*s2gO2QYx5P-KttJjQBpnCg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/295/1*nlCWh03h4Y_oeJY2Cw3YvQ.gif" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4x8bMTXu4kcAcHFhPZpddg.png" /></figure><p>注意：有時播放時 APP 會突然 crash，查了一下解決的方式就是加入這一行<br>，確保 currentTime 不會是 Nan 或 Infinite</p><pre>guard !(currentTime.isNaN || currentTime.isInfinite) else {return}</pre><p>✨ 用 <strong>timeControlStatus</strong> 讀取播放器狀態</p><p>✨ 用 <strong>currentItem?.asset.duration.seconds</strong> 讀取歌曲總秒數</p><p>✨ 用 <strong>currentTime().seconds</strong> 讀取目前播放到第幾秒</p><p>✨ 用 <strong>seek</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/%E5%88%A9%E7%94%A8-viewdidload-%E9%BB%9E%E4%B8%80%E9%A6%96%E6%AD%8C-%E6%92%AD%E6%94%BE%E4%B8%80%E6%AC%A1pl-bfe59e9e22c">利用 AVPlayer 播放音樂音效</a></p><p>播放進度的 Slider 的 IBAction function</p><pre>    //change process of song while sliding the slider<br>    @IBAction func changeTimeSlider(_ sender: UISlider) {<br>        let time = CMTime(value: CMTimeValue(sender.value), timescale: 1)<br>        player.seek(to: time)<br>    }</pre><p>說明：透過 seek 當滑動 Slider 就可以找到對應的播放進度了</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/295/1*g5BBKqHxR6hmk3_p3Urzcg.gif" /></figure><blockquote><strong>播放時間快進5秒、倒退5秒</strong></blockquote><p>同樣用 <strong>seek</strong> 就可以做到</p><pre>    @IBAction func pressGoforward(_ sender: Any) {<br>        let time = CMTime(value: Int64(timeSlider.value + 5), timescale: 1)<br>        player.seek(to: time)<br>    }<br>    <br>    @IBAction func pressBackward(_ sender: Any) {<br>        let time = CMTime(value: Int64(timeSlider.value - 5), timescale: 1)<br>        player.seek(to: time)<br>    }</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/295/1*517-yZmwyGiTbAfsLxwrbw.gif" /></figure><blockquote><strong>背景播放音樂</strong></blockquote><p>這篇有詳細得解釋</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/%E8%A8%AD%E5%AE%9A-background-mode-%E5%9C%A8%E8%83%8C%E6%99%AF%E6%92%AD%E6%94%BE%E9%9F%B3%E6%A8%82-9bab5db75cc9">設定 Background Mode 在背景播放音樂</a></p><blockquote><strong>隨機播放，順序播放</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YxIa862NfsQfedxF7H7exw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/295/1*rQviXjjtNSbyl9L1PnI-zQ.gif" /></figure><p>GitHub：</p><p><a href="https://github.com/Ryan-CY/Music-Player-advanced-">GitHub - Ryan-CY/Music-Player-advanced-</a></p><p>參考資料：</p><ul><li><a href="https://stackoverflow.com/questions/53551539/receiving-fatal-error-double-value-cannot-be-converted-to-int-because-it-is-eit">Receiving Fatal error: Double value cannot be converted to Int because it is either infinite or NaN</a></li><li><a href="https://www.tutorialspoint.com/how-can-i-use-timer-formerly-nstimer-in-swift#">How can I use Timer (formerly NSTimer) 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%E5%95%8F%E9%A1%8C%E8%A7%A3%E7%AD%94%E9%9B%86/%E7%B8%AE%E5%B0%8F%E5%9C%96%E7%89%87%E7%9A%84-preparingthumbnail-94fdd6ff9c7e">縮小圖片的 preparingThumbnail</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/uikit-app-%E6%8C%89%E7%A9%BA%E7%99%BD%E8%99%95%E6%94%B6%E9%8D%B5%E7%9B%A4%E7%9A%84%E6%96%B9%E6%B3%95-97a676338e86">UIKit 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/28-%E6%A8%A1%E4%BB%BFios-musicapp-%E9%9F%B3%E6%A8%82%E6%92%AD%E6%94%BE%E5%99%A8-62f9664ba2ad">#28 模仿iOS MusicApp, 音樂播放器</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/59-music-app-%E9%9F%B3%E6%A8%82%E6%92%AD%E6%94%BE%E5%99%A8-c193751b36e3">＃59 Music App 音樂播放器</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f18797aad292" width="1" height="1" alt=""><hr><p><a href="https://medium.com/peter-pan-swift-ios-class/41-music-player-%E9%9F%B3%E6%A8%82%E6%92%AD%E6%94%BE%E5%99%A8-f18797aad292">#41 Music Player 音樂播放器</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[#40 串接 TIH API - present, shouldPerformSegue, AlertController & prepare]]></title>
            <link>https://medium.com/peter-pan-swift-ios-class/40-%E4%B8%B2%E6%8E%A5-tih-api-present-shouldperformsegue-alert-prepare-b9059d112bda?source=rss-b5b0c3dc8e10------2</link>
            <guid isPermaLink="false">https://medium.com/p/b9059d112bda</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[api]]></category>
            <dc:creator><![CDATA[CY’s Programming Journey]]></dc:creator>
            <pubDate>Mon, 03 Apr 2023 05:51:06 GMT</pubDate>
            <atom:updated>2023-07-06T02:30:56.396Z</atom:updated>
            <content:encoded><![CDATA[<h4>reviews, website &amp; map</h4><blockquote>本篇為實作 present 呈現網頁，加入 shouldPerformSegue 決定跳出 AlertController 或執行 prepare 顯示 reviews 及 map</blockquote><p><strong><em>繼前兩篇介紹了 TIH 及其 API 及部分APP應用的實作</em></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%E6%95%99%E5%AE%A4/%E4%B8%B2%E6%8E%A5-api-tih-%E4%BB%8B%E7%B4%B9-44c4d4099234">#38 串接 TIH API - TIH 介紹</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/39-%E4%B8%B2%E6%8E%A5-api-tableviewcontroller-collectionview-%E8%88%87-prepare-%E5%82%B3%E9%81%9E%E8%B3%87%E6%96%99-cbaa53c25dec">#39 串接 TIH API - TableViewController, CollectionView 與 prepare 傳遞資料</a></li></ul><p><strong><em>接下來將介紹其餘在APP上的實作部分：</em></strong></p><blockquote><strong>顯示 reviews</strong></blockquote><blockquote><strong>利用 shouldPerformSegue 分辨不同 segue</strong></blockquote><blockquote><strong>present 跳出 AlertController</strong></blockquote><blockquote><strong>顯示自訂 Date 格式</strong></blockquote><blockquote><strong>顯示飯店 map</strong></blockquote><blockquote><strong>prepare 傳遞資料</strong></blockquote><blockquote><strong>present 呈現 website</strong></blockquote><blockquote><strong>顯示 reviews、利用 shouldPerformSegue 分辨不同 segue &amp; present 跳出 AlertController</strong></blockquote><p>看到 JSON 裡有旅客對飯店的 reviews (評論)，這裡也是用 function prepare 去傳遞資料，但若是有 function shouldPerformSegue 則在執行 prepare 前會先執行 shouldPerformSegue。</p><p>仔細觀察，發現有時 reviews 也會是空的！！</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3yk6OOLzwJ-AN01MFTVASA.png" /><figcaption>Ex: Array of reviews is empty</figcaption></figure><p>若是在同一頁面會傳出資料到不同頁面，注意 shouldPerformSegue 的參數 identifier，就得設定 segue 的 identifier，才可分辨是專指哪一條 segue</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E3PuvUFevy_CsT00Cy_gbg.png" /><figcaption>setting identifier of segue</figcaption></figure><p>若 reviews 的 <strong>array 是空</strong>的則會跳出<strong> AlertController</strong> 提醒 user；</p><pre>    //決定segue要不要執行<br>    override func shouldPerformSegue(withIdentifier identifier: String, sender: Any?) -&gt; Bool {<br>        <br>        if identifier == &quot;reviewSegue&quot;, hotel?.reviews.isEmpty == true {<br>            let alert = UIAlertController(title: &quot;NO REVIEW YET !&quot;, message: &quot;To return, click on Close &quot;, preferredStyle: .alert)<br>            alert.addAction(UIAlertAction(title: &quot;Close&quot;, style: .default))<br>            present(alert, animated: true)<br>            return false<br>        }<br>        return true<br>    }</pre><p>反之，則顯示 reviews 在 ReviewTableViewController</p><pre>    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -&gt; Int {<br>        // #warning Incomplete implementation, return the number of rows<br>        return reviews.count<br>    }<br>    <br>    func configuration(_ cell: ReviewTableViewCell) {<br>        cell.authorNameLabel.frame = CGRect(x: 10, y: 30, width: 150, height: 25)<br>        cell.authorNameLabel.adjustsFontSizeToFitWidth = true<br>        <br>        cell.ratingLabel.font = .systemFont(ofSize: 12, weight: .semibold)<br>        <br>        cell.textTextView.backgroundColor = .systemGray6<br>        cell.textTextView.textColor = .black<br>        cell.textTextView.layer.cornerRadius = 10<br>        <br>        cell.timeLabel.frame = CGRect(x: 30, y: 120, width: 130, height: 25)<br>        cell.timeLabel.font = .systemFont(ofSize: 13, weight: .regular)<br>        cell.timeLabel.textAlignment = .right<br>    }<br>    <br>    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -&gt; UITableViewCell {<br>        let cell = tableView.dequeueReusableCell(withIdentifier: &quot;\(ReviewTableViewCell.self)&quot;, for: indexPath) as! ReviewTableViewCell<br>        <br>        configuration(cell)<br>        <br>        let review = reviews[indexPath.row]<br>        <br>        cell.authorNameLabel.text = review.authorName<br>        cell.ratingLabel.text = review.rating.description<br>        cell.textTextView.text = review.text<br>        <br>        //顯示時間<br>        let newDateFormatter = DateFormatter()<br>        newDateFormatter.dateFormat = &quot;MMMM d, yyyy&quot;<br>        cell.timeLabel.text = newDateFormatter.string(from: review.time)<br>        <br>        for star in cell.starImageViews {<br>            star.image = nil<br>            star.image = UIImage(systemName: &quot;star&quot;)<br>            star.tintColor = .systemGray5<br>        }<br>        <br>        let rating = review.rating<br>        let starRagne = Int(rating)-1<br>        <br>        if rating != 0 {<br>            for star in 0...starRagne {<br>                cell.starImageViews[star].tintColor = .systemYellow<br>                cell.starImageViews[star].image = UIImage(systemName: &quot;star.fill&quot;)<br>                <br>                if rating - Double(Int(rating)) &gt; 0 {<br>                    cell.starImageViews[Int(rating)].tintColor = .systemYellow<br>                    cell.starImageViews[Int(rating)].image = UIImage(systemName: &quot;star.leadinghalf.filled&quot;)<br>                }<br>            }<br>        }<br>        <br>        return cell<br>    }</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/295/1*Ndol91JsBVth_iMlKN1SUA.gif" /><figcaption>demonstration of reviews</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rgeZ4qaHLUoPcrg_MDqdJg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*27nFkB6EoD5iJVppPAIQwg.png" /><figcaption>Left: Array of reviews is empty, Right: show reviews</figcaption></figure><p>AlertController 可參考</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/27-%E9%AA%B0%E5%AD%90%E6%AF%94%E5%A4%A7%E5%B0%8F-uiviewpropertyanimator-uialertcontroller-599ef5ab3b7e">#27 骰子比大小-UIViewPropertyAnimator &amp; UIAlertController</a></p><blockquote><strong>顯示自訂 Date 格式</strong></blockquote><p>在上一篇解釋如何讓程式看懂 JSON 的 Date 格式，現在要呈現出我們自己想要的時間格式。</p><p>同樣的，需要 DateFormatter() 幫忙</p><pre>//顯示時間<br>let newFormatter = DateFormatter()<br>newFormatter.dateFormat = &quot;MMMM d, yyyy&quot;<br>cell.timeLabel.text = newFormatter.string(from: review.time)</pre><p>一樣是用 DateFormatter() 的參數 dateFormat 去設定想要的 Date 格式。</p><p>特別注意：要顯示時間的來源，則是用 DateFormatter() 的參數 <strong>string(from: )</strong> 去設定其來源。</p><p>結果可參考上圖右。</p><blockquote><strong>顯示飯店 map、prepare 傳遞資料</strong></blockquote><p>除了顯示 reviews 用到 function prepare ，顯示飯店 map 同樣也用到 function prepare ！</p><p>所以它們的 source (起始頁面) 一樣，destination (終點頁面) 不一樣，<br>用 segue 的 <strong>destination 型別分辨要傳什麼資料</strong></p><pre>    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {<br>        <br>        if let destoination = segue.destination as? ReviewTableViewController {<br><br>            destoination.reviews = hotel!.reviews<br><br>        } else if let destination = segue.destination as? MapViewController {<br><br>            destination.hotel = hotel<br>        }<br>    }</pre><p>在 destination 頁面自訂型別並遵從 UIViewController，新增 <strong>Map Kit View</strong> 及拉好 IBOutlet，<strong>import MapKit</strong> 及宣告好要承接資料的屬性 <strong>var</strong> hotel: Hotel?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fevtqfkgPGVfPGn2jUiSpw.png" /></figure><p>JSON 裡也有給座標，同樣解析後就可以使用了</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*fQrPzVcMAaP_Z3Xl1gj_5w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/562/1*uQta4s-cEVpuYJ2r0ImsWQ.png" /></figure><p>要顯示地圖需要用到：<br> <strong>CLLocationCoordinate2D(latitude:, longitude:) </strong>設定座標，<br>在把座標丟進 <strong>MKCoordinateRegion</strong> 設為 center 及設好範圍，<br>之後用 <strong>Map Kit View</strong> 的 Method <strong>setRegion()</strong> 把設好的 center 及範圍丟進去</p><p>最後，設定地圖上的<strong>註解</strong>，利用 <strong>MKPointAnnotation()</strong></p><pre>        hotelMapView.frame = CGRect(x: 0, y: 0, width: 393, height: 700)<br>        <br>        if let latitude = hotel?.location.latitude,<br>           let longitude = hotel?.location.longitude {<br>            //defining the coordinate via latitude and longitude<br>            let location = CLLocationCoordinate2D(latitude: latitude, longitude: longitude)<br>            //defining the center and range(meter) of the map<br>            let mapRange = MKCoordinateRegion(center: location, latitudinalMeters: 1000, longitudinalMeters:520)<br>            //show the map<br>            hotelMapView.setRegion(mapRange, animated: true)<br>            let annotation = MKPointAnnotation()<br>            //defining the coordinate of annotation<br>            annotation.coordinate = location<br>            annotation.title = hotel?.name<br>            annotation.subtitle = &quot;Hotel&quot;<br>            //show the annotation on the map<br>            hotelMapView.addAnnotation(annotation)<br>            hotelMapView.showsScale = true<br>        }</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/295/1*K2uheBVhAI7mkbLz8TRsCA.gif" /><figcaption>demonstration of map</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WvxEnVtj9ydZgyczFIbXig.png" /><figcaption>show map</figcaption></figure><blockquote><strong>present 呈現 website</strong></blockquote><p>發現 JSON 給的飯店網址有的不是很完整，少了 https:// ，以至於無法顯示，只能自己幫它補齊了</p><pre>    @IBAction func pressWebsiteButton(_ sender: Any) {<br>        <br>        if hotel?.officialWebsite.contains(&quot;https://&quot;) == false {<br>            let urlString = &quot;https://\(hotel!.officialWebsite)&quot;<br>            print(urlString)<br>            if let url = URL(string: urlString) {<br>                let browser = SFSafariViewController(url: url)<br>                present(browser, animated: true)<br>            }<br>        } else {<br>            if let url = URL(string: hotel!.officialWebsite) {<br>                let browser = SFSafariViewController(url: url)<br>                present(browser, animated: true)<br>            }<br>        }<br>    }</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/295/1*96-YiJU5b0GXdXywMi5NNw.gif" /><figcaption>demonstration of website</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5cjfTihNV4_6_35jSqzWgw.png" /><figcaption>show website</figcaption></figure><p>GitHub：</p><p><a href="https://github.com/Ryan-CY/TIH-API-via-prepare">GitHub - Ryan-CY/TIH-API-via-prepare</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b9059d112bda" width="1" height="1" alt=""><hr><p><a href="https://medium.com/peter-pan-swift-ios-class/40-%E4%B8%B2%E6%8E%A5-tih-api-present-shouldperformsegue-alert-prepare-b9059d112bda">#40 串接 TIH API - present, shouldPerformSegue, AlertController &amp; prepare</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[#39 串接 TIH API - TableViewController, CollectionView 與 prepare 傳遞資料]]></title>
            <link>https://medium.com/peter-pan-swift-ios-class/39-%E4%B8%B2%E6%8E%A5-api-tableviewcontroller-collectionview-%E8%88%87-prepare-%E5%82%B3%E9%81%9E%E8%B3%87%E6%96%99-cbaa53c25dec?source=rss-b5b0c3dc8e10------2</link>
            <guid isPermaLink="false">https://medium.com/p/cbaa53c25dec</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[api]]></category>
            <dc:creator><![CDATA[CY’s Programming Journey]]></dc:creator>
            <pubDate>Fri, 31 Mar 2023 07:32:31 GMT</pubDate>
            <atom:updated>2023-07-03T12:56:12.119Z</atom:updated>
            <content:encoded><![CDATA[<h4>TableViewController-Hotel List, CollectionView-show photos, prepare-transfer information</h4><blockquote>本篇為實作 TableViewController, CollectionView 與 prepare 傳遞資料</blockquote><p><strong><em>繼上一篇介紹了 TIH 及其 API</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%E6%95%99%E5%AE%A4/%E4%B8%B2%E6%8E%A5-api-tih-%E4%BB%8B%E7%B4%B9-44c4d4099234">#38 串接 TIH API - TIH 介紹</a></p><p><strong><em>接下來將介紹應用在APP上的實作部分：</em></strong></p><blockquote><strong>URLSession 抓取資料</strong></blockquote><blockquote><strong>關於解析 Date</strong></blockquote><blockquote><strong>顯示 data — TableViewController</strong></blockquote><blockquote><strong>prepare 傳遞資料</strong></blockquote><blockquote><strong>製作 CollectionView</strong></blockquote><blockquote><strong>URLSession 抓取資料</strong></blockquote><p>在解析好 JSON 後，就可以開始利用 URLSession 告訴程式 API 網址及轉換 JSON 到自訂好的型別，之後就可以使用它的資料了</p><p>可以先把API Key 的 Value 寫成屬性，以及宣告一個空array，裡面是自訂型別</p><pre>    let APIValue = &quot;2M.....eE&quot;<br>    <br>    var hotels = [Hotel]()</pre><p>把抓取資料寫成 function，之後放在 viewDidLoad 裡，使其 APP 開啟就自動抓取</p><pre>func fetchList() {<br>        let urlString = &quot;https://api.stb.gov.sg/content/accommodation/v2/search?searchType=keyword&amp;searchValues=city%20hall&amp;sort=name&amp;sortOrder=asc&quot;<br>        <br>        if let url = URL(string: urlString) {<br>            var request = URLRequest(url: url)<br>            request.setValue(APIValue, forHTTPHeaderField: &quot;X-API-Key&quot;)<br>            URLSession.shared.dataTask(with: request) { data, response, error in<br>                if let data,<br>                   let response = response as? HTTPURLResponse {<br>                    //印出server狀態<br>                    print(&quot;statusCode&quot;,response.statusCode)<br>                    let decorder = JSONDecoder()<br>                    let dateFormatter = DateFormatter()<br>                    dateFormatter.dateFormat = &quot;yyyy-MM-dd&#39;T&#39;HH:mm:ssZZZZZ&quot;<br>                    decorder.dateDecodingStrategy = .formatted(dateFormatter)<br>                    do {<br>                        //從JSON物件轉換成自訂型別<br>                        let result = try decorder.decode(Result.self, from: data)<br>                        //轉換好型別後，存入定義好相同型別的空 array<br>                        //重要：得一起寫在 URLSession.shared.dataTask (background thread)裡，不然會存到空的資料<br>                        self.hotels = result.data<br>                        <br>                        DispatchQueue.main.async {<br>                            self.tableView.reloadData()<br>                        }<br>                    } catch {<br>                        print(error)<br>                    }<br>                }<br>            }.resume()<br>        }<br>    }</pre><p>注意：URLSession 是在 background thread 執行，若是跟UI有關的都要寫在 DispatchQueue.main.async { } 的大括號裡，就會在 main thread 執行。</p><blockquote><strong>關於解析 Date</strong></blockquote><p>其中的關鍵在於利用 DateFormatter() 以及 JSONDecoder.dateDecodingStrategy</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/jsondecoder-%E8%A7%A3%E6%9E%90%E6%99%82%E9%96%93%E7%9A%84-datedecodingstrategy-a4095481f193">JSONDecoder 解析時間的 DateDecodingStrategy</a></p><p>時間在 reviews 的最下一行</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QlE3DRXmjDp6zZIVqanvDQ.png" /></figure><p>它的時間格式是自訂的時間格式，這時需要參考下面網站，在程式裡用英文字母呈現它的格式</p><p><a href="http://nsdateformatter.com/#reference">NSDateFormatter.com - Live Date Formatting Playground for Swift</a></p><p>變成：</p><pre>let decorder = JSONDecoder()<br>let dateFormatter = DateFormatter()<br>dateFormatter.dateFormat = &quot;yyyy-MM-dd&#39;T&#39;HH:mm:ssZZZZZ&quot;<br>decorder.dateDecodingStrategy = .formatted(dateFormatter)</pre><p>到這一步，只是讓程式看懂它的時間格式</p><blockquote><strong>顯示 data - TableViewController</strong></blockquote><p>解析好 JSON 就可以開始藉由自訂型別去使用 JSON 資料，這裡是去顯示在 TableViewController 上</p><pre>    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -&gt; Int {<br>        // #warning Incomplete implementation, return the number of rows<br>        return hotels.count<br>    }<br>    <br>    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -&gt; UITableViewCell {<br>        let cell = tableView.dequeueReusableCell(withIdentifier: &quot;\(ListTableViewCell.self)&quot;, for: indexPath) as! ListTableViewCell<br>        <br>        let hotel = hotels[indexPath.row]<br>        //顯示飯店照片<br>        //防止cell重複利用顯示錯誤影像，方法一：先清空影像<br>        cell.photoImageView.image = nil<br>        cell.processIndicator.startAnimating()<br>        /*<br>         防止cell重複利用顯示錯誤影像，方法二：顯示預設照片<br>         cell.photoImageView.image = UIImage(systemName: &quot;photo&quot;)<br>         cell.photoImageView.tintColor = .systemGray5<br>         cell.photoImageView.contentMode = .scaleAspectFit<br>         cell.photoImageView.layer.cornerRadius = 10<br>         */<br>        //當uuid是空字串，從url取得圖片<br>        if hotel.images.first?.uuid == &quot;&quot; {<br>            let urlString = hotel.images.first?.url<br>            let finalUrl = URL(string: urlString!)<br>            print(&quot;imageURL&quot;, urlString!)<br>            cell.photoImageView.kf.setImage(with: finalUrl)<br>            cell.photoImageView.contentMode = .scaleAspectFill<br>            cell.processIndicator.stopAnimating()<br>        }<br>        //當url是空字串，從uuid取得圖片<br>        else if hotel.images.first?.url == &quot;&quot; {<br>            <br>            let hotelUuid = hotel.images.first?.uuid<br>            if let url = URL(string: &quot;https://tih-api.stb.gov.sg/media/v1/download/uuid/\(hotelUuid!)?apikey=\(APIValue)&quot;) {<br>                cell.photoImageView.kf.setImage(with: url)<br>                cell.photoImageView.contentMode = .scaleAspectFill<br>                cell.processIndicator.stopAnimating()<br>            }<br>        } else {<br>            //當uuid跟url都沒有時，顯示特定圖示<br>            cell.photoImageView.image = UIImage(systemName: &quot;photo.on.rectangle.angled&quot;)<br>            cell.photoImageView.tintColor = .systemGray4<br>            cell.photoImageView.contentMode = .scaleAspectFit<br>            cell.processIndicator.stopAnimating()<br>        }<br>        <br>        cell.titleLabel.text = hotel.name<br>        <br>        cell.ratingLabel.text = hotel.rating.description<br>        //show the stars of rating<br>        //avoid showing wrong images on cell<br>        for star in cell.ratingImageViews {<br>            star.image = UIImage(systemName: &quot;&quot;)<br>        }<br>        <br>        for star in cell.ratingImageViews {<br>            star.image = UIImage(systemName: &quot;star&quot;)<br>            star.tintColor = .systemGray5<br>        }<br>        <br>        let rating = hotel.rating<br>        let intStarRating = Int(rating)<br>        let starRagne = intStarRating-1<br>        <br>        for star in 0...starRagne {<br>            cell.ratingImageViews[star].tintColor = .systemYellow<br>            cell.ratingImageViews[star].image = UIImage(systemName: &quot;star.fill&quot;)<br>            <br>            if rating - Double(intStarRating) &gt; 0 {<br>                cell.ratingImageViews[intStarRating].tintColor = .systemYellow<br>                cell.ratingImageViews[intStarRating].image = UIImage(systemName: &quot;star.leadinghalf.filled&quot;)<br>            }<br>        }<br>        //顯示是否有官方衛生認證 SG Clean<br>        if hotel.group != &quot;&quot; {<br>            cell.groupLabel.text = &quot;SG Clean&quot;<br>            cell.groupLabel.backgroundColor = UIColor(red: 131/255, green: 181/255, blue: 87/255, alpha: 1)<br>        }<br>        <br>        cell.configuration()<br>        <br>        return cell<br>    }</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/295/1*dgphu2I_rkLQf6N7x-WkGA.gif" /><figcaption>TableViewController-GIF</figcaption></figure><blockquote><strong>prepare 傳遞資料</strong></blockquote><p>傳遞資料的方法有很多種，這裡練習用 prepare 把資料傳遞到別的頁面。</p><p><strong>Step 1：</strong><br>從<strong>起始(source)頁面</strong>( TableViewController 的 cell )，<strong>拉線</strong>到<strong>終點(destination)頁面</strong>( ViewController )，</p><p><strong>Step 2：</strong><br>在<strong>終點頁面</strong>裡，<strong>宣告</strong>好跟傳遞資料<strong>一樣型別的屬性</strong>，去<strong>承接資料</strong>；</p><pre>    var APIValue = &quot;&quot;<br>    var hotel: Hotel?</pre><p><strong>Step 3：</strong><br>在<strong>起始頁面</strong>( TableViewController ) 裡，輸入 <strong>prepare function 的程式碼</strong>。</p><pre>override func prepare(for segue: UIStoryboardSegue, sender: Any?) {<br>        if let destination = segue.destination as? IntroViewController,<br>           let row = self.tableView.indexPathForSelectedRow?.row {<br>            let hotel = hotels[row]<br>            destination.hotel = hotel<br>            destination.APIValue = APIValue<br>        }<br>    }</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/295/1*KswKqcF2FIDCYL6_JduO4g.gif" /><figcaption>GIF</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9jBqxmXo9ObOh8sI4ZoLrw.png" /><figcaption>ViewController</figcaption></figure><blockquote><strong>製作 CollectionView</strong></blockquote><p>在 ViewController 下方加了一個 CollectionView，希望能以水平捲動的方式顯示飯店的照片</p><p>可以參考：</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/121-%E6%B0%B4%E5%B9%B3%E6%8D%B2%E5%8B%95%E7%9A%84-collection-view-eb679cb5fbaf">#121 水平捲動的 collection view</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/35-ebook-of-jewel-changi-airport-%E6%98%9F%E8%80%80%E6%A8%9F%E5%AE%9C-%E9%9B%BB%E5%AD%90%E6%9B%B8-%E7%A8%8B%E5%BC%8F%E7%89%88-8e7cbb990b75"># 35 eBook of Jewel Changi Airport 星耀樟宜 電子書-程式版</a></li></ul><pre>import Foundation<br>import UIKit<br><br>extension IntroViewController: UICollectionViewDataSource {<br>    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -&gt; Int {<br>        //若image array是空的，至少產生一個cell，去顯示APP預設圖片<br>        if hotel!.images.isEmpty == true {<br>            return 1<br>        } else {<br>            return hotel!.images.count<br>        }<br>    }<br>    <br>    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -&gt; UICollectionViewCell {<br>        guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: &quot;\(OneCollectionViewCell.self)&quot;, for: indexPath) as? OneCollectionViewCell else {<br>            fatalError(&quot;dequeueReusableCell PhotoCollectionViewCell Failed&quot;)<br>        }<br>        <br>        if hotel?.images.isEmpty == true {<br>            cell.oneImageView.image = UIImage(systemName: &quot;photo.on.rectangle.angled&quot;)<br>            cell.oneImageView.contentMode = .scaleAspectFit<br>            cell.oneImageView.tintColor = .systemGray4<br>            <br>        } else {<br>            onePhotoActivityIndicator.startAnimating()<br>            let newIndex = (indexPath.item + hotel!.images.count) % hotel!.images.count<br>            <br>            if hotel?.images[newIndex].uuid == &quot;&quot; {<br>                let urlString = hotel?.images[newIndex].url<br>                if let url = URL(string: urlString!) {<br>                    cell.oneImageView.kf.setImage(with: url)<br>                    cell.oneImageView.contentMode = .scaleAspectFill<br>                    onePhotoActivityIndicator.stopAnimating()<br>                }<br>                <br>            } else if hotel?.images[newIndex].url == &quot;&quot; {<br>                let imageUuid = hotel?.images[newIndex].uuid<br>                if let url = URL(string: &quot;https://tih-api.stb.gov.sg/media/v1/download/uuid/\(imageUuid!)?apikey=\(APIValue)&quot;) {<br>                    cell.oneImageView.kf.setImage(with: url)<br>                    cell.oneImageView.contentMode = .scaleAspectFill<br>                    onePhotoActivityIndicator.stopAnimating()<br>                }<br>            }<br>        }<br>        photoCollectionView.isPagingEnabled = true<br>        photoCollectionView.showsHorizontalScrollIndicator = false<br>        return cell<br>    }<br>}<br><br>extension IntroViewController: UIScrollViewDelegate {<br>    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {<br>        let pageNumber = scrollView.contentOffset.x/scrollView.bounds.width<br>        pageIndicator.currentPage = Int(pageNumber)<br>        //print(scrollView.contentOffset.x)<br>        //print(scrollView.bounds.width)<br>    }<br>}</pre><p>下方加了一個 PageControl 去提示使用者可以滑動照片</p><pre>        pageIndicator.hidesForSinglePage = true<br>        pageIndicator.numberOfPages = hotel!.images.count<br>        pageIndicator.pageIndicatorTintColor = .systemGray5<br>        pageIndicator.currentPageIndicatorTintColor = .systemCyan</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/295/1*FNnTQ1adVopfT4UOVKsjMw.gif" /><figcaption>CollectionView-GIF</figcaption></figure><p><strong><em>下一篇將介紹 CollectionView 上方三個 Button ( reviews, website and map )的連結部分。</em></strong></p><p><a href="https://medium.com/@chiayenlin_31230/40-%E4%B8%B2%E6%8E%A5-tih-api-present-shouldperformsegue-alert-prepare-b9059d112bda">#40 串接 TIH API - present, shouldPerformSegue, alert &amp; prepare</a></p><p>GitHub：</p><p><a href="https://github.com/Ryan-CY/TIH-API-via-prepare">GitHub - Ryan-CY/TIH-API-via-prepare</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cbaa53c25dec" width="1" height="1" alt=""><hr><p><a href="https://medium.com/peter-pan-swift-ios-class/39-%E4%B8%B2%E6%8E%A5-api-tableviewcontroller-collectionview-%E8%88%87-prepare-%E5%82%B3%E9%81%9E%E8%B3%87%E6%96%99-cbaa53c25dec">#39 串接 TIH API - TableViewController, CollectionView 與 prepare 傳遞資料</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[#38 串接 TIH API - TIH 介紹]]></title>
            <link>https://medium.com/peter-pan-swift-ios-class/%E4%B8%B2%E6%8E%A5-api-tih-%E4%BB%8B%E7%B4%B9-44c4d4099234?source=rss-b5b0c3dc8e10------2</link>
            <guid isPermaLink="false">https://medium.com/p/44c4d4099234</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[api]]></category>
            <dc:creator><![CDATA[CY’s Programming Journey]]></dc:creator>
            <pubDate>Thu, 30 Mar 2023 00:18:30 GMT</pubDate>
            <atom:updated>2023-07-03T12:55:21.820Z</atom:updated>
            <content:encoded><![CDATA[<h4>星國官方旅遊 API、取得 JSON及解析 JSON</h4><blockquote>在尋找練習串接 API 的題材時，赫然發現新加坡旅遊局提供免費註冊就可以使用 Tourism Information &amp; Services Hub (TIH) 所提供的 API</blockquote><blockquote><strong><em>本篇著重在 API 題材介紹、取得其 JSON及</em></strong>解析 JSON</blockquote><h3>星國官方旅遊 API</h3><p><a href="https://tih.stb.gov.sg/content/tih/en/home.html">Home | TIH</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vIWb-ivPaD40CqLbIGaA3w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*68QAJGwcXDDLxVs7xd1oow.png" /></figure><blockquote><strong>🌟 註冊 &amp; 取得API Key</strong></blockquote><p>從首頁就可以發現，官方提供的 API 好像很豐富</p><p>點選註冊後會出現三個選項：<br><strong>Public(公眾)、Developers(開發者)</strong>及<strong>Businesses(公司企業)</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*svw12iN7lg9oV9E3PSfZAQ.gif" /></figure><p>現階段是點選 Developers，之後表格不會太冗長，大約三分鐘就可以完成整個註冊過程，最後 <strong>e-mail 就會收到 API Key</strong> 囉！</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oxu-CTGNpRmMsd83a1SdNQ.png" /></figure><blockquote><strong>🌟 Developer Portal (開發者網站)</strong></blockquote><p>登入後，點選<strong>網頁右上角的人像 icon</strong>，就會出現<strong>綠色字樣</strong>的 <strong>Developer Portal</strong>，點選後就會進入<strong>開發者網站</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/744/1*LmZe68gBJnsldYnPTGX8rw.png" /></figure><p>開啟後，發現 API 的頁面很簡潔，網頁<strong>上方橫排的選項</strong>可以看到 <strong>API</strong> 及<strong>其文件</strong>跟<strong>導覽介紹</strong>，還有關於 TIH 及新聞的介紹</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wIJIYS3VHGnkWLkFtnbE-w.png" /></figure><p>往下移動，發現這個 API 網頁不只可以下載(API Get)，還支援更新，但需進一步研究。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Bk4_3OX3OYQZ227kWcpmZw.png" /></figure><blockquote><strong>🌟 探索開發者網站 — About TIH</strong></blockquote><p>從最左邊的選項開始探索這個網站，<strong>點選 About TIH</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6p8SDdlBh0nIx4rKfYZ6kw.png" /><figcaption>Home Page of TIH</figcaption></figure><p>點選後的畫面，主要是在說明註冊後透過自動更新的 API，去應用在網頁或是行動裝置的 APP 將使其更多元豐富，助於拓展星國旅遊</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*77H2Aw-2S_Fijza9VAsnTQ.png" /><figcaption>About TIH</figcaption></figure><p>往下移動，針對不同的使用者，有各自的說明，提供一個大方向的概念，但一個前提，先註冊！最下方會出現一個很大的註冊按鈕</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V1RHrjaB8_SgLANCQOXGdg.png" /><figcaption>About TIH</figcaption></figure><blockquote><strong>🌟 探索開發者網站 — Getting Started</strong></blockquote><p><strong>點選 Getting Started</strong>，會出現申請的程序及註冊帳戶(Business/Developer account)之間的差異，Business account 可以提供更多的服務給使用者，如擬定旅遊計畫等。若是申請 Developer account 則只需讀到第二點就可以了(橘色框框的部分)。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wWgPZl1x3SAHUVc8OOkJ1A.png" /><figcaption>Getting Started</figcaption></figure><blockquote><strong>🌟 探索開發者網站 — API Guides</strong></blockquote><p><strong>點選 API Guides</strong>，會出現各個分類的 API 文件</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oqD34Fl5uXzspJRb5ZKb1Q.png" /><figcaption>API Guildes</figcaption></figure><p>例如：API User Guide — Content，進去後看第一段說明，很明確地指出內容分成兩大點：如何<strong>提供</strong>資料內容給TIH以及<strong>使用</strong>現有的資料內容<br>均有詳細的介紹及範例，篇幅也不會太冗長。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PBtvI8x1KLLd_a71rNE1wg.png" /><figcaption>頁面上方</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iRmJNcktCd1fcax_QMvZjg.png" /><figcaption>頁面下方</figcaption></figure><blockquote><strong>🌟 探索開發者網站 — API Products</strong></blockquote><p><strong>點選 API Products</strong>，會出現 <strong>API 的分類</strong>，點進去會在拆分成相關的各個小項目</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HrTwNFdRnnXktySWbrfwfA.png" /><figcaption>API Products</figcaption></figure><p>例如：點選 Content User，會看到一系列分類好的 API 連結及說明</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GsBTHjZ_ieO8gJkpZbimQw.png" /><figcaption>Content User</figcaption></figure><h3>取得JSON</h3><p>實際點選一個 API - Search Accommodation By Keyword or UUIDs</p><p>進去後，會看到第一個欄位是 Resource URL，是 base URL，就是 API 網址的前面固定的部分</p><p>往下的欄位會變成參數跟 Resource URL ，用<strong> ?</strong> 隔開，組成 API 完整的網址，參數包含關鍵字、過濾特定來源、排序、筆數等，至少需填寫有 require 的部分。(這裡示範是選 searchType: keyword，searchValue: city)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KMbAcMIEZnUuouJzjarOig.png" /></figure><p>移到網頁下方，<strong>輸入API Key</strong>，就可<strong>按下 SEND</strong> 發送到 server</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Xs8Bxh7U_BITQ5_tBUulBA.png" /></figure><p>之後可以在 <strong>Response</strong> 看到 <strong>HTTP code</strong> ，若是200就是請求有效，其餘可參考下方說明。</p><p>點到右邊的 <strong>cURL</strong> 在最後一行可以看到完整的網址</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sh-1_TC6dB_wjPRCMn0imQ.png" /><figcaption>Response</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*exgnZQ78ExP-WryKU2Z7Bg.png" /><figcaption>cURL</figcaption></figure><blockquote><strong>🌟 Postman、 JSON Editor Online 登場</strong></blockquote><p><a href="https://www.postman.com/">Postman: The World&#39;s Leading API Platform | Sign Up for Free</a></p><p>把 <strong>API 網址</strong>及<strong> API Key</strong> 輸入 <strong>Postman</strong>，就可以<strong>取得完整的 JSON</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fa-nelNUT2ufJUvzYaPlmw.png" /></figure><p>把 JSON 複製出來，放在<strong> JSON Editor Online</strong> 也可以，會更容易看懂它的架構一些</p><p><a href="https://jsoneditoronline.org/">JSON Editor Online</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PVE8MxRjev1rRMjwhEB0uQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xEJ8yuHK72pQ2acULV6lzQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sRjwsqXaxvn4bEqHMhbLdw.png" /></figure><p>之後就可以開始解析 JSON了！</p><h3>解析 JSON</h3><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-swift-4-%E7%9A%84-jsondecoder-%E5%92%8C-codable-%E8%A7%A3%E6%9E%90-json-%E5%92%8C%E7%94%9F%E6%88%90%E8%87%AA%E8%A8%82%E5%9E%8B%E5%88%A5%E8%B3%87%E6%96%99-ee793622629e">利用 JSONDecoder 把 JSON 轉換成自訂型別的資料</a></p><blockquote><strong>🌟 有些項目只出現一半</strong></blockquote><p>解析 JSON 只需解析<strong>有用到的項目</strong>即可，<strong>APP</strong> 需要<strong>用到哪</strong>裡就<strong>解到哪</strong>裡就好。</p><p>特別需要注意到是：它的 JSON 沒有長得很工整。<br>記得在解析 JSON 時，若是一個項目有時出現，有時消失，那就加上問號，讓它變成 optional 就好。<br>但若是只出現一半呢？<strong>冒號前面(Key)有東西，冒號後面(Value)有時有東西，有時是空的</strong>。<br>例如它的 image 項目，有時來源是 uuid，有時是 url，有時又整個是空的。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iBQT1Tzjd_A6NLLe65EKug.png" /><figcaption>來源是 uuid</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xEFpdV7q5HH0t7SfbEPCHw.png" /><figcaption>來源是 url</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*3hbiL5SqohFLj293cUiubA.png" /><figcaption>empty</figcaption></figure><p>這裡的做法是<strong>把它們都寫成 String</strong></p><p>記住 <strong>String 很特別，它可以是空字串，還是字串！</strong></p><p>解析寫成型別 struct，只有用到 API Get，只需繼承 Decodable ：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/738/1*iQw6c_PUnVxjSQx6m_VIdw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/738/1*JAtjzPB54hKXd3X19oHF3w.png" /></figure><blockquote><strong>🌟 uuid 取得影像</strong></blockquote><p>利用 url 串接圖片的 API 很簡單，照課堂上的方式做就可以得到影像。<br>那 uuid 呢？仔細檢視 TIH website，會在 API Products &gt; Media User 的最下方發現可用 uuid 取得媒體的 API</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zcVbCxszXorlfQYF64Rueg.png" /></figure><p>之後就可以利用<strong>網址</strong>加上 <strong>uuid </strong>以及<strong>API Key</strong>，去取得影像。</p><p>可以參考：</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/37-%E9%9A%A8%E6%A9%9F%E5%9C%96%E7%89%87api-%E9%80%B2%E9%9A%8E%E7%89%88uipickervier-c990b5ed2309">#37 隨機圖片API ＆進階版 UIPickerVier</a></p><p><strong>作業來源：</strong></p><p><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/19-%E4%B8%B2%E6%8E%A5%E7%AC%AC%E4%B8%89%E6%96%B9-api-%E8%A7%A3%E6%9E%90-json-%E8%B3%87%E6%96%99%E9%A1%AF%E7%A4%BA-f1556e84daec">#19 串接第三方 API，解析 JSON 資料，轉換成自訂型別顯示</a></p><p><em>希望這篇文章可以幫到正在學習 API 的你，減少一些卡關的時間。</em></p><p>後兩篇將介紹 TIH API 應用在 APP 上實作的部分：</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/39-%E4%B8%B2%E6%8E%A5-api-tableviewcontroller-collectionview-%E8%88%87-prepare-%E5%82%B3%E9%81%9E%E8%B3%87%E6%96%99-cbaa53c25dec">#39 串接 TIH API - TableViewController, CollectionView 與 prepare 傳遞資料</a></li><li><a href="https://medium.com/@chiayenlin_31230/40-%E4%B8%B2%E6%8E%A5-tih-api-present-shouldperformsegue-alert-prepare-b9059d112bda">#40 串接 TIH API - present, shouldPerformSegue, alert &amp; prepare</a></li></ul><p>GitHub：</p><p><a href="https://github.com/Ryan-CY/TIH-API-via-prepare">GitHub - Ryan-CY/TIH-API-via-prepare</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=44c4d4099234" width="1" height="1" alt=""><hr><p><a href="https://medium.com/peter-pan-swift-ios-class/%E4%B8%B2%E6%8E%A5-api-tih-%E4%BB%8B%E7%B4%B9-44c4d4099234">#38 串接 TIH API - TIH 介紹</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[#37 隨機圖片API ＆進階版 UIPickerVier]]></title>
            <link>https://medium.com/peter-pan-swift-ios-class/37-%E9%9A%A8%E6%A9%9F%E5%9C%96%E7%89%87api-%E9%80%B2%E9%9A%8E%E7%89%88uipickervier-c990b5ed2309?source=rss-b5b0c3dc8e10------2</link>
            <guid isPermaLink="false">https://medium.com/p/c990b5ed2309</guid>
            <dc:creator><![CDATA[CY’s Programming Journey]]></dc:creator>
            <pubDate>Wed, 15 Mar 2023 09:53:17 GMT</pubDate>
            <atom:updated>2023-06-26T06:23:22.330Z</atom:updated>
            <content:encoded><![CDATA[<p>繼上一回的作業練習了<strong>串接文字API</strong>及UIPickerView基礎練習；</p><p>這次練習<strong>串接圖片API，</strong>共有<strong>兩種</strong>方式：</p><blockquote>1.<em> </em><strong><em>用一般 coding 顯示API圖片</em></strong><em><br></em>2.<em> </em><strong><em>用第三方套件 kingfisher 顯示API圖片</em></strong></blockquote><p>另外，也包含了<strong>進階題UIPickerView</strong>：</p><blockquote>1. <strong><em>點選畫面後顯示 Picker View</em></strong></blockquote><blockquote>2.<strong><em> Picker View 的上方加入包含完成 &amp; 取消 button 的 bar，按下完成時更新畫面的內容</em></strong></blockquote><blockquote>3.<strong><em> 顯示多欄的 Picker View，第二欄的 picker view 隨著第一欄而變化</em></strong></blockquote><p>其他功能</p><blockquote><strong>等待畫面時，顯示 UIActivityIndicatorView</strong></blockquote><blockquote><strong>等待畫面時，顯示預設圖片</strong></blockquote><p><strong>作業來源：</strong></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/128-%E9%9A%A8%E6%A9%9F%E5%9C%96%E7%89%87-api-692ce98d6b1e">#128 隨機圖片 API</a></li><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/97-uipickerview-%E7%B7%B4%E7%BF%92-42d71c5e298c">#97 UIPickerView 練習</a></li></ul><h3>APP畫面：</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G1nCt9_W9yqnWvlre-6Qag.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RkZV6lDWdMEV4ywBdnBSmg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Sjl9tiL62wk8g9Kk3RDrqQ.png" /><figcaption>左：起始畫面；中：loading畫面；右：呈現API影像</figcaption></figure><h3>UIPikerView</h3><p>基礎版UIPickerView可以參考上一篇：</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/36-%E7%94%A8uipickerview-uitapgesturerecognizer%E9%81%B8%E6%93%87%E8%81%96%E7%B6%93%E7%B6%93%E6%96%87-c0811664cf46">#36 用 UIPickerView, UITapGestureRecognizer串接聖經經文API</a></p><p><strong>這裡說明進階版不同的部分：</strong></p><p>點選畫面後，UIPickerView才會出現，並搭配著<strong>按鈕</strong>去<strong>取消</strong>與<strong>選取</strong></p><p>新增UIToolbar在畫面外(放在exit底下)，並拉好 IBOutlet；<br>UIPickerView 也是一樣的方式先新增跟拉好</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/678/1*EMUsVtTzNE4ox3R0zFlNUA.png" /><figcaption>UIToolbar</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/202/1*ZGSxeK8uwm8NfcT2LeKrJA.png" /><figcaption>放在exit底下</figcaption></figure><p>再新增一個TextField放在View裡，在 <strong>func</strong> viewDidLoad() 裡利用程式碼</p><pre>optionTextField.inputView = optionPickerView<br>optionTextField.inputAccessoryView = optionToolBar</pre><p>讓UIPickerView跟UIToolbar取代觸發時會跳出的鍵盤</p><p>用 .becomeFirstResponder( ) 去觸發 TextField</p><pre>optionTextField.becomeFirstResponder()</pre><p>這裡是用<strong>點兩下</strong>畫面<strong>觸發顯示UIPickerView跟UIToolbar</strong>，所以寫在 UITapGestureRecognizer 的 function 裡</p><pre>    func tapToSelect() {<br>        let tap = UITapGestureRecognizer()<br>        tap.numberOfTapsRequired = 2<br>        tap.addTarget(self, action: #selector(showPickerVier))<br>        pictureImageView.isUserInteractionEnabled = true<br>        pictureImageView.addGestureRecognizer(tap)<br>        <br>    }<br>    <br>    @objc func showPickerVier() {<br>        optionTextField.becomeFirstResponder()<br>        optionTextField.isHidden = true<br>    }</pre><p>關於 UITapGestureRecognizer 也可以參考上一篇</p><p>仔細觀察，Toolbar 中間其實有三個 item</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/478/1*N4vZlPKkAI3AFo_ei4yeNg.png" /></figure><p>中間的item，Fixed Space Bar Button Item 是固定兩個item之間的距離</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/675/1*xch2n-IGvYkMGb36G2AwZA.png" /></figure><p>記得 Cancel Button 跟 Get Image Button 也要拉 IBAction，去定義按下時要做的事。例如：收鍵盤</p><pre>view.endEditing(true)</pre><p><strong>UIPickerView 裡的資料設定</strong></p><p>第一個欄位(component = 0)選取的資料不會出現在第二個欄位(component = 1)，也就是不會選到一樣的選項</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/295/1*3eIxTs-hRFhgrMwg8sQN_A.gif" /><figcaption>PickerView不重複選取</figcaption></figure><p>撰寫程式的概念是：<br>在 ViewController 裡宣告兩組 array，其中一組包含所有資料，另一組是空 array，搭配移除 array 資料( .remove(at: ) )，與存入資料去改變第二組欄位</p><pre>        if component == 0 {<br>            secondOptions = firstOptions<br>            let firstSelected = pickerView.selectedRow(inComponent: 0)<br>            secondOptions.remove(at: firstSelected)<br>            pickerView.selectRow(2, inComponent: 1, animated: true)<br>            pickerView.reloadComponent(1)<br>        } else if component == 1 {<br>            pickerView.reloadComponent(1)<br>        }</pre><p>特別注意，因為第二組欄位會因第一組欄位而改變，所以也必須被 reload，不然第二組欄位選取的資料會不正確。</p><h3>串接API，顯示選取PickerView後的畫面</h3><h4>試了兩種方式串接API來顯示圖片</h4><p>✨ <strong>使用一般coding</strong><br>✨ <strong>使用第三方套件(kingfisher)</strong></p><p><a href="https://developer.apple.com/documentation/xcode/adding-package-dependencies-to-your-app">Adding package dependencies to your app | Apple Developer Documentation</a></p><h4>APP GIF呈現比較：</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/295/1*afbS-u6nbGmx-ZFcyiMLvw.gif" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/295/1*Oa5QmtM4kr7sOtGgo-XjrQ.gif" /><figcaption>左圖：一般coding；右圖：kingfisher</figcaption></figure><p>使用起來幾乎一樣，但用一般 coding 撰寫程式的可以一直按 GetImage 去取得同樣條件下不同的圖片；但用kingfisher的，在同樣條件下，會一直呈現同樣的照片，仔細翻閱文件可以發現原因</p><p><a href="https://github.com/onevcat/Kingfisher">GitHub - onevcat/Kingfisher: A lightweight, pure-Swift library for downloading and caching images from the web.</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/885/1*n3vgljqeK3qw8-C36kC1Qw.png" /><figcaption>from kingfisher documents</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DG3d5-PqgE0VwaZ8--pVdg.png" /><figcaption>from kingfisher documents</figcaption></figure><p>它抓過的資料都會暫存起來，讓程式更有效率</p><h4>一般coding的串接API程式碼：</h4><pre>    func fetchImage() {<br>        processIndicator.startAnimating()<br>        optionTextField.isHidden = true<br>        pictureImageView.image = UIImage(systemName: &quot;sailboat&quot;)<br>        if let randomURL = URL(string: &quot;https://loremflickr.com/350/400/\(firstOption),\(secondOption)/all&quot;) {<br>            print(randomURL.description)<br>            URLSession.shared.dataTask(with: randomURL) { data, response, error in<br>                if let data {<br>                    let image = UIImage(data: data)<br>                    DispatchQueue.main.async {<br>                        <br>                        self.pictureImageView.image = image<br>                        self.pictureImageView.contentMode = .scaleAspectFill<br>                        self.processIndicator.stopAnimating()<br>                    }<br>                }<br>            }.resume()<br>        }<br>    }</pre><h4>用kingfisher串接API的程式碼：</h4><pre>    func fetchImage() {<br>        optionTextField.isHidden = true<br>        if let randomURL = URL(string: &quot;https://loremflickr.com/350/400/\(firstOption),\(secondOption)/all&quot;) {<br>            print(randomURL.description)<br>          <br>            //顯示未知進度<br>            pictureImageView.kf.indicatorType = .activity<br>            //等待載入影像時，顯示placeholder設定的圖示<br>            let processorRoundCorner = RoundCornerImageProcessor(cornerRadius: 15)<br>            //在影像上覆蓋一層自訂顏色的透明色調<br>            let processorOverLay = OverlayImageProcessor(overlay: .systemOrange)<br>            <br>            pictureImageView.kf.setImage(<br>                with: randomURL,<br>                placeholder: UIImage(systemName: &quot;sailboat&quot;),<br>                options: [<br>                    .processor(processorRoundCorner),<br>                    .processor(processorOverLay)<br>                ])<br>        }<br>    }</pre><p>kingfisher的文件寫得非常清楚，還搭配範例，很適合初學者練習第三方程式與閱讀其文件。</p><h3>UIActivityIndicatorView</h3><p>有時網路比較慢或是在載入較大檔案時會花上幾秒時間，可以顯示 UIActivityIndicatorView 去讓使用者知道現在APP的狀態。</p><p>關鍵的三行程式碼：</p><p>開始運作：</p><pre>processIndicator.startAnimating()</pre><p>停止運作：</p><pre>processIndicator.stopAnimating()</pre><p>停止運作時自動隱藏：</p><pre>processIndicator.hidesWhenStopped = true</pre><h3>GitHub:</h3><h4>一般coding</h4><p><a href="https://github.com/Ryan-CY/random-image-API-practice">GitHub - Ryan-CY/random-image-API-practice</a></p><p><strong>使用第三方套件kingfisher</strong></p><p><a href="https://github.com/Ryan-CY/-kingfisher-random-image-API-practice">GitHub - Ryan-CY/-kingfisher-random-image-API-practice: with kingfisher</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c990b5ed2309" width="1" height="1" alt=""><hr><p><a href="https://medium.com/peter-pan-swift-ios-class/37-%E9%9A%A8%E6%A9%9F%E5%9C%96%E7%89%87api-%E9%80%B2%E9%9A%8E%E7%89%88uipickervier-c990b5ed2309">#37 隨機圖片API ＆進階版 UIPickerVier</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[#36 用 UIPickerView, UITapGestureRecognizer串接聖經經文API]]></title>
            <link>https://medium.com/peter-pan-swift-ios-class/36-%E7%94%A8uipickerview-uitapgesturerecognizer%E9%81%B8%E6%93%87%E8%81%96%E7%B6%93%E7%B6%93%E6%96%87-c0811664cf46?source=rss-b5b0c3dc8e10------2</link>
            <guid isPermaLink="false">https://medium.com/p/c0811664cf46</guid>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[CY’s Programming Journey]]></dc:creator>
            <pubDate>Mon, 06 Mar 2023 18:37:28 GMT</pubDate>
            <atom:updated>2023-06-05T06:46:34.431Z</atom:updated>
            <content:encoded><![CDATA[<p>在尋找適合練習的API get時，忽然看到有Bible的API，查詢經文需要知道聖經的書卷名稱(例如馬太福音、哥林多前書等等)、第幾章以及第幾節，若再加上不同的翻譯版本，則有四個變數，非常適合用來練習UIPickerView。</p><p>搭配UITapGestureRecognizer，輕拍螢幕時串接API更新顯示經文</p><h3>作業來源：</h3><p><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/97-uipickerview-%E7%B7%B4%E7%BF%92-42d71c5e298c">#97 UIPickerView 練習</a></p><h3>APP畫面：</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/295/1*QWl2nxMQ_U3FCZGS_3iXeA.gif" /><figcaption>GIF</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*npxdETk5_tB4olPpzgl9xg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2LEai_mz_8Gth0OqyEOH5A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gYozW4Bo11LpbaTa7JFfyA.png" /></figure><h4>首先，先找到聖經經文API的文件：</h4><p>仔細觀察它的參數有哪些</p><p><a href="https://bible-api.com/">bible-api.com</a></p><h4>解析 JSON：</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bGgvtNEjngqkswRMXD246Q.png" /></figure><p>也可以用Postman解析JSON，但在上傳資料時才會真正顯出它的功用</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wNB6ewxOTxIPzlwawldkeg.png" /><figcaption>Postman</figcaption></figure><p>不需要全部寫進 struct，只寫需要的項目就好</p><pre>struct BibleVerse: Decodable {<br>    let reference: String<br>    let text: String<br>    let translation_id: String<br>}</pre><h4>建立資料：</h4><p>透過API文件，確認可以使用文章開頭所說的四個項目：</p><p>✨ 書卷名稱<br>✨ 第幾章<br>✨ 第幾節<br>✨ 翻譯版本</p><p>去組成網址，取得對應的經文。</p><p>聖經的書卷很多，加上對應的章節，資料會很龐大，所以先用四福音(馬太福音、馬可福音、路加福音跟約翰福音)的部分來練習。</p><p>為了讓UIPickerView有依循的資料：第一步是建立資料的struct</p><pre>struct Bible {<br>    let bookName: String<br>    let chapters: [Chapter]<br>}<br><br>struct Chapter {<br>    let chapterNo: String<br>    let verses:[String]<br>}</pre><p>然後依照struct把資料用array具體化出來：</p><p>跟UITableVIew做法非常相似</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zf15b6n2-TCRIoA7Ix5NyQ.png" /></figure><p>有些書卷的章節有80節這麼多，身為IT新鮮人就試著寫程式來解決吧！</p><p>在playground寫了一個迴圈幫我打好數字</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9bLzjg6iYoO9ez7HYKhJkg.png" /></figure><p>翻譯版本則自成一個array</p><pre>let translation = [&quot;web&quot;,&quot;bbe&quot;,&quot;kjv&quot;]</pre><h3>UIPikerView ：</h3><p>UIPikerView 的 <strong>dataSource</strong> 跟 <strong>delegate</strong> 都要連到 Controller 才會正常運作。</p><p>UIPikerView就是可以上下滑動選則的滾輪(wheel)，程式寫法跟UITableView 很像，所以也要讓所在的 Controller 繼承UIPickerViewDataSource，其底下的<strong>兩個 function </strong>會<strong>決定外觀</strong></p><p><strong>Component</strong>：決定有幾個 wheel<br><strong>row</strong>：決定一個 Component 裡有多少選項</p><pre>extension BibleViewController: UIPickerViewDataSource {<br>    func numberOfComponents(in pickerView: UIPickerView) -&gt; Int {<br>        4<br>    }<br>    <br>    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -&gt; Int {<br>        <br>        if component == 0 {<br>           return bibles.count<br>        } else if component == 1 {<br>            let bookRow = pickerView.selectedRow(inComponent: 0)<br>            return bibles[bookRow].chapters.count<br>        } else if component == 2 {<br>            let bookRow = pickerView.selectedRow(inComponent: 0)<br>            let chapterRow = pickerView.selectedRow(inComponent: 1)<br>            return bibles[bookRow].chapters[chapterRow].verses.count<br>        } else {<br>            return translation.count<br>        }<br>    }<br>}</pre><p>說明：</p><p>Component共有4個，跟array一樣，從左至右分別是 0,1,2,3<br>row則對應資料上array的變化</p><p>Controller 繼承 UIPickerViewDelegate，其底下<strong>兩個function</strong>決定<strong>顯示的文字</strong>及<strong>點選時wheel要做的反應</strong></p><pre>extension BibleViewController: UIPickerViewDelegate {<br>    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -&gt; String? {<br>        <br>        if component == 0 {<br>            return bibles[row].bookName<br>        } else if component == 1 {<br>            let bookRow = pickerView.selectedRow(inComponent: 0)<br>            return bibles[bookRow].chapters[row].chapterNo<br>        } else if component == 2 {<br>            let bookRow = pickerView.selectedRow(inComponent: 0)<br>            let chapterRow = pickerView.selectedRow(inComponent: 1)<br>            return bibles[bookRow].chapters[chapterRow].verses[row]<br>        } else {<br>            return translation[row]<br>        }<br>    }<br>    <br>    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {<br><br>        if component == 0 {<br>            pickerView.selectRow(6, inComponent: 1, animated: true)<br>            pickerView.selectRow(13, inComponent: 2, animated: true)<br>        } else if component == 1 {<br>            pickerView.selectRow(13, inComponent: 2, animated: true)<br>        }<br>        pickerView.reloadAllComponents()<br>        <br>        let bookRow = pickerView.selectedRow(inComponent: 0)<br>        let chapterRow = pickerView.selectedRow(inComponent: 1)<br>        let verseRow = pickerView.selectedRow(inComponent: 2)<br>        let translationRow = pickerView.selectedRow(inComponent: 3)<br>        <br>        let bookName = bibles[bookRow].bookName<br>        let chapter = bibles[bookRow].chapters[chapterRow].chapterNo<br>        let verse = bibles[bookRow].chapters[chapterRow].verses[verseRow]<br>        let translationVersion = translation[translationRow]<br>        <br>        self.bookName = bookName<br>        self.chapter = chapter<br>        self.verse = verse<br>        self.translationVersion = translationVersion<br>    }<br>    <br>    func pickerView(_ pickerView: UIPickerView, widthForComponent component: Int) -&gt; CGFloat {<br>        if component == 0 {<br>            return 120<br>        } else if component == 1, component == 2 {<br>            return 30<br>        } else {<br>            return 70<br>        }<br>    }<br>}</pre><p>說明：</p><pre>func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -&gt; String?</pre><p>依照資料去設定要wheel顯示的字樣</p><pre>    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {<br><br>        if component == 0 {<br>            pickerView.selectRow(6, inComponent: 1, animated: true)<br>            pickerView.selectRow(13, inComponent: 2, animated: true)<br>        } else if component == 1 {<br>            pickerView.selectRow(13, inComponent: 2, animated: true)<br>        }<br>        pickerView.reloadAllComponents()<br>        <br>        let bookRow = pickerView.selectedRow(inComponent: 0)<br>        let chapterRow = pickerView.selectedRow(inComponent: 1)<br>        let verseRow = pickerView.selectedRow(inComponent: 2)<br>        let translationRow = pickerView.selectedRow(inComponent: 3)<br>        <br>        let bookName = bibles[bookRow].bookName<br>        let chapter = bibles[bookRow].chapters[chapterRow].chapterNo<br>        let verse = bibles[bookRow].chapters[chapterRow].verses[verseRow]<br>        let translationVersion = translation[translationRow]<br>        <br>        self.bookName = bookName<br>        self.chapter = chapter<br>        self.verse = verse<br>        self.translationVersion = translationVersion<br>    }</pre><p>function UIPickerVew didSelectRow 決定點選時wheel的反應。</p><p>可能引起APP 閃退的狀況：</p><p><strong>✨狀況一：</strong></p><p>pickerView.reloadAllComponents()：顯示更新，要寫在pickerView.selectRow之後，不然可能會忽然閃退。</p><p>可是為什麼有些project上的順序是相反的還是可以運作，我猜想是因為資料比較單純變化較少，一旦資料變得複雜一些就可能會閃退。</p><p><strong>✨狀況二：</strong></p><p>當點選row時，可能會使children component變化，假設children component只有6個row，意即row只有0到5，若設定點選後row=6則也會閃退。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ficAc00NH1gSnoUXb06ULw.png" /><figcaption>APP crash</figcaption></figure><h3>串接API GET：</h3><pre>    var bookName = &quot;Matthew&quot;<br>    var chapter = &quot;1&quot;<br>    var verse = &quot;1&quot;<br>    var translationVersion = &quot;web&quot;<br>    <br>    func fetchBibleVerse(bookName: String, chapter: String, verse: String) {<br>        <br>        let urlString = &quot;https://bible-api.com/\(bookName)\(chapter):\(verse)?translation=\(translationVersion)&quot;<br>        <br>        if let url = URL(string: urlString) {<br>            //var request = URLRequest(url: url)<br>            URLSession.shared.dataTask(with: url) { data, response, error in<br>                if let data {<br>                    let decoder = JSONDecoder()<br>                    do {<br>                        let result = try decoder.decode(BibleVerse.self, from: data)<br>                        DispatchQueue.main.async {<br>                            self.verseLabel.text = result.text<br>                            self.bookNameLabel.text = result.reference<br>                            self.versionLabel.text = &quot;(\(result.translation_id))&quot;<br>                        }<br>                    } catch {<br>                        print(error)<br>                    }<br>                }<br>            }.resume()<br>        }<br>    }</pre><p>說明：</p><p>這次的作業，是把網址的參數用變數來取代，而在UIPickerView轉動時，又可以改變變數，最後再用手勢輕點去取得經文。</p><p>特別注意：URLSession的部分，最後一定要加上.resume( )去實際執行程式，不然不會有作用，這部分是在background thread執行。</p><p>跟畫面有關的程式一定要在main thread執行，所以會需要加入DispatchQueue.main.async { }，讓裡面的程式在main thread裡執行。</p><h3>UITapGestureRecognizer：</h3><p>這裡有兩個做法：</p><p>作法一：</p><p>直接加一個UITapGestureRecognizer在所要作用的object上(例如ImageView)，然後拉IBAction function，裡面輸入輕點後要觸發的事。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0Z978VijX5EHikuQCAvBPQ.png" /></figure><p>但這個做法有一個缺點，當要做用的object改變時(如從ImageView變成view)時，整個IBAction跟UITapGestureRecognizer要刪除重做。</p><p>做法二：</p><p>不需要新增UITapGestureRecognizer，只需輸入程式碼</p><pre>    @objc func refrech() {<br>        fetchBibleVerse(bookName: bookName, chapter: chapter, verse: verse)<br>    }<br>    <br>    func tapToRefresh() {<br>        let tapGesture = UITapGestureRecognizer()<br>        tapGesture.numberOfTapsRequired = 2<br>        tapGesture.addTarget(self, action: #selector(refrech))<br>        backgroundImageView.isUserInteractionEnabled = true<br>        backgroundImageView.addGestureRecognizer(tapGesture)<br>    }</pre><p>說明：</p><pre>tapGesture.addTarget(self, action: #selector(refrech))</pre><p>輕點之後要觸發的事。</p><p>action之後只能接受@objc的function，乾脆宣告一個refresh的@objc function，然後把要觸發的事包進去。</p><pre>backgroundImageView.addGestureRecognizer(tapGesture)</pre><p>把要輕點的object直接加進手勢裡</p><pre>backgroundImageView.isUserInteractionEnabled = true</pre><p>記得要開啟isUserInteractionEnable</p><h3>GitHub：</h3><p><a href="https://github.com/Ryan-CY/UIPickerView-TapGesture-API-get-Practice">GitHub - Ryan-CY/UIPickerView-TapGesture-API-get-Practice</a></p><p>這次的作業著重在UIPickerView跟UITapGestureRecognizer的練習。<br>聖經的API幾乎都是文字，沒有太多的變化，API再找其他的來練習。</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c0811664cf46" width="1" height="1" alt=""><hr><p><a href="https://medium.com/peter-pan-swift-ios-class/36-%E7%94%A8uipickerview-uitapgesturerecognizer%E9%81%B8%E6%93%87%E8%81%96%E7%B6%93%E7%B6%93%E6%96%87-c0811664cf46">#36 用 UIPickerView, UITapGestureRecognizer串接聖經經文API</a> was originally published in <a href="https://medium.com/peter-pan-swift-ios-class">彼得潘的 Swift iOS / Flutter App 開發教室</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[# 35 eBook of Jewel Changi Airport 星耀樟宜 電子書-程式版]]></title>
            <link>https://medium.com/peter-pan-swift-ios-class/35-ebook-of-jewel-changi-airport-%E6%98%9F%E8%80%80%E6%A8%9F%E5%AE%9C-%E9%9B%BB%E5%AD%90%E6%9B%B8-%E7%A8%8B%E5%BC%8F%E7%89%88-8e7cbb990b75?source=rss-b5b0c3dc8e10------2</link>
            <guid isPermaLink="false">https://medium.com/p/8e7cbb990b75</guid>
            <dc:creator><![CDATA[CY’s Programming Journey]]></dc:creator>
            <pubDate>Sat, 11 Feb 2023 14:48:01 GMT</pubDate>
            <atom:updated>2023-03-25T09:16:28.028Z</atom:updated>
            <content:encoded><![CDATA[<h4>Collection View, Table View &amp; 資料傳遞</h4><h4>作業來源：</h4><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/53-collection-view-%E7%85%A7%E7%89%87%E7%89%86-c03f156de0c">#53 照片牆(Grid Photo Wall)</a></li><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/121-%E6%B0%B4%E5%B9%B3%E6%8D%B2%E5%8B%95%E7%9A%84-collection-view-eb679cb5fbaf">#121 水平捲動的 collection view</a></li></ul><p>複習完 Collection View 思考要如何完成相關作業，忽然想到在文組班時做的電子書有用到照片牆，但當時是用不寫程式的方法，現在拿來重新製作成程式版。</p><p><em>文組班時的電子書作業作品：</em></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/5-storyboard-ebook-of-jewel-changi-airport-%E6%98%9F%E8%80%80%E6%A8%9F%E5%AE%9C-%E9%9B%BB%E5%AD%90%E6%9B%B8-c5bb19f3387">#5 Storyboard eBook of Jewel Changi Airport 星耀樟宜 電子書</a></p><h4>做到的部分：</h4><blockquote><strong>照片牆(Grid Photo Wall)</strong></blockquote><p><strong><em>🌟 </em>版本 2: 程式版，使用 collection view controller</strong></p><p>點選照片後，切換到下一頁顯示大張圖片</p><p><strong><em>🌟 </em>版本 3: 在 view controller 上加入 collection view</strong></p><blockquote><strong>水平捲動的 collection view</strong></blockquote><p>🌟 <strong>進階版</strong></p><p><strong>分頁功能，一頁顯示一個 cell</strong></p><p>大張圖可以水平滑動瀏覽</p><blockquote><strong>Table View</strong></blockquote><p>🌟 <strong>客製 cell 顯示表格的內容</strong></p><p>搭配 as! , as? 轉型</p><p>🌟 <strong>點選 cell 後可到下一頁顯示詳細資訊</strong></p><p><strong>🌟 cell 類別裡定義設定內容的 function</strong></p><p>在 Table View 的 cell 裡設定 func updateUI( ) 使程式分散一些</p><blockquote><strong>頁面間資料傳遞</strong></blockquote><p>🌟 <strong>在下一頁 controller 定義 property 及 init</strong></p><p>利用 IBSegueAction func 傳遞資料</p><h4>APP畫面：</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/296/1*Ezb74dZX0vf3qZBCVfl_iw.gif" /><figcaption>GIF</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e674fJR3PE29C5JeGpFxjw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T9jLxjEg_yAzDKDjBqFnHA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XIIng8tfMHHpFvKZ8nmVMg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RpyNtDTI9yyKGF2gVAZrYQ.png" /></figure><h4>作業摘要：</h4><p>storyboard 畫面，從文組班時期是這樣子</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4xfMZ3Oy5qk-ByVwTFzPUQ.png" /></figure><p>在彼得潘班變成這樣子</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lT1srYy-FaP3d5KA2f6RtQ.png" /></figure><blockquote><strong>Collection View</strong></blockquote><p>基本上跟 Table View 作法非常類似，主要可以分成三種設計：</p><p>第一種：照片牆，就是IG上可以看到到配置（Collection View Controller）<br>第二種：水平滑動水平方向的多張照片（View Controller + Collection View）<br>第三種：一頁(一個 Controller)一張大圖片(一個 cell)滑動（View Controller + Collection View）</p><p>第二種跟第三種幾乎一樣作法，這次作業用了第一種跟第三種作法。</p><p><strong>🌟 照片牆</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4b_XhNqp06DqAM8ps4CwyQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xEu0NGWHCHAb4vQFvbx8Pg.png" /></figure><p>這裡是新增一個 <strong>Collection View Controller</strong>，注意 Size Inspector， cell 的間距以及大小，如下圖橘色框框，將左右呈現出來的樣子</p><p>注意：因為未用到 AutoLayout，所以 <strong>Estimate Size 要選 None</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/524/1*qYBF19RCsmTIEWLd55anbA.png" /></figure><p>再來是注意滑動方向，在 Attributes Inspector</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/524/1*3keUfxpq8CNKuIzo7oZtyQ.png" /></figure><p>跟 Table View 一樣，用 array 建立資料。程式也幾乎一樣，只是Table View 的 row，在 Collection View 變成了 item</p><p>一樣是用三個 function，去決定 <strong>section 數量</strong>，i<strong>tem 數量</strong>，<br>以及 <strong>cell 內容</strong></p><pre>    override func numberOfSections(in collectionView: UICollectionView) -&gt; Int {<br>        // #warning Incomplete implementation, return the number of sections<br>        return 1<br>    }<br>    <br>    override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -&gt; Int {<br>        // #warning Incomplete implementation, return the number of items<br>        return jewelSpots.count<br>    }<br>    <br>    override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -&gt; UICollectionViewCell {<br>        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: &quot;\(GridCollectionViewCell.self)&quot;, for: indexPath) as! GridCollectionViewCell<br>        <br>        cell.GridImageView.image = UIImage(named: jewelSpots[indexPath.item].name)<br>        <br>        return cell<br>    }</pre><p><strong>🌟 一頁(一個 Controller)一張大圖片滑動</strong></p><p>在照片牆點選後，設計可以連到這個 Collecetion View，<br>然後可以水平滑動繼續瀏覽照片</p><p>作法是新增一個 View Controller，裡面放一個 Collection View，<br>注意： data source 及 delegate 在這裡要自己拉！所有的 Controller 跟 Cell 都要自訂型別並套用上去。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1020/1*U_wxv_6k17V-bYs8ajQ8VA.png" /><figcaption>一頁一張大圖的設定</figcaption></figure><p>因為會用自己定義的 cell ID，務必<strong>刪除</strong>兩行<strong>預設的程式碼</strong></p><pre>private let reuseIdentifier = &quot;Cell&quot;</pre><p>以及</p><pre>// Register cell classes<br>self.collectionView!.register(UICollectionViewCell.self, forCellWithReuseIdentifier: reuseIdentifier)</pre><p>再來是資料傳遞的程式碼部分，從上一頁(照片牆)傳到下一頁(顯示一張大圖可水平滑動瀏覽)：</p><p><strong><em>Step 1</em></strong>：在下一頁，新增所需要資料的同樣型別的屬性，並定義好 init</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MtSzDOhGJAEr7aHaWFcxMw.png" /></figure><p><strong><em>Step 2</em></strong>：在上一頁，定義 IBSegueAction func</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C_o0Pmxeh9Ic4PxmakDAmQ.png" /></figure><p>return 後面下一頁 Controller 的參數，對應著上一頁要傳到下一頁時產生的資料。</p><p><strong><em>Step 3</em></strong>：回到下一頁，這裡比較特別一些，下一頁是傳入另一個 Collection View 去顯示，結合接收到的資料，所以寫入 func <strong>cellForItemAt</strong> 去設定 cell 的內容</p><pre>extension OneViewController: UICollectionViewDataSource {<br>    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -&gt; Int {<br>        jewels.count<br>    }<br>    <br>    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -&gt; UICollectionViewCell {<br>        guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: &quot;\(OneCollectionViewCell.self)&quot;, for: indexPath) as? OneCollectionViewCell else {fatalError(&quot;dequeueReusableCell OneCollectionViewCell Failed&quot;)}<br>        <br>        let newIndex = (newItem + indexPath.item + jewels.count) % jewels.count<br>        <br>        cell.oneImageView.image = UIImage(named: jewels[newIndex].name)<br>        <br>        print(&quot;newItem:\(newItem), indexPath.item:\(indexPath.item), jewels.count:\(jewels.count), newIndex:\(newIndex)&quot;)<br>        return cell<br>    }<br>}</pre><p><strong><em>說明：</em></strong></p><pre>let newIndex = (newItem + indexPath.item + jewels.count) % jewels.count<br><br>cell.oneImageView.image = UIImage(named: jewels[newIndex].name)</pre><p>在第一行，這裡的 newIndex 會取代原本第二行的 jewel[ ] 中括號裡的indexPath.item。</p><p><strong><em>newItem</em></strong>：代表<strong>上一頁被點選的 cell 的 indexPath.item</strong>，型別是Int，代表被點選的照片，跟 array 一樣，第一張會是0，第二張會是1 ,以此類推。</p><p><strong><em>indexPath.item</em></strong>：這邊因為只會顯示一張大圖，開始即產生一個 item，item 跟 array 一樣從0開始算起，所以一開始的 indexPath.item 等於 0 ，隨著水平滑動瀏覽照片的增加而增加。</p><p><strong><em>jewels.count</em></strong>：資料的筆數，這裡是16。</p><p><strong><em>結果：</em></strong></p><p>透過常數 newIndex 的算式</p><pre>let newIndex = (newItem + indexPath.item + jewels.count) % jewels.count</pre><p>或是這樣（兩個算式差別在於商不一樣，餘數是一樣的）</p><pre>let newIndex = (newItem + indexPath.item) % jewels.count</pre><p>newIndex 都會等於<strong>上一頁的 indexPath.item</strong>，就會在下一頁顯示相同的照片。<br>而算式裡的 indexPath.item 是下一頁的，會隨瀏覽增加而增加，讓滑動照片時 newIndex 也跟著增加</p><pre>cell.oneImageView.image = UIImage(named: jewels[newIndex].name)</pre><p>隨著 newIndex 的增加，就會改變 array jewels 顯示照片的名稱，最終滑動時就會顯示下一張照片。</p><blockquote><strong>Table View</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*auxnhMCntVuU-OqvXiS42A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KEnefHCPZgSqiyZkXKyYlg.png" /></figure><p>Table View 的作法在前兩篇有介紹過。<br>這裡稍微提一下當資料 array 有兩層時，傳遞資料時的寫法，觀念跟剛剛Collection View 是一樣的，</p><p>第一層資料的型別：</p><pre>import Foundation<br><br>struct Shop {<br>    let name: String<br>    let attractions: [Attraction]<br>}</pre><p>第二層資料的型別：</p><pre>import Foundation<br><br>struct Attraction {<br>    let name: String<br>    let chineseName: String<br>    let photo: String<br>    let intro: String<br>    let location: String<br>}</pre><p><strong><em>Step 1</em></strong>：在下一頁，新增所需要資料的同樣型別的屬性，並定義好 init</p><pre>import UIKit<br><br>class DetailViewController: UIViewController {<br>    <br>    let shops: [Shop]<br>    let section: Int<br>    let row: Int<br>    <br>    init?(coder: NSCoder, shops: [Shop], section: Int, row: Int) {<br>        self.shops = shops<br>        self.section = section<br>        self.row = row<br>        super.init(coder: coder)<br>    }<br>    <br>    required init?(coder: NSCoder) {<br>        fatalError(&quot;init(coder:) has not been implemented&quot;)<br>    }<br>    <br>    @IBOutlet weak var detailImageView: UIImageView!<br>    @IBOutlet weak var detailNameLabel: UILabel!<br>    @IBOutlet weak var detailChineseLabel: UILabel!<br>    @IBOutlet weak var detailTextView: UITextView!<br>    @IBOutlet weak var locationLabel: UILabel!</pre><p><strong><em>Step 2</em></strong>：在上一頁，定義 IBSegueAction func，return 後面下一頁 Controller 的參數，對應著上一頁要傳到下一頁時產生的資料。</p><pre>    @IBSegueAction func showDetail(_ coder: NSCoder) -&gt; DetailViewController? {<br>        <br>        guard let row = tableView.indexPathForSelectedRow?.row else {return nil}<br>        <br>        let section = tableView.indexPathForSelectedRow?.section<br>        <br>        return DetailViewController(coder: coder, shops: shops, section: section!, row: row)<br>    }</pre><p>特別注意因為有兩層 array，所以會需要用到 section 的數值</p><pre>let section = tableView.indexPathForSelectedRow?.section</pre><p><strong><em>Step 3</em></strong>：回到下一頁，因為第一層的屬性原本就包含第二層的 array 型別，可以用來產生第二層的 array，如下</p><pre>let attraction = shops[section].attractions[row]</pre><p>最後，在讓傳回的資料，對應拉好的IBOutlet，及顯示出想要的樣式</p><pre>    override func viewDidLoad() {<br>        super.viewDidLoad()<br>        <br>        updateUI()<br>        configutation()<br>    }<br>    <br>    func updateUI() {<br>        let attraction = shops[section].attractions[row]<br>        <br>        detailImageView.image = UIImage(named: attraction.photo)<br>        detailNameLabel.text = attraction.name<br>        detailChineseLabel.text = attraction.chineseName<br>        detailTextView.text = attraction.intro<br>        locationLabel.text = attraction.location<br>        <br>        detailTextView.isEditable = false<br>    }<br>    <br>    func configutation() {<br>        detailNameLabel.frame = CGRect(x: 25, y: 100, width: 140, height: 44)<br>        detailNameLabel.numberOfLines = 0<br>        detailNameLabel.textAlignment = .center<br>        detailNameLabel.textColor = .orange<br>        detailNameLabel.font = .systemFont(ofSize: 18, weight: .semibold)<br>        <br>        detailChineseLabel.frame = CGRect(x: 180, y: 100, width: 140, height: 44)<br>        detailChineseLabel.textAlignment = .left<br>        detailChineseLabel.textColor = .orange<br>        detailChineseLabel.font = .systemFont(ofSize: 18, weight: .medium)<br>        <br>        detailImageView.frame = CGRect(x: 10, y: 150, width: 370, height: 300)<br>        detailImageView.contentMode = .scaleAspectFit<br>        <br>        detailTextView.frame = CGRect(x: 50, y: 480, width: 290, height: 190)<br>        detailTextView.font = .systemFont(ofSize: 16)<br>        detailTextView.backgroundColor = .clear<br>        <br>        locationLabel.frame = CGRect(x: 75, y: 720, width: 250, height: 30)<br>        locationLabel.textAlignment = .center<br>    }</pre><blockquote><strong>cell 類別裡定義設定內容的 function</strong></blockquote><p>在 Table View 的 cell 裡製作 function，作法有兩種：</p><p>🌟 作法一：把需要傳的資料的類別，寫成 <strong>cell 型別的屬性</strong></p><p>🌟 作法二：把需要傳的資料的類別，寫成 <strong>function 的參數</strong></p><p>這裡練習的是作法二</p><pre>    func updateUI(with attraction: Attraction) {<br>        <br>        accessoryType = .disclosureIndicator<br>        <br>        shopImageView.image = UIImage(named: attraction.photo)<br>        nameLabel.text = attraction.name<br>        chineseName.text = attraction.chineseName<br>        <br>        shopImageView.frame = CGRect(x: 20, y: 10, width: 188, height: 133)<br>        shopImageView.contentMode = .scaleAspectFill<br>        <br>        nameLabel.frame = CGRect(x: 210, y: 40, width: 160, height: 44)<br>        nameLabel.numberOfLines = 0<br>        nameLabel.font = .systemFont(ofSize: 18, weight: .semibold)<br>        //nameLabel.backgroundColor = .gray<br>        <br>        chineseName.frame = CGRect(x: 210, y: 84, width: 160, height: 44)<br>        chineseName.numberOfLines = 0<br>        chineseName.font = .systemFont(ofSize: 16, weight: .medium)<br>        //chineseName.backgroundColor = .lightGray<br>        <br>    }</pre><p>function 後的外部參數 with，可有可無，重點是後面的內部參數 attraction 及 類別 Attraction。</p><p>然後把 function 運用到對應的 Table View Controller 裡</p><pre>    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -&gt; UITableViewCell {<br>        <br>        guard let cell = tableView.dequeueReusableCell(withIdentifier: &quot;\(ShopTableViewCell.self)&quot;, for: indexPath) as? ShopTableViewCell else {fatalError(&quot;dequeueReusableCell ShopTableViewCell Failed&quot;)}<br>        <br>        let attraction = shops[indexPath.section].attractions[indexPath.item]<br>        <br>        cell.updateUI(with: attraction)<br>        <br>        return cell<br>    }</pre><p>把 function 裡參數的類別存入常數，這裡取跟內部參數同名 attraction，然後寫進 function 後的參數裡。</p><p>✨ 作法一：把需要傳的資料的類別，寫成 <strong>cell 型別的屬性：</strong>可參考另一篇 Medium 的<strong>最後兩個 GitHub 檔案</strong></p><p><a href="https://medium.com/%E5%BD%BC%E5%BE%97%E6%BD%98%E7%9A%84-swift-ios-app-%E9%96%8B%E7%99%BC%E6%95%99%E5%AE%A4/31-%E5%88%A9%E7%94%A8avplayerviewcontroller-%E6%90%AD%E9%85%8D-ibsegueaction-%E6%92%AD%E5%BD%B1%E7%89%87-592aff973a1e">#31 利用AVPlayerViewController與SFSafariViewController 搭配 IBSegueAction 播影片與開啟網頁</a></p><h4>參考資料：</h4><p><a href="https://medium.com/%E5%BD%BC%E5%BE%97%E6%BD%98%E7%9A%84-swift-ios-app-%E9%96%8B%E7%99%BC%E5%95%8F%E9%A1%8C%E8%A7%A3%E7%AD%94%E9%9B%86/%E5%88%A9%E7%94%A8-flow-layout-%E7%9A%84-collection-view-%E8%A3%BD%E4%BD%9C%E7%85%A7%E7%89%87%E7%89%86-e31dad55a7ac">利用 flow layout 的 collection view 製作照片牆</a></p><h4>GitHub：</h4><p><a href="https://github.com/Ryan-CY/ebook2-CollectionView-Practice">GitHub - Ryan-CY/ebook2-CollectionView-Practice</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8e7cbb990b75" width="1" height="1" alt=""><hr><p><a href="https://medium.com/peter-pan-swift-ios-class/35-ebook-of-jewel-changi-airport-%E6%98%9F%E8%80%80%E6%A8%9F%E5%AE%9C-%E9%9B%BB%E5%AD%90%E6%9B%B8-%E7%A8%8B%E5%BC%8F%E7%89%88-8e7cbb990b75"># 35 eBook of Jewel Changi Airport 星耀樟宜 電子書-程式版</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[#34 cell 的重覆利用 — to-do list 的完成打勾]]></title>
            <link>https://medium.com/peter-pan-swift-ios-class/34-cell-%E7%9A%84%E9%87%8D%E8%A6%86%E5%88%A9%E7%94%A8-to-do-list-%E7%9A%84%E5%AE%8C%E6%88%90%E6%89%93%E5%8B%BE-e9c2a13de246?source=rss-b5b0c3dc8e10------2</link>
            <guid isPermaLink="false">https://medium.com/p/e9c2a13de246</guid>
            <dc:creator><![CDATA[CY’s Programming Journey]]></dc:creator>
            <pubDate>Tue, 07 Feb 2023 11:51:08 GMT</pubDate>
            <atom:updated>2023-02-22T04:36:14.287Z</atom:updated>
            <content:encoded><![CDATA[<h3>#34 cell 的重覆利用 — to-do list 的完成打勾</h3><h4>不負責旅遊清單練習</h4><h4>作業來源：</h4><p><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/50-to-do-list-%E7%9A%84%E5%AE%8C%E6%88%90%E6%89%93%E5%8B%BE-dc2d31d3c3e6">#50 cell 的重覆利用 — to-do list 的完成打勾</a></p><h4>涵蓋的部分：</h4><p>基本版</p><blockquote>1. 產生 array 資料(待辦事項，想讀的書，想去玩的國家等)，顯示在表格裡。</blockquote><blockquote>2. 點選 cell 顯示 / 取消勾選。觀察表格上下捲動後，原本打勾的 cell 是否變沒打勾，原本沒打勾的 cell 是否變打勾。</blockquote><blockquote>3. 其他：點選灰色空心的愛心，會變成紅色實心的愛心，再次點選會變回灰色空心愛心。</blockquote><h4>練習目標：</h4><p>Apple 程式會利用重複使用 cell，來增加運作時的效能，但當在表格上做註記(如打勾,愛心等)時，練習不因表格上下捲動而把註記位置給打亂</p><h4>做法摘要：</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/295/1*UPrPbNu2UDyoCekVTVKB-w.gif" /><figcaption>GIF</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R1Wy31k3aqateaLg7-G44Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t9Iin0LUqrC9sq3HXNoFMg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0i-adBxtwaAzEdDWDAQidA.png" /></figure><blockquote><strong>產生資料：</strong></blockquote><p>為了減少產生資料花費的時間，使用 ChatGPT 產生資料，當產生的資料很怪或不是很滿意時，可以按下方中間 “Regenerate response” 重新產生答案，或是把問題打得更明確一些。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/888/1*f-DJQ8KXjKRDAv-YBLsCZg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/888/1*ihXGh6aHn4TrA0ZOpKOg_w.png" /></figure><p>🌟 ChatGPT 相關教學</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/%E7%94%A8-chatgpt-%E7%AF%80%E7%9C%81%E8%BC%B8%E5%85%A5%E8%B3%87%E6%96%99%E7%9A%84%E6%99%82%E9%96%93-%E5%BF%AB%E9%80%9F%E5%BB%BA%E7%AB%8B%E5%AF%A6%E9%AB%94-array-json-569a33fb4b6a">用 ChatGPT 節省輸入資料的時間，快速建立實體，array &amp; JSON (mock data)</a></p><p>然後就是把資料複製到 Xcode 裡，加上兩個變數其型別為Bool去產生表格，<br>在 true 時顯示打勾或顯示愛心，false 時取消勾選或刪除愛心。</p><p>一樣先產生兩個 swift file 及 struct</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/504/1*N_4iVzMUCEM08kmuUMAbpw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/516/1*uuBkuDJJ72btrAetpX3w5w.png" /></figure><p>最後產生的資料長這個樣子，兩個 Bool 設定為 false</p><pre>var Countries: [Country] = [<br>        <br>        Country(name: &quot;JAPAN&quot;, attrction: [<br>            Attraction(name: &quot;東京塔&quot;, location: &quot;東京都港區&quot;, transportation: &quot;地鐵&quot;, visit: false, like: false),<br>            Attraction(name: &quot;上野動物園&quot;, location: &quot;東京都台東區&quot;, transportation: &quot;地鐵&quot;, visit: false, like: false),<br>            Attraction(name: &quot;富士山&quot;, location: &quot;静岡縣&quot;, transportation: &quot;巴士&quot;, visit: false, like: false),<br>            Attraction(name: &quot;淺草寺&quot;, location: &quot;東京都台東區&quot;, transportation: &quot;地鐵&quot;, visit: false, like: false),<br>            Attraction(name: &quot;新宿&quot;, location: &quot;東京都新宿區&quot;, transportation: &quot;地鐵&quot;, visit: false, like: false),<br>            Attraction(name: &quot;原宿&quot;, location: &quot;東京都渋谷區&quot;, transportation: &quot;地鐵&quot;, visit: false, like: false),<br>            Attraction(name: &quot;日本橋&quot;, location: &quot;東京都中央區&quot;, transportation: &quot;地鐵&quot;, visit: false, like: false),<br>            Attraction(name: &quot;東京迪士尼樂園&quot;, location: &quot;千葉縣&quot;, transportation: &quot;巴士&quot;, visit: false, like: false),<br>            Attraction(name: &quot;江戶村&quot;, location: &quot;東京都墨田區&quot;, transportation: &quot;地鐵&quot;, visit: false, like: false),<br>            Attraction(name: &quot;秋葉原&quot;, location: &quot;東京都千代田區&quot;, transportation: &quot;地鐵&quot;,  visit: false, like: false),<br>            Attraction(name: &quot;銀座&quot;, location: &quot;東京都中央區&quot;, transportation: &quot;地鐵&quot;, visit: false, like: false),<br>            Attraction(name: &quot;晴空塔&quot;, location: &quot;東京都港區&quot;, transportation: &quot;地鐵&quot;, visit: false, like: false),<br>            Attraction(name: &quot;神田明神&quot;, location: &quot;東京都千代田區&quot;, transportation: &quot;地鐵&quot;, visit: false, like: false),<br>            Attraction(name: &quot;涉谷&quot;, location: &quot;東京都渋谷區&quot;, transportation: &quot;地鐵&quot;, visit: false, like: false),<br>            Attraction(name: &quot;明治神宮&quot;, location: &quot;東京都渋谷區&quot;, transportation: &quot;地鐵&quot;, visit: false, like: false)]),<br>        <br>        Country(name: &quot;KOREA&quot;, attrction: [<br>            Attraction(name: &quot;首爾塔&quot;, location: &quot;首爾市中心&quot;, transportation: &quot;地鐵&quot;, visit: false, like: false),<br>            Attraction(name: &quot;景福宮&quot;, location: &quot;景福門&quot;, transportation: &quot;地鐵&quot;, visit: false, like: false),<br>            Attraction(name: &quot;光州塔&quot;, location: &quot;光州市中心&quot;, transportation: &quot;公車&quot;, visit: false, like: false),<br>            Attraction(name: &quot;首爾城堡&quot;, location: &quot;首爾市中心&quot;, transportation: &quot;地鐵&quot;, visit: false, like: false),<br>            Attraction(name: &quot;海邊藝術村&quot;, location: &quot;釜山市西部海岸&quot;, transportation: &quot;公車&quot;, visit: false, like: false),<br>            Attraction(name: &quot;秀川村&quot;, location: &quot;忠清北道&quot;, transportation: &quot;公車&quot;, visit: false, like: false),<br>            Attraction(name: &quot;漢江花園城&quot;, location: &quot;首爾市東南部&quot;, transportation: &quot;地鐵&quot;, visit: false, like: false),<br>            Attraction(name: &quot;東大門市場&quot;, location: &quot;首爾市東部&quot;, transportation: &quot;地鐵&quot;, visit: false, like: false),<br>            Attraction(name: &quot;釜山海洋世界&quot;, location: &quot;釜山市西部海岸&quot;, transportation: &quot;公車&quot;, visit: false, like: false),<br>            Attraction(name: &quot;慶州海灘&quot;, location: &quot;慶州市&quot;, transportation: &quot;公車&quot;, visit: false, like: false),<br>            Attraction(name: &quot;首爾科學博物館&quot;, location: &quot;首爾市中心&quot;, transportation: &quot;地鐵&quot;, visit: false, like: false),<br>            Attraction(name: &quot;松山文化村&quot;, location: &quot;首爾市中心&quot;, transportation: &quot;地鐵&quot;, visit: false, like: false),<br>            Attraction(name: &quot;南怡島&quot;, location: &quot;釜山市西南部&quot;, transportation: &quot;公車&quot;, visit: false, like: false),<br>            Attraction(name: &quot;韓國牛肉餐廳&quot;, location: &quot;首爾市中心&quot;, transportation: &quot;地鐵&quot;, visit: false, like: false),<br>            Attraction(name: &quot;濟州島&quot;, location: &quot;忠清北道&quot;, transportation: &quot;飛機&quot;, visit: false, like: false)<br>        ])<br>        <br>    ]</pre><blockquote><strong>製作藍色勾勾：</strong></blockquote><p>藍色勾勾是利用 Table View Cell 裡的 accessory 內建的樣式，共有五種，這次只用到 none 跟 checkmark</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/740/1*7FZdZ-P4hVZpAbE07j46Pw.png" /></figure><p>當點選到特定 cell 時，希望可以觸發勾選或是取消打勾，但其實程式裡的變化是：<br><strong>順序 1.</strong> 點選時先去改變 Bool 值 <strong>→ 順序 2.</strong> Bool 值改變時再去改變顯示介面</p><p>所以在 cellForRow 的 function 裡（<strong>順序 2</strong>）：<br>當變數 visit 的 Bool 值變成 true 則 accessoryType = .checkmark，變 false 則 accessoryType = .none</p><pre>if Countries[indexPath.section].attrction[indexPath.row].visit == false {<br>            cell.accessoryType = .none<br>        } else {<br>            cell.accessoryType = .checkmark<br>        }</pre><p>再來，設定點到 cell 時要讓 Bool 值改變（<strong>順序 1</strong>），<br>所以在 didSelectRow 的 function 裡，運用運算子! 對 Bool 值取相反值，</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9Pw7br3ynsm8gT743h5ldw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aAJ4Ixc-HYnb9ceRIXPu9Q.png" /></figure><p>假設：A 是 Bool 型別，則觸發 A = !A (讀作：把相反 A 的值存入 A)時，<br>A 原本是 true 會變成 false，false 會變成 true。</p><p>在這裡程式會變這樣：</p><p>Countries[indexPath.section].attraction[indexPath.row].visit <strong>= !</strong>Countries[indexPath.section].attraction[indexPath.row].visit</p><p>🌟 因為 value type 的關係，得把它們(Countries &amp; attraction)直接寫在一起。參考：</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/swift-%E7%9A%84-value-type-%E5%92%8C-reference-type-25f9ae9f54b6">Swift 的 value type 和 reference type</a></p><p>點選了 cell 改變了 Bool 值，最後，要再加上一行：<br>tableView.reloadData( )，去更新表格</p><pre>override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {<br>        // !：Bool之間轉換，不是true就是false<br>        Countries[indexPath.section].attrction[indexPath.row].visit = !Countries[indexPath.section].attrction[indexPath.row].visit<br>        //Reloads the rows and sections of the table view.<br>        tableView.reloadData()<br>    }</pre><blockquote><strong>製作點取變成紅色愛心：</strong></blockquote><p>愛心的部分則是使用 Button 搭配 SF Symbols，搭配顏色的變化</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/560/1*onU5gh5bjT5yNGDWW83bng.png" /></figure><p>跟藍色勾勾觀念類似，在 cellForRow 的 function 裡：<br>當變數 like 的 Bool 值變成 true 則 heartButton.setImage 呈現紅色愛心，變 false 則呈現灰色空心愛心</p><p>這裡做了一個 enum 的 rawValue 字串對應 SF Symbols 的字串</p><pre>enum Heart: String {<br>    case like = &quot;heart.fill&quot;<br>    case unlike = &quot;heart&quot;<br>}</pre><p>搭配顏色變化</p><pre>if Countries[indexPath.section].attrction[indexPath.row].like == false {<br>            cell.heartButton.setImage(UIImage(systemName: &quot;\(Heart.unlike.rawValue)&quot;), for: .normal)<br>            cell.heartButton.tintColor = .systemGray3<br>        } else {<br>            cell.heartButton.setImage(UIImage(systemName: &quot;\(Heart.like.rawValue)&quot;), for: .normal)<br>            cell.heartButton.tintColor = UIColor.systemRed<br>        }</pre><p>一樣在最後，在按下愛心 Button 時，去改變 Bool 值，所以拉 IBAction func 到 Table View Controller，搭配 convert function 用座標判斷觸發的 cell 。</p><p>參考這篇</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%E8%BD%89%E6%8F%9B%E5%BA%A7%E6%A8%99%E7%9A%84-convert-function-%E5%88%A4%E6%96%B7%E9%BB%9E%E9%81%B8%E7%9A%84-cell-1eee56a57d3b">利用轉換座標的 convert function 判斷點選的 button 在哪個 cell</a></p><p>Button 的 IBAction func 程式，一樣也要輸入 tableView.reloadData( ) 去更新表格</p><pre>@IBAction func heartButtonChosen(_ sender: UIButton) {<br>        <br>        let point = sender.convert(CGPoint.zero, to: tableView)<br>        <br>        if let indexPath = tableView.indexPathForRow(at: point) {<br>            Countries[indexPath.section].attraction[indexPath.row].like = !Countries[indexPath.section].attraction[indexPath.row].like<br>        }<br>        tableView.reloadData()<br>    }</pre><p>在 cell 的 reuseIdentifier 使用 Extension 跟 computed property 去取代輸入ID字串</p><pre>import Foundation<br>import UIKit<br><br>extension UITableViewCell {<br>    static var reuseIdentifier: String {&quot;\(Self.self)&quot;}<br>}</pre><p>cellForRow 程式碼</p><pre> override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -&gt; UITableViewCell {<br>        guard let cell = tableView.dequeueReusableCell(withIdentifier: AttractionTableViewCell.reuseIdentifier, for: indexPath) as? AttractionTableViewCell else {<br>            fatalError(&quot;dequeueReusableCell AttractionTableViewCell failed&quot;)<br>        }<br>        <br>        if Countries[indexPath.section].attraction[indexPath.row].visit == false {<br>            cell.accessoryType = .none<br>        } else {<br>            cell.accessoryType = .checkmark<br>        }<br>        <br>        if Countries[indexPath.section].attraction[indexPath.row].like == false {<br>            cell.heartButton.setImage(UIImage(systemName: &quot;\(Heart.unlike.rawValue)&quot;), for: .normal)<br>            cell.heartButton.tintColor = .systemGray3<br>        } else {<br>            cell.heartButton.setImage(UIImage(systemName: &quot;\(Heart.like.rawValue)&quot;), for: .normal)<br>            cell.heartButton.tintColor = UIColor.systemRed<br>        }<br>        <br>        configureCell(indexPath, cell)<br>        <br>        return cell<br>    }</pre><h4>細節調整：</h4><p>在 Table View 的 Attributes Inspector 可以調整 Style，共有</p><p>🌟 Plain<br>🌟 Grouped<br>🌟 Inset Grouped</p><p>將在以下說明。</p><blockquote><strong>Plain</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/251/1*NnVnbmksXyGyIQ1FKSXxZA.png" /></figure><p>如文章上方的GIF所示，滑動時螢幕上方一直有一根 bar 在那裡。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/295/1*UPrPbNu2UDyoCekVTVKB-w.gif" /></figure><blockquote><strong>Grouped</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/251/1*EEQSkBpJ8nf79t1mlDP0Ag.png" /></figure><p>滑動時螢幕上方不會有 bar</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/295/1*ydXSgJj_XnSN6N4y4ayuzg.gif" /></figure><blockquote><strong>Inset Grouped</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/251/1*ElbiRKcR7k_AivvFNt2cVg.png" /></figure><p>把表格變成圓角的格式，記得表格跟 Table View 背景顏色要不一樣才看得出來。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/295/1*RtM057fTh2oQTVfahxXzxQ.gif" /></figure><h4>參考資料：</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%E6%95%99%E5%AE%A4/100%E9%81%93iosapp%E8%AC%8E%E9%A1%8C-50-to-do-list-%E7%9A%84%E5%AE%8C%E6%88%90%E6%89%93%E5%8B%BE-6a550ce4174">100道iOSApp謎題#50 to-do list 的完成打勾</a></li><li><a href="https://itisjoe.github.io/swiftgo/ch1/basic_operators.html">基本運算子</a></li></ul><h4>GitHub：</h4><p><a href="https://github.com/Ryan-CY/to-do-list-TableView-Practice">GitHub - Ryan-CY/to-do-list-TableView-Practice</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e9c2a13de246" width="1" height="1" alt=""><hr><p><a href="https://medium.com/peter-pan-swift-ios-class/34-cell-%E7%9A%84%E9%87%8D%E8%A6%86%E5%88%A9%E7%94%A8-to-do-list-%E7%9A%84%E5%AE%8C%E6%88%90%E6%89%93%E5%8B%BE-e9c2a13de246">#34 cell 的重覆利用 — to-do list 的完成打勾</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>