貓世界用網路資料API下載解碼JSON以及動態tableview及自訂cell運用

綜合版來到了最後一階段

首先看畫面:

再說一下構圖吧:

  1. 生一個View Controller畫面上放置一個Image View 按下Random會隨機變換API內提供的圖片 由於此url是每次輸入都會給不同資料 所以每次點擊時會重新解碼沒辦法即時變圖 並且Image View拉線到新增自訂名稱的ExchangeRateViewController資料夾
  2. 畫面下方放Container View 裡面放TableViewController改成 DynamicPrototypes 將TableViewCell命名成mycell 再放上兩個Label 並且新增自訂NasaTableViewController資料夾(本來要做Nasa星球但找不到免費完整API…) 還有MyTableViewCell資料夾 把Label拉到MyTableViewCell裡面 再把 Label做AutoLayout這樣才讓動態表格顯示的Label不會跑掉
  3. 再生一個ViewController 裡面放WebView拉線到新增自訂CatViewController資料夾
  4. 再加入一個讀取顯示器ActivityIndicator在WebView中間

部分程式碼:

  1. ExchangeRateViewController:
//定義該字串中需下載 且因需要讀取的圖片則為URLstruct CatImage: Codable {var url: URL}var aImage = [CatImage]()override func viewDidLoad() {super.viewDidLoad()if let url = URL(string: "https://api.thecatapi.com/v1/images/search"){let task = URLSession.shared.dataTask(with: url) { (Data, URLResponse, Error) inlet decoder = JSONDecoder()if let data = Data{do {let catImage = try decoder.decode([CatImage].self, from: data)self.aImage = catImage} catch {print(error)}}let image = self.aImage[0]let taskImage = URLSession.shared.dataTask(with: image.url) { (Data, response , error) inif let data = Data {DispatchQueue.main.async {self.imageCat.image = UIImage(data: data)}}}taskImage.resume()}task.resume()}}//按鈕同上 因為每次輸入https://api.thecatapi.com/v1/images/search網址跟內容皆會改變 所以需每次重新下載解碼@IBAction func randomCat(_ sender: UIButton) {if let url = URL(string: "https://api.thecatapi.com/v1/images/search"){let task = URLSession.shared.dataTask(with: url) { (Data, URLResponse, Error) inlet decoder = JSONDecoder()if let data = Data{do {let catImage = try decoder.decode([CatImage].self, from: data)self.aImage = catImage} catch {print(error)}}let image = self.aImage[0]let taskImage = URLSession.shared.dataTask(with: image.url) { (Data, response , error) inif let data = Data {DispatchQueue.main.async {self.imageCat.image = UIImage(data: data)}}}taskImage.resume()}task.resume()}}

2. NasaTableViewController:

struct CatKind: Codable {var name: String?var description: String?var vetstreet_url: String?}class NasaTableViewController: UITableViewController {var cats = [CatKind]()override func viewDidLoad() {super.viewDidLoad()if let url = URL(string: "https://api.thecatapi.com/v1/breeds"){let task = URLSession.shared.dataTask(with: url) { (Data, URLResponse, Error) inlet decoder = JSONDecoder()if let data = Data{do {let catArray = try decoder.decode([CatKind].self, from: data)self.cats = catArray} catch {print(error)}}DispatchQueue.main.async {self.tableView.reloadData()}}task.resume()}}}

3. CatViewController

//(讀取進度符)加入ActivityIndicator需服從WKNavigationDelegateclass CatViewController: UIViewController, WKNavigationDelegate {@IBAction func backButton(_ sender: UIButton) {dismiss(animated: true, completion: nil)}@IBOutlet weak var myActivityIndicator: UIActivityIndicatorView!@IBOutlet weak var catWebView: WKWebView!//此變數接收tableview傳過來的資料var senderCat: CatKind?override func viewDidLoad() {super.viewDidLoad()//(讀取進度)服從協定實作navigationDelegate裡面的方法catWebView.navigationDelegate = self//指定傳過來資料內的vetstreet_url並設為URL且連線if let okCat = senderCat?.vetstreet_url, let okURL = URL(string: okCat){let request = URLRequest(url: okURL)catWebView.load(request)}}//開始轉func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {myActivityIndicator.startAnimating()}//停止轉且將storeboard的Hides When Stopped勾選起來 停止才會消失func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {myActivityIndicator.stopAnimating()}

使用WebView要注意的是 其中我圖片的網址http沒有s是沒加密網址 所以必須到info.plist新增一個key才能正常顯示 如下圖:

綜合時鐘&折扣&貓的世界github在此:

--

--