SwiftUI 中级之获取API数据并显示(2020)

1. 定义struct



import Foundation


struct Features: Decodable, Hashable {
    var properties: Properties
    var geometry: Geometry
}

struct Properties: Decodable, Hashable {
    var mag: Double
    var place: String
    var time: Double
    var detail: String
    var title: String
    
}
struct Geometry: Decodable, Hashable {
    var type: String
    var coordinates: [Double]
}


struct QuakeAPIList: Decodable {
    var features: [Features]
}

2. 创造请求class



import Foundation

class NetworkingManager : ObservableObject {
 
  
  @Published var dataList = QuakeAPIList(features: [])
  
  init() {
      guard let url = URL(string: "https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/2.5_day.geojson") else {return}
      
      URLSession.shared.dataTask(with: url) {
          (data, _, _) in
          guard let data = data else {return}
          
          let dataList = try! JSONDecoder().decode(QuakeAPIList.self, from: data)
          
          DispatchQueue.main.async {
              self.dataList = dataList
              
             // print(dataList.features)
              
              
          }
      }.resume()
  }
}

界面显示

  1. 主页面
import SwiftUI

struct ContentView: View {
    
    @ObservedObject var networkingManager = NetworkingManager()
    
    var body: some View {
        NavigationView {
        List(networkingManager.dataList.features, id: \.properties) { data in
            
            NavigationLink(destination: QuakeDetails(data: data)) {
               CellRow(data: data)
                
            }.navigationBarTitle("Quakes")
           
        }
      }
    }
}

行页面



import SwiftUI

struct CellRow: View {
    var data: Features
    var body: some View {
        HStack(alignment: .center, spacing: 9) {
            VStack(alignment: .leading) {
                VStack {
                    Text(String(data.properties.mag))
                    .bold()
                        .foregroundColor(.white)
                        .font(.headline)
                }.frame(width: 100, height:  100)
                    .background(Color.green)
            }.clipShape(Circle())
                .overlay(Circle().stroke(Color.gray, lineWidth: 1))
            .shadow(radius: 10)
            
            VStack {
                Text(data.properties.place)
                    .foregroundColor(.gray)
                .bold()
                
                Text("Time: \(timeConverter(timeStamp: data.properties.time))")
                .italic()
                    .foregroundColor(.orange)
                    .font(.subheadline)
                    .padding(.top, 2)
            }
            
            
        }
    }
}


详细页面

//
//  QuakeDetails.swift
//  QuakesApp-New-XC11
//
//  Created by Paulo Dichone on 10/2/19.
//  Copyright © 2019 Paulo Dichone. All rights reserved.
//

import SwiftUI
import Foundation
import UIKit
import MapKit

struct QuakeDetails: View {
   var data: Features
   var body: some View {
       ZStack(alignment: .top) {
           MapView(data: data)
               .edgesIgnoringSafeArea(.all)
            
           VStack(alignment: .center, spacing: 6) {
               Text(String(data.properties.mag))
                   .font(.largeTitle)
               
               Text(data.properties.place)
                   
           }.clipShape(Rectangle())
               .frame(width: nil, height: nil)
               .padding(.all, 20)
               .background(Color.green)
           .shadow(radius: 9)
           .cornerRadius(9)
               .opacity(0.8)
       }
   }
}

struct MapView: UIViewRepresentable {
   var data: Features
   
   func makeUIView(context: Context) -> MKMapView {
       MKMapView(frame: .zero)
   }
   
   func updateUIView(_ uiView: MKMapView, context: Context) {
       
       let annotation = MKPointAnnotation()
       
       let coordinate = CLLocationCoordinate2D(latitude: data.geometry.coordinates[1], longitude: data.geometry.coordinates[0])
       
       let span = MKCoordinateSpan(latitudeDelta: 1.0, longitudeDelta: 1.0)
       
       let region = MKCoordinateRegion(center: coordinate, span: span)
       
       uiView.setRegion(region, animated: true)
       
       annotation.coordinate = coordinate
       annotation.title = data.properties.place
       annotation.subtitle = "Magnitude: \(data.properties.mag)"
       
       uiView.addAnnotation(annotation)
       
       
       
   }
   
}

最终效果

SwiftUI 中级之获取API数据并显示(2020)_第1张图片

更多SwiftUI教程和代码关注专栏

你可能感兴趣的:(ios,swift)