其本质是数据解析的管理器
import Foundation
protocol NetworkDataManagerDelegate: AnyObject {
func updateInterface( _: NetworkDataManager, with currenData: CurrentData)
}
class NetworkDataManager {
weak var delegate: NetworkDataManagerDelegate?
func fetchCurrentData() {
let urlString = "https://run.mocky.io/v3/1d1cb4ec-73db-4762-8c4b-0b8aa3cecd4c"
guard let url = URL(string: urlString) else {return}
let urlSession = URLSession(configuration: .default)
let task = urlSession.dataTask(with: url) { data, responce, error in
if let data = data {
if let currentData = self.parseJSON(withData: data){
self.delegate?.updateInterface(self, with: currentData)
}
}
}
task.resume()
}
func parseJSON(withData data: Data) -> CurrentData?{
let decoder = JSONDecoder()
do {
let currentDataData = try decoder.decode(CurrentDataData.self, from: data)
guard let currentData = CurrentData(currentDataData: currentDataData) else {return nil}
return currentData
} catch let error as NSError {
print(error)
}
return nil
}
}
在tableViewController上我背叛了协议,其中有一个updateInterface()类,问题是如何将数据传输到单元格数组中,以便需要拉起单元格的数量?单元有一个单独的 viewController,它们实际连接到该 viewController。
查看单元格
import UIKit
class CustomCell: UITableViewCell {
@IBOutlet weak var skilsLable: UILabel!
@IBOutlet weak var numbeLable: UILabel!
@IBOutlet weak var nameLable: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
}
这是 tableViewController 本身
class MyTableViewController: UITableViewController {
var cell: [String] = []
let network = NetworkDataManager()
override func viewDidLoad() {
super.viewDidLoad()
network.fetchCurrentData()
network.delegate = self
tableView.rowHeight = 150
self.title = "Team of Developer"
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return cell.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! CustomCell
return cell
}
}
extension MyTableViewController: NetworkDataManagerDelegate{
func updateInterface(_: NetworkDataManager, with currenData: CurrentData) {
}
}