iT邦幫忙

第 11 屆 iThome 鐵人賽

DAY 29
1

在昨天談完Day28:使用Unwind Segue將表格選擇結果回傳後,今天我們來談談如何串接

後台API,做出一個辦公室訂下午茶 / 飲料App , 下午茶人人愛愛吃 ,

但負責點餐及收錢 , 人人閃躲逃 , 因此我們做一個自助點下午茶系統 ,

你點什麼及付錢了沒? , 一清二楚 , 無所遁形 /images/emoticon/emoticon01.gif

https://ithelp.ithome.com.tw/upload/images/20191006/20112182m5NQZRTn0U.jpg

App 功能需求:

新增訂購的飲料。

欄位:

(1) 名字
(2) 飲料 (讀取飲料價目 txt 檔,運用 picker, table 或 action sheet
讓使用者選擇,甚至加上 search 功能)
(3) 甜度
(4) 溫度

統計顯示訂購的飲料清單。

實做步驟

1.首先申請點下午茶資料存放雲端平台sheetDB,點餐完就可將資料存放在這裡

(有空我再來試用Azure Cosmos DB來存資料)

https://ithelp.ithome.com.tw/upload/images/20191006/20112182VnvzWmGWbD.jpg

SheetDB用自己的Google帳號就可以申請

https://ithelp.ithome.com.tw/upload/images/20191006/20112182EXAOwZ9Yf4.jpg

完成就可以看到Your Spreadsheets顯示訊息

https://ithelp.ithome.com.tw/upload/images/20191006/20112182DlLIuGxrv7.jpg

2.先在Google Sheet建立欄位資料

https://ithelp.ithome.com.tw/upload/images/20191006/20112182hNKZiJyWhv.jpg

將Google Sheet網址貼到sheetdb.io,按Create API

https://ithelp.ithome.com.tw/upload/images/20191006/20112182xWCIYIIJev.jpg

就會看到以下Sheet API資料

https://ithelp.ithome.com.tw/upload/images/20191006/20112182Ev0O9DGCrg.jpg

3.建立專案,在MainStoryBoard新增以下頁面

https://ithelp.ithome.com.tw/upload/images/20191006/20112182coMIm0pWKd.png

4.在程式碼注意將下單資料儲存在sheetDB

import Foundation
class Cdrink{
    static let Drink = Cdrink()
    func upload(data: [String: Any] , finished:@escaping ((Bool)->())) {
        let apiStr = "https://sheetdb.io/api/v1/yourkey"
        if let urlStr = apiStr.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed), let url = URL(string: urlStr) {
            print(urlStr)
            var urlRequest = URLRequest(url:url)
            
            // Set request HTTP method to GET. It could be POST as well
            urlRequest.httpMethod = "POST"
            urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")

            do{
                let data = try JSONSerialization.data(withJSONObject: data, options: [])
                let task = URLSession.shared.uploadTask(with: urlRequest, from: data, completionHandler:{(retData, res,err) in
                    if let returnData = retData, let dic = (try? JSONSerialization.jsonObject(with: returnData)) as? [String:String] {
                        print(dic)
                        finished(false)
                    }else{
                        finished(true)
                    }
                })
                task.resume()
            }catch{
                print(error)
            }
        }
    }
    func download(finish:@escaping (([CdrinkOrder]?)->())) {
        var item = [CdrinkOrder]()
        let apiStr = "https://sheetdb.io/api/v1/yourkey"
        if let urlStr = apiStr.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed), let url = URL(string: urlStr) {
            print(urlStr)
            let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
                if let data = data
                {
                    do {
                        var i = 0
                        let Results = try JSONDecoder().decode(Array<DrinkArr>.self, from: data)
                        for _ in Results{
                            let name = Results[i].name
                            let drink = Results[i].drink
                            let sweet = Results[i].sweet
                            let ice = Results[i].ice
                            let size = Results[i].size
                            let time = Results[i].time
                            item.append(CdrinkOrder(name: name, drink: drink, sweet: sweet, ice: ice, size: size, time: time))
                            i=i+1
                        }
                        print(Results)
                        if item.count != 0{
                            finish(item)
                        }else{
                            finish(nil)
                        }
                    }catch{
                        print(error)
                    }
                }
            }
            task.resume()
        }
    }
}

5.按Play,看iPhone 11 Pro Max模擬器執行結果

https://ithelp.ithome.com.tw/upload/images/20191006/20112182lwncKtF5n1.png

https://ithelp.ithome.com.tw/upload/images/20191006/201121826PytUcEsbW.png

6.檢視sheetDB資料

https://ithelp.ithome.com.tw/upload/images/20191006/20112182cTuvxr26Yl.jpg


上一篇
Day28:如何使用unwind segue 將表格選擇結果回傳
下一篇
Day30:如何使用SwiftUI來設計App
系列文
iOS App初心者的30天試鍊31
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言