#7 用RESTful API來訂杯珍奶喝吧!Part-4-訂單上傳及查詢
如顆要順利喝到想喝的飲料,那就不能少了這一步-上傳訂單,告知店家您想喝什麼飲料~
接著就來看看上如何從APP上,將您的想法告訴遠方的飲料店人員您訂了什麼飲品:
稍早己在Airtable上建立了OrderList這個table用來存訂單的資訊~
- 在Storyboard建立程式訂購飲料頁面,設定好AutoLayout,並將前頁2個menu list的Cell連接到訂購飲料頁面,訂購頁的Content可以選擇使用Static Cells
2. 使用者在menu list頁面點選想要訂購的飲料後,透過Segue將資料傳至訂購頁面
3. 接著,解析上傳JSON資料型別,並寫程式透過RESTful API方式將訂單上傳(POST),上傳前檢核TextField欄位若為空顯示Alert告知使用者填寫,按下訂購鈕以Alert顯示訊息告知使用杯數及總價,使用確認訂購再以Alert告知訂購完成
//解析上傳JSON的型別
import Foundation
struct UpdateOrderInfo: Codable {
var fields: Fields
struct Fields: Codable {
var name: String
var price: Int
var iceDegree: String
var sugarDegree: String
var cupAmount: Int
var comment: String
var userName: String
var userPhone: String
var totalAmount: Int
var updateTime: String
var storeName: String
}
}
//上傳訂單的函數
func uploadOrderInfo(name: String, price: Int, iceDegree: String, sugarDegree: String, cupAmount: Int, comment: String, userName: String, userPhone: String, totalAmount: Int, storeName: String) {
//計算總金額
self.totalAmount = price * cupAmount
let url = URL(string: "https://api.airtable.com/v0/appHy2q9FOUrGGhqS/OrderList")!
let apiKey = "Your API_KEY"
let httpHeader = "Authorization"
var request = URLRequest(url: url)
request.httpMethod = "POST" //新增
request.setValue(apiKey, forHTTPHeaderField: httpHeader)
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
let encoder = JSONEncoder()
let fieldsData = UploadOrderData.Fields(name: name, price: price, iceDegree: iceDegree, sugarDegree: sugarDegree, cupAmount: cupAmount, comment: comment, userName: userName, userPhone: userPhone, totalAmount: totalAmount, storeName: storeName)
let uploadData = UploadOrderData.Records(fields: fieldsData)
let data = try? encoder.encode(uploadData)
request.httpBody = data
URLSession.shared.dataTask(with: request) { data, response, error in
if let data {
do {
let decoder = JSONDecoder()
let formatter = DateFormatter()
//自訂時間格式
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
decoder.dateDecodingStrategy = .formatted(formatter)
let _ = try decoder.decode(OrderInfo.self, from: data)
} catch {
print(error)
}
}
}.resume()
//提示己完成訂購
let controller = UIAlertController(title: "訂購通知", message: "己完成訂購", preferredStyle: .alert)
let okAction = UIAlertAction(title: "好的", style: .default)
controller.addAction(okAction)
self.present(controller, animated: true)
}
詢問是否訂購:
提示己訂購完成:
確認Airtable的OrderList數到上傳的訂單:
接著來說說訂單查詢的部份囉~
- 在Storyboard中設定好"訂單列表頁面"
2. 回到menu list的頁面,右上角新增"訂單"按鈕,並將Button連接到"訂單列表頁面"
3. 按下"訂單"鈕後,透過API下載訂單資料,下載完成後顯示在APP畫面中
//解析JSON型別
import Foundation
struct OrderInfo: Codable {
var id: String
var createdTime: Date
var fields: Fields
struct Fields: Codable {
var name: String
var price: Double
var iceDegree: String
var sugarDegree: String
var cupAmount: Int
var comment: String
var userName: String
var userPhone: String
var totalAmount: Int
}
}
//下載訂單資料函數
func fetchOrderInfoList() {
//網址中sort那串字是API排序的方式,預設ASC
//sort%5B0%5D%5Bfield%5D=createdTime&sort%5B0%5D%5Bdirection%5D=desc依據創建時間由新而舊排序
let url = URL(string: "https://api.airtable.com/v0/appHy2q9FOUrGGhqS/OrderList?sort%5B0%5D%5Bfield%5D=createdTime&sort%5B0%5D%5Bdirection%5D=desc")!
let apiKey = "Your API_Key"
let httpHeader = "Authorization"
var request = URLRequest(url: url)
request.httpMethod = "GET" //下載
request.setValue(apiKey, forHTTPHeaderField: httpHeader)
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
URLSession.shared.dataTask(with: request) { data, response, error in
if let data {
do {
let decoder = JSONDecoder()
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
decoder.dateDecodingStrategy = .formatted(formatter)
let orderInfo = try decoder.decode(LoadOrderInfoList.self, from: data)
if orderInfo.records.count > 0 {
self.loadOrderInfoList = []
for i in 0...(orderInfo.records.count - 1){
self.loadOrderInfoList.append(orderInfo.records[i])
}
let controller = UIAlertController(title: "使用通知", message: "點選訂單,可進入修改刪除頁面", preferredStyle: .alert)
let okAction = UIAlertAction(title: "好的", style: .default)
controller.addAction(okAction)
self.present(controller, animated: true)
} else {
let controller = UIAlertController(title: "訊息通知", message: "目前尚無訂單", preferredStyle: .alert)
let okAction = UIAlertAction(title: "好的", style: .default)
controller.addAction(okAction)
self.present(controller, animated: true)
}
DispatchQueue.main.async {
self.tableView.reloadData()
}
} catch {
print(error)
}
}
}.resume()
}
呈現在APP的畫面:
以上就是訂單上傳及查詢建置內容,謝謝觀賞~
相關聯結:
#4 用RESTful API來訂杯珍奶喝吧!Part-1-畫面及功能簡介 — 重來 就從 APPLE APP 開始吧 — Medium
#5 用RESTful API來訂杯珍奶喝吧!Part-2-Web官網整合介紹 — 重來 就從 APPLE APP 開始吧 — Medium
#6 用RESTful API來訂杯珍奶喝吧!Part-3-menu呈現及banner輪播 — 重來 就從 APPLE APP 開始吧 — Medium
#8 用RESTful API來訂杯珍奶喝吧!Part-5-訂單修改及刪除 — 重來 就從 APPLE APP 開始吧 — Medium