【问题标题】:Show API data from console window in UITableView (right side)在 UITableView 的控制台窗口中显示 API 数据(右侧)
【发布时间】:2021-02-11 05:36:00
【问题描述】:

我正在创建这个“天气应用”

我是 swift 新手,我对 API 的了解更少。

我想我能够从 [1]:https://api.met.no/weatherapi/locationforecast/2.0/documentation%23!/data/get_compact#!/data/get_compact_format API,但它显示在控制台窗口中,而我基本上试图让它出现在我的 UItableview 单元格中。

谁能帮忙?

这是我的 viewController.swift 文件:

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var tableView: UITableView!
    
    let data = ["Nå", "Neste time", "Neste 6 timer", "Neste 12 timer"]
    
    let subtitles = ["Temperatur:", "Vær:", "Vær:", "Vær:"]
    
    
    struct WeatherManager: Codable {
        let air_temperature: Int
        let next_1_hours: Int
        let next_6_hours: Int
        let next_12_hours: String
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        metAPI.shared.fetchWeatherManager()
        
        tableView.delegate = self
        tableView.dataSource = self
    }
    
    }


extension ViewController: UITableViewDelegate {
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        print("You tapped me")
    }
}

extension ViewController: UITableViewDataSource {
    
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return data.count
    }

    
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "firstCell", for: indexPath)
        
        cell.textLabel?.text = data[indexPath.row]
        cell.detailTextLabel?.text = subtitles[indexPath.row]
        
        return cell            
    }

}

这是我的 weatherManager.swift 文件:

final class metAPI {
    
    static let shared = metAPI()
    
    func fetchWeatherManager() {
        let url = URL(string: "https://api.met.no/weatherapi/locationforecast/2.0/compact.json?lat=10.74481&lon=59.91116")!

        let task = URLSession.shared.dataTask(with: url) {(data, response, error) in
            guard let data = data else { return }
            print(String(data: data, encoding: .utf8)!)
        }

        task.resume()
        
        /*let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
            
            guard let data = data else {
                print("data was nil")
                return
            }
            
            guard (try? JSONDecoder().decode(WeatherManager.self, from: data)) != nil else {
                print("couldnt decode json")
                return
            }
            
        }
        task.resume()
    }*/
    
}
    
struct WeatherManager: Codable {
    let air_temperature: Int
    let next_1_hours: Int
    let next_6_hours: Int
    let next_12_hours: String
}
}

我希望在每个单元格的右侧显示不同的数据,所以:

air_temperature: Int, 10 度 next_1_hours: Int, Rain 4mm next_6_hours:Int,多云 3mm next_12_hours:字符串,太阳

如果有人可以帮助我一点吗? :)

【问题讨论】:

  • 有两个主要问题:JSON 似乎与数据模型不匹配,您根本没有使用解码后的数据。此外,不要忽略 try? 的错误。添加一个 do catch 块并打印错误。

标签: ios swift api uitableview


【解决方案1】:

您使用的默认 UITableViewCell 在项目的设计和放置方面非常有限。

要更好地控制项目的类型及其在每个单元格上的位置,最好的办法是创建一个自定义 UITableViewCell 并将 UILabel 布局到您想要的位置。

这是一个例子:https://www.ralfebert.de/ios-examples/uikit/uitableviewcontroller/custom-cells/

【讨论】:

    【解决方案2】:

    如果您想在单元格中显示所有这些数据,您将无法使用默认单元格,至少如果您想优雅地做到这一点。使用您想要的所有标签、图标/图像创建您自己的自定义单元格,然后您将能够以更直观的方式填写数据。

    如果您使用故事板,您可以使用它在表格视图中提供给您的单元格来模拟您自己的自定义单元格。放置您的标签、图像视图、约束等,然后在一个新的 swift 文件中创建您的 outlet,然后代替:

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "firstCell", for: indexPath)
        
        cell.textLabel?.text = data[indexPath.row]
        cell.detailTextLabel?.text = subtitles[indexPath.row]
        
        return cell            
    }
    

    您将添加为单元格创建的类的名称作为 cellForRowAt 的返回类型,如下所示:

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> {customCellNameHere} {
        let cell = tableView.dequeueReusableCell(withIdentifier: "firstCell", for: indexPath)
        
        {customCellNameHere}.{whateverYouNamedItInTheOutlet}.text = data[indexPath.row]
        {customCellNameHere}.{whateverYouNamedItInTheOutlet}.text = subtitles[indexPath.row]
        
        return cell            
    }
    

    【讨论】:

    • 我不需要显示 API 中的所有数据。(很多)只有以下数据:空气温度:例如:10 摄氏度 next_1_hours:例如:雨 - 2 毫米 next_6_hours:例如:多云next_12_hours: eg: Rain 6mm,需要显示在单元格的右侧。我在创建自定义单元格时没有问题,而是从 API 接收数据并出现在我的应用程序中
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-09-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多