在昨天談完Day28:使用Unwind Segue將表格選擇結果回傳後,今天我們來談談如何串接
後台API,做出一個辦公室訂下午茶 / 飲料App , 下午茶人人愛愛吃 ,
但負責點餐及收錢 , 人人閃躲逃 , 因此我們做一個自助點下午茶系統 ,
你點什麼及付錢了沒? , 一清二楚 , 無所遁形
App 功能需求:
新增訂購的飲料。
欄位:
(1) 名字
(2) 飲料 (讀取飲料價目 txt 檔,運用 picker, table 或 action sheet
讓使用者選擇,甚至加上 search 功能)
(3) 甜度
(4) 溫度
統計顯示訂購的飲料清單。
1.首先申請點下午茶資料存放雲端平台sheetDB,點餐完就可將資料存放在這裡
(有空我再來試用Azure Cosmos DB來存資料)
SheetDB用自己的Google帳號就可以申請
完成就可以看到Your Spreadsheets顯示訊息
2.先在Google Sheet建立欄位資料
將Google Sheet網址貼到sheetdb.io,按Create API
就會看到以下Sheet API資料
3.建立專案,在MainStoryBoard新增以下頁面
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模擬器執行結果
6.檢視sheetDB資料