注:请自行封装API数据请求接口
下载开发工具Xcode
新建项目
输入自己的项目名称等信息,这里使用的是Storyboard界面
创建HttpSender类,新建Swift文件。本次提供POST请求。
import Foundation
class HttpSender {
//JSON 解析器
private static let decoder = JSONDecoder()
//http-post请求
/**
T : 范型
urlString : 请求url地址
params:传递参数
callback :回掉
*/
public static func post<T: Decodable>(_ type: T.Type, _ urlString: String, _ params: [String:String], _ callback: @escaping (T?) -> Void) {
//传递参数
var query = ""
for (key, value) in params {
query += "\(key)=\(value)&"
}
query.removeLast()
//调用post请求
post(type, urlString, query, callback)
}
public static func post<T: Decodable>(_ type: T.Type, _ urlString: String, _ params: String, _ callback: @escaping (T?) -> Void) {
// Prepare URL
let url = URL(string: urlString)
guard let requestUrl = url else { fatalError() }
// Prepare URL Request Object
var request = URLRequest(url: requestUrl)
request.httpMethod = "POST"
// HTTP Request Parameters which will be sent in HTTP Request Body
// Set HTTP Request Body
request.httpBody = params.data(using: String.Encoding.utf8);
// Perform HTTP Request
let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
// Check for Error
if let error = error {
print("Error took place \(error)")
return
}
// Convert HTTP Response Data to a String
if let data = data, let dataString = String(data: data, encoding: .utf8) {
let info = convertJsonToType(data, T.self)
callback(info)
}
}
task.resume()
}
// 解析json
private static func convertJsonToType<T: Decodable>(_ json: Data, _ toType: T.Type) -> T? {
do {
if T.self == Int.self {
let dataString = String(data: json, encoding: .utf8) ?? "-1"
let res: Int? = Int(dataString)
return res as! T?
}
return try decoder.decode(toType, from: json)
} catch {
//解析失败
print("Couldn't parse json as \(T.self): \n\(error)")
}
return nil
}
}
创建需要的实体类对象,方便解析JSON数据
WeatherModel.swift
import Foundation
class weatherModel: Identifiable, Decodable {
public var errcode: Int = 0 // 返回错误代码
public var errmsg: String = "" //返回信息
public var update_time: String = "" //更新时间
public var cityid: String = "" //城市id
public var province: String = "" //省份
public var city: String = "" //当前城市
public var day: dayModel = dayModel() //当天信息
public var week: [weekModel] = [] //一周以内的信息
public var alarm: [alarmModel] = [] //天气预警
}
class dayModel: Identifiable, Decodable {
public var tem: String = "" // 当天天气温度
public var pressure: String = "" //当天气压
public var rain: String = "" // 当天降雨
public var feel: String = "" //当天感觉指数
public var wea: String = "" //当天天气
public var wea_img: String = "" // 当天天气图标
public var humidity: String = "" // 当天天气湿度
public var win: String = "" //当天风向
public var win_speed: String = "" //当天风速
public var air: String = "" //当天空气指数
public var air_level: String = "" //当天空气质量
}
class weekModel: Identifiable, Decodable {
public var date: String = "" //
public var week: String = "" //周几
public var day_tem: String = "" //当天温度
public var day_wea: String = "" //当天天气
public var day_wea_img: String = "" //当天天气图标
public var day_win: String = "" //当天风向
public var day_win_speed: String = "" //当天风速
public var night_tem: String = "" //当夜温度
public var night_wea: String = "" //当夜天气
public var night_wea_img: String = "" //当夜天气图标
public var night_win: String = "" //当夜天气风向
public var night_win_speed: String = "" //当夜风速
public var hours: [hourModel] = [] //当天天气详情
}
class hourModel: Identifiable, Decodable {
public var time: String = "" //具体时间
public var icon: String = ""// 天气图标库
public var wea: String = "" //天气
public var wea_img: String = "" //天气图标
public var tem: String = "" //天气温度
public var rain: String = "" //
public var win: String = "" //天气风向
public var win_meter: String = "" //天气风速
public var pressure: String = "" //天气压力
public var humidity: String = "" //天气湿度
}
class alarmModel: Identifiable, Decodable {
public var alarm_type: String = "" // 预警类型
public var alarm_level: String = "" // 预警类型
public var alarm_title: String = "" // 预警标题
public var alarm_content: String = "" //预警内容
}
WeekModel.swift
import Foundation
class Week:Decodable, Identifiable {
public var nums: Int = 0
public var cityid: String = ""
public var city: String = ""
public var update_time: String = ""
public var data:[OneDay] = []
}
class OneDay:Decodable, Identifiable {
public var date: String = ""
public var wea: String = ""
public var wea_img: String = ""
public var tem_day: String = ""
public var tem_night: String = ""
public var win: String = ""
public var win_speed: String = ""
}
在Main.storyboard文件添加组件。可以如下图所示,具体可以按照自己需求添加即可
因为我要使用到页面跳转,所以我首页设置为NavigationController
在Main.storyboard中,选择首页,选择Editor->Embed In->Navigation Controller 如下图所示
添加组件,可参照如下图所示
测试机型效果图
把添加的组件绑定到ViewController里
这里打断一下,我写错了一点,我首页应该展示的是24小时天气情况,解析数据的方式是一样的。
在ViewController中加两个扩展(UITableViewDelegate、UITableViewDataSource),如图所示
最后在ViewController里添加数据请求方式。完整版的代码如下
import UIKit class ViewController: UIViewController { public var weather = weatherModel() var apiUrl = "" //替换为自己的API接口 var time = "" var week_wea:[weekModel] = [] var hours:[hourModel] = [] override func viewDidLoad() { super.viewDidLoad() updateWeaInfo() // Do any additional setup after loading the view. } @IBOutlet weak var icon: UIImageView! //天气图标 @IBOutlet weak var hourTable: UITableView! //一天天气 @IBOutlet weak var weatherTem: UILabel! //天气温度 private func updateWeaInfo() { HttpSender.post(weatherModel.self, apiUrl, "") {wea in if let data = wea { self.weather = data self.time = data.update_time self.week_wea = data.week self.hours = data.week[0].hours } DispatchQueue.main.async { let image = UIImage(named: self.weather.day.wea_img) self.icon.image = image self.weatherTem.text = self.weather.day.tem + "°" self.hourTable.dataSource = self self.hourTable.estimatedRowHeight = 200 self.hourTable.rowHeight = UITableView.automaticDimension self.hourTable.reloadData() } } } } extension ViewController: UITableViewDelegate { func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { } } extension ViewController: UITableViewDataSource { func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return hours.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = hourTable.dequeueReusableCell(withIdentifier: "hour_cell", for: indexPath) as! CellTableViewCell // 当天每小时天气 let hour:hourModel = hours[indexPath.row] let time = hour.time let info = time + "的温度:" + hour.tem + "°\t" + hour.wea + "\n风向:" + hour.win + "\n风速:" + hour.win_meter + "\n湿度:" + hour.humidity + "\n气压:" + hour.pressure // cell.textLabel?.text = info cell.label_text.text = info let image = UIImage(named: hour.wea_img) cell.icon.image = image return cell } }
运行如下图所示