iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 27
0
Mobile Development

《菜鳥のSwift》持續30天開發挑戰系列 第 27

《DAY 27》在表格裡顯示 JSON 資料

昨天已經先在除錯區裡顯示資料了,今天要把這些資料放到表格裡顯示,先在畫面中放入一個 Table View,並取好 IBOutlet 屬性名稱、取好 Table View Cell 的名稱等等,然後因為讀取網頁需要時間,會發生表格已經呈現出來資料卻沒有出現的狀況,所以再放入一個活動指示器(Activity Indicator View),在 viewDidLoad() 就開始轉圈,等到資料都顯示好再停止轉圈並隱藏,目的只是讓使用者知道載入還沒有完成。

  • 改寫程式碼如下。
import UIKit

class ViewController: UIViewController {
    
    var aqiCount = 0
    var county:[String] = []
    var siteName:[String] = []
    var aqiValue:[String] = []
    var aqiStatus:[String] = []
    var aqiTime:[String] = []
    
    @IBOutlet weak var tableView: UITableView!
    @IBOutlet weak var myActivityIndicator: UIActivityIndicatorView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        myActivityIndicator.hidesWhenStopped = true
        myActivityIndicator.startAnimating() // 開始轉圈圈
        
        var request = URLRequest(url: URL(string: "http://opendata.epa.gov.tw/webapi/Data/REWIQA/?$orderby=SiteName&$skip=0&$top=1000&format=json")!,timeoutInterval: Double.infinity)
        request.httpMethod = "GET"
        let task = URLSession.shared.dataTask(with: request){(data, respond, error) in
            
            let decoder = JSONDecoder()
            if let data = data, let AQI = try? decoder.decode([AQI].self, from: data){
                
                self.aqiCount = AQI.count
                for aqi in AQI {
                    print(aqi)
                    self.county.append(aqi.County)
                    self.siteName.append(aqi.SiteName)
                    self.aqiValue.append(aqi.AQI)
                    self.aqiStatus.append(aqi.Status)
                    self.aqiTime.append(aqi.PublishTime)
                }

            }
            else {
                print("error")
            }
            DispatchQueue.main.sync {
                self.tableView.reloadData()
                self.myActivityIndicator.stopAnimating() // 停止轉圈圈
            }
        }
        task.resume()
 
    }

}


extension ViewController: UITableViewDataSource,UITableViewDelegate {
    
    // 相信表格的三階段對話應該不難看懂才是
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return aqiCount
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
        cell.textLabel?.text = county[indexPath.row] + " " + siteName[indexPath.row] + " " + aqiValue[indexPath.row]
        cell.detailTextLabel?.text = aqiStatus[indexPath.row] + " " + aqiTime[indexPath.row]
        
        return cell
    }
    
}
  • 當切換到其它執行序時,必須切回主執行序才能對 UI 進行操作。

執行看看。
https://ithelp.ithome.com.tw/upload/images/20201010/20129680uXPWhiKeIr.png


上一篇
《DAY 26》使用 Codable 抓取 JSON 資料
下一篇
《DAY 28》天氣 App 實作(一)
系列文
《菜鳥のSwift》持續30天開發挑戰30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言