最近參加了彼得潘的iOS App程式設計入門,單純記錄swift課程筆記,本篇將會詳細描述如何用Swift串接API
此次的相關代碼放置於:https://github.com/hsuanchi/Swift_Demo/tree/master/getJsonAPI
文章目錄
一. 取得API
首先這次要拿的是咖啡廳的API資料 https://cafenomad.tw/api/v1.2/cafes/taipei,用GET方式進入網頁,可以看到不易閱讀的JSON格式

所以使用JSON Editor來視覺化Json格式 http://jsoneditoronline.org

二. 定義JSON型別
宣告變數的型態可以參考如下:
- 整數 ➪ Int
- 浮點數 ➪ Float 或 Double
- 字串 ➪ String
- true 或 false ➪ Bool
- 陣列 ➪ Array
- 網址 ➪ URL (ps: 如果網址包含 ASCII 以外的文字,請將型別宣告為 String,之後再另外轉成 URL)
- 時間 ➪ Date (ps: 若時間是特別的格式,請將型別宣告為 String,之後再另外轉成 Date)
除此之外可以參考Peter的這篇 :利用 JSONDecoder 和 Codable 解析 JSON 和生成自訂型別資料
這次只簡單的拿了name和city來使用,定義如下
struct CoffeeData: Decodable {
var name: String
var city: String
}
三. Swift串接API,解析回傳資料
寫了getCoffeeData的function,並放在viewDidLoad發生時觸發獲取API資料
override func viewDidLoad() {
super.viewDidLoad()
getCoffeeData()
}
看到 if let coffeeData = try? decoder.decode([CoffeeData].self, from: data),這邊使用JSONDecoder的方式將抓到的資料轉換成剛剛定義好的CoffeeData型別
for coffee in coffeeData { } 這邊將取得的資料放到shopName和shopCity array裡面
var shopName:[String] = []
var shopCity:[String] = []
func getCoffeeData() {
let address = "https://cafenomad.tw/api/v1.2/cafes/taipei"
if let url = URL(string: address) {
// GET
URLSession.shared.dataTask(with: url) { (data, response, error) in
if let error = error {
print("Error: \(error.localizedDescription)")
} else if let response = response as? HTTPURLResponse,let data = data {
print("Status code: \(response.statusCode)")
let decoder = JSONDecoder()
if let coffeeData = try? decoder.decode([CoffeeData].self, from: data) {
DispatchQueue.main.async{
for coffee in coffeeData { self.shopName.append(coffee.name)
self.shopCity.append(coffee.city)
}
self.tableView.reloadData()
}
}
}
}.resume()
} else {
print("Invalid URL.")
}
}
四. 將資料顯示成列表
為了待會能將ShopName和ShopCity傳入Cell內,這邊先用UITableViewCell將兩個label拉成Outlet

shopName.count這邊設定總共有幾列
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return shopName.count
}
cell.productLabel.text = shopName[indexPath.row] 這邊將剛剛從API取得的資料放進Label內
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Product_cell", for: indexPath) as! MenuListTableViewCell
cell.productLabel.text = shopName[indexPath.row]
cell.priceLabel.text = shopCity[indexPath.row]
return cell
}

關於更多顯示列表設定可以參考:
六. 完成

相關延伸閱讀:
- [Swift 教學] 彼得潘的iOS App課程作業五連發
- [Swift 教學] iOS APP如何串接API
- [Swift 教學] Swift Firebase資料庫串接 (附程式碼)
- [Swift 教學] Swift example 訂飲料App (附程式碼)
[Swift 教學] iOS APP如何串接API 結束囉,感謝收看,有關Max行銷誌的最新文章,都會發佈在Max的Facebook粉絲專頁,如果想看最新更新,還請您按讚或是追蹤唷!