iT邦幫忙

2021 iThome 鐵人賽

DAY 20
0
Mobile Development

轉職App開發打怪雜記系列 第 20

接API

緣由:

接API大概是在科技業的面試時最常問的問題了吧,但老實說資料的複雜性能不能接得正確好像才是關鍵,但假如單純只是要回答會或不會的問題,再怎麼科技業菜鳥,一定是回答”會“的吧~~但對於面試官來說,會或不會其實滿一翻兩瞪眼,接接看就知道了~以下我們來試接看看,假如有什麼寫錯的地方,再請指教我~感恩

實作:

找到一些政府公開資訊,這邊我們使用
https://cloud.culture.tw/frontsite/trans/SearchShowAction.do?method=doFindTypeJ&category=4
我們可以看到裡面是json檔案
將資料丟到https://jsoneditoronline.org/ 上查看樹狀結構,如下圖
https://ithelp.ithome.com.tw/upload/images/20210917/20130757FwlGJ3ow95.png
然後想想我們需要什麼資料,這邊我們要呈現版本號(version)、UID、標題(title)、展覽資訊(showInfo)、展覽說明(descriptionFilterHtml)
根據樹狀圖很清楚地看到資料分層的狀態,除了展覽資訊可以再往下展開外,其他皆為單層結構,
所以在定義Codable結構時(Codable 是 Encodable 和 Decodable 協議的類型別名),
只有展覽資訊需要使用字典來解,如下所示:

//政府公開資訊 -藝文類
struct govOpenData: Codable {
   let version:String
   let UID:String
   let title:String
   let placeinfo:[[String:String?]]
   let description:String

   //在struct內列舉,一定要寫成enum CodingKeys: String, CodingKey
   enum CodingKeys: String, CodingKey {
       case version
       case UID
       case title
       case placeinfo = "showInfo"
       case description = "descriptionFilterHtml"
   }

}

接著要來拷貝資料了,當然有很棒也很好用的套件,例如:Alamofire等,可以拷貝api資料,
但我們這邊示範先用swift內建的方法,寫法如下:

let urlStr3 = "https://cloud.culture.tw/frontsite/trans/SearchShowAction.do?method=doFindTypeJ&category=4"
if let url = URL(string: urlStr3) {
   URLSession.shared.dataTask(with: url) { data, response , error in
       if let data = data {
           do {
               let openDatas = try JSONDecoder().decode([govOpenData].self, from: data)
               print("公開資料\(openDatas)")
           } catch  {
               print("錯誤\(error)")
           }
       }
   }.resume()
}

上一篇
webkit的inline play設定
下一篇
Webview問題集(上)-另開分頁
系列文
轉職App開發打怪雜記30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言