一片難求的口罩
Tags: iOS, Json, Xcode

一片難求的口罩

struct Mask:Codable { var id:String var name:String var address:String var tel:String var adult:String var child:String var time:Date enum CodingKeys: String, CodingKey { case id = "醫事機構代碼" case name = "醫事機構名稱" case address = "醫事機構地址" case tel = "醫事機構電話" case adult = "成人口罩剩餘數" case child = "兒童口罩剩餘數" case time = "來源資料時間" } }

接下來是解析口罩分布的地點

@objc func getData() -> () { let urlStr = "https://quality.data.gov.tw/dq_download_json.php?nid=116285&md5_url=2150b333756e64325bdbc4a5fd45fad1" print("GOT URL") if let url = URL(string: urlStr){ URLSession.shared.dataTask(with: url) { (data, response, error) in let decoder = JSONDecoder() //存時間所要的格式 let formatter = DateFormatter() formatter.dateFormat = "yyyy/MM/dd HH:mm:ss" decoder.dateDecodingStrategy = .formatted(formatter) do{ try decoder.decode([Mask].self, from: data!) }catch{ print(error) } if let data = data, let masks = try? decoder.decode([Mask].self, from: data){ self.masks = masks print("get Result") DispatchQueue.main.async { print("viewDidLoad") self.activityIndicatorView.removeFromSuperview() self.tableView.reloadData() self.refreshControl!.endRefreshing() } } }.resume() }else{ print("error") } }



顯示在地圖上

import UIKit import MapKit import CoreLocation class MaskAnnotationViewController: UIViewController { @IBOutlet weak var mapView: MKMapView!

let locationManager = CLLocationManager()

override func viewDidLoad() { super.viewDidLoad()

locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters locationManager.requestWhenInUseAuthorization() mapView.delegate = self mapView.register(MKMarkerAnnotationView.self, forAnnotationViewWithReuseIdentifier: "\(MaskAnnotation.self)") //這邊要解析地圖，需import MapKit guard let url = URL(string: "https://raw.githubusercontent.com/kiang/pharmacies/master/json/points.json") else{ return } URLSession.shared.dataTask(with: url) { (data, response, error) in guard let data = data else {return} let decoder = MKGeoJSONDecoder() if let features = try? decoder.decode(data) as? [MKGeoJSONFeature]{ let maskAnnotations = features.map { MaskAnnotation(feature: $0) } DispatchQueue.main.async { self.mapView.addAnnotations(maskAnnotations) } } }.resume() } } extension MaskAnnotationViewController:MKMapViewDelegate{ func mapView(_ mapView: MKMapView, didUpdate userLocation: MKUserLocation) { print("didUpdate") //定位 需import CoreLocation let region = MKCoordinateRegion(center: userLocation.coordinate, latitudinalMeters: 23.5, longitudinalMeters: 121) mapView.setRegion(region, animated: true) print(region) } func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? { guard let annotation = annotation as? MaskAnnotation else{ return nil } let annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: "\(MaskAnnotation.self)", for: annotation) as? MKMarkerAnnotationView annotationView!.canShowCallout = true let infoButton = UIButton(type:.detailDisclosure) annotationView?.rightCalloutAccessoryView = infoButton if let count = annotation.mask?.maskAdult, count == 0 { annotationView?.markerTintColor = .green }else{ annotationView?.markerTintColor = .blue } return annotationView } func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) { let annotation = view.annotation as? MaskAnnotation print(annotation) } func mapView(_ mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) { let annotation = view.annotation as? MaskAnnotation print(annotation) }

以上是做API解析的練習參考的網站

github