iT邦幫忙

2021 iThome 鐵人賽

DAY 17
0
自我挑戰組

一個令我自豪的App完成之路系列 第 17

使用Google api查詢書本資訊 Day 17

這次實作的功能是使用Google Book api

使用textfield輸入ISBN碼按下Button,自動填入書名、書本簡介、書本作者、書本圖片

1. 建立一個@IBAction的Button到ViewController

從URLSession開始的內容都會建立這個CheckButton內

https://i.imgur.com/wcDihWc.png

1.1 建立 textfield連結

		@IBOutlet weak var Booktitle: UITextField!
    @IBOutlet weak var Bookdescription: UITextView!
    @IBOutlet weak var BookISBN: UITextField!
		@IBOutlet weak var Bookauthors:UITextField!
		@IBOutlet weak var Bookimage:ImageView!

2. 建立URLSession來去得到json檔案

URLSession.shared.dataTask(with: url){(data,response,error) in
	if let data = data, let content = String(data:data, encoding: .utf8){
		// 先列印出內容,檢查是否正確下載json檔案
		print(content)
	}

2.1 將content印出來的內容丟入jsoneditoronline方便用肉眼觀看

https://i.imgur.com/1DkrEGJ.png

3. 建立Struct 來放置JSONDecoder後的資料

根據上面解析出來的json資料配置Decoder的資料結構

因為我要顯示的是書名,書本描述,所以我找的是titledescription

struct BookInfo:Codable{
	// 因為所需要的東西在Nested Array內
	let items:[BookNeed]
}

struct BookNeed:Codable{
	let volumeInfo:[Content]
}

struct Content:Codable{
	let title:String
	let authors:[String]
	let description:String
	let imageLinks:[imagelinks]
}

struct imagelinks:Codable{
	let thumbnail:URL
}

3. 建立JSONDecoder來解析json檔案

// 使用Google Book的web api來查詢所要的資料
let url = URL(string:"https://www.googleapis.com/books/v1/volumes?q=isbn:\(String(BookISBN.text!))")!
// 將JSONDecoder建立在剛剛的URLSession下面
URLSession.shared.dataTask(with: url){(data,response,error) in

// 建立JSONDecoder實例
	let decoder = JSONDecoder()

	if let data = data{
		do{
				// 讓decoder來解析data,讓解析完成的資料儲存在BookInfo的資料結構內
				let Response = try decoder.decode(BookInfo.self, from:data)
				// 讓textfield內的文字顯示在textfield上
				self.Booktitle.text = Response.items.first?.volumeInfo.title
				self.Bookdescription.text = Response.items.first?.volumeInfo.description
				self.Bookauthors.text = Response.items.first?.volumeInfo.authors.first
				let imageurl = Response.items.first?.volumeInfo.imageLinks.thumbnail
				let imageData = try Data(contentOf:imageurl!)
				self.Bookimage.image = UIImage(data:imageData)
			}catch{
				print("error")
				}
	}
}.resume()
			

/

成果展示:

https://i.imgur.com/ka6SA4D.gif


參考資料

利用 JSONDecoder 和 Codable 解析 JSON 和生成自訂型別資料

Json解析筆記

Day 03: 試著解析 JSON 的檔案吧! - iT 邦幫忙::一起幫忙解決難題,拯救 IT 人的一天


上一篇
JSONDecoder 介紹 Day 16
下一篇
UISearchController 出來挑土豆 Day 18
系列文
一個令我自豪的App完成之路32
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言