【问题标题】:Assign json data to labels将 json 数据分配给标签
【发布时间】:2020-04-16 22:15:34
【问题描述】:

我是 swift 编程的初学者,我想将数据分配给标签

所以我在下面有这段代码

@IBOutlet weak var Infected: WKInterfaceLabel!
@IBOutlet weak var Cured: WKInterfaceLabel!
@IBOutlet weak var Deaths: WKInterfaceLabel!

@IBOutlet weak var OmanInfected: WKInterfaceLabel!
@IBOutlet weak var OmanCured: WKInterfaceLabel!
@IBOutlet weak var OmanDeaths: WKInterfaceLabel!
func check()
{

    // MARK: - CoronaData
    struct CoronaData: Codable {
        var countrydata: [Countrydatum]
        var stat: String
    }
    // MARK: - Countrydatum
    struct Countrydatum: Codable {
        var info: Info
        var totalCases, totalRecovered, totalUnresolved, totalDeaths: Int
        var totalNewCasesToday, totalNewDeathsToday, totalActiveCases, totalSeriousCases: Int
        var totalDangerRank: Int

        enum CodingKeys: String, CodingKey {
            case info
            case totalCases = "total_cases"
            case totalRecovered = "total_recovered"
            case totalUnresolved = "total_unresolved"
            case totalDeaths = "total_deaths"
            case totalNewCasesToday = "total_new_cases_today"
            case totalNewDeathsToday = "total_new_deaths_today"
            case totalActiveCases = "total_active_cases"
            case totalSeriousCases = "total_serious_cases"
            case totalDangerRank = "total_danger_rank"
        }
    }
    // MARK: - Info
    struct Info: Codable {
        var ourid: Int
        var title, code: String
        var source: String
    }

    if let url = URL(string: "https://api.thevirustracker.com/free-api?countryTotal=OM") {
       URLSession.shared.dataTask(with: url) { data, response, error in
          if let data = data {
              do {
                 let decoder = JSONDecoder()
                 let gitData = try decoder.decode(Countrydatum.self, from: data)
                print(gitData.totalCases as Any)
              } catch let error {
                 print(error)
              }
           }
       }.resume()
    }
}

我现在如何将这些值分配给此处的标签(Num labels)

我知道这是一个愚蠢的问题,但请原谅我 我只是想完成程序并学习一些新东西

【问题讨论】:

  • self.Deaths.setText("8")

标签: json swift alamofire apple-watch watchos


【解决方案1】:

你可以下载这个免费的程序来制作结构

查看此example 以使用该结构

         if let url = URL(string: "https://api.thevirustracker.com/free-api?countryTotal=OM") {
           URLSession.shared.dataTask(with: url) { data, response, error in
              if let data = data {
                  do {
                     let decoder = JSONDecoder()
                     let profile = try decoder.decode(ProfileResponse.self, from: data)
                     print(profile.countrydata.first)
                  } catch let error {
                     print(error)
                  }
               }
           }.resume()
        }

您可以使用 setText(:) 或 setAttributedText(:) 方法以编程方式更改文本。

我在 Playground 中复制请求,文本是不同的总线,您需要访问数据的方式是相同的,国家/地区数据是一个数组,因此您需要获取第一个元素

import UIKit
import PlaygroundSupport

// MARK: - ProfileResponse
struct ProfileResponse: Codable {
    var countrydata: [ProfileCountrydatum]
    var stat: String
}

// MARK: - ProfileCountrydatum
struct ProfileCountrydatum: Codable {
    var info: ProfileInfo
    var totalCases, totalRecovered, totalUnresolved, totalDeaths: Int
    var totalNewCasesToday, totalNewDeathsToday, totalActiveCases, totalSeriousCases: Int
    var totalDangerRank: Int

    enum CodingKeys: String, CodingKey {
        case info
        case totalCases = "total_cases"
        case totalRecovered = "total_recovered"
        case totalUnresolved = "total_unresolved"
        case totalDeaths = "total_deaths"
        case totalNewCasesToday = "total_new_cases_today"
        case totalNewDeathsToday = "total_new_deaths_today"
        case totalActiveCases = "total_active_cases"
        case totalSeriousCases = "total_serious_cases"
        case totalDangerRank = "total_danger_rank"
    }
}

// MARK: - ProfileInfo
struct ProfileInfo: Codable {
    var ourid: Int
    var title, code: String
    var source: String
}


class MyViewController : UIViewController {
    override func loadView() {
        let view = UIView()
        view.backgroundColor = .white

        let label = UILabel()
        label.frame = CGRect(x: 150, y: 200, width: 200, height: 20)
        label.text = "Hello World!"
        label.textColor = .black

        view.addSubview(label)
        self.view = view

        if let url = URL(string: "https://api.thevirustracker.com/free-api?countryTotal=OM") {
           URLSession.shared.dataTask(with: url) { data, response, error in
              if let data = data {
                  do {
                     let decoder = JSONDecoder()
                     let gitData = try decoder.decode(ProfileResponse.self, from: data)
                     label.text = "\(gitData.countrydata.first?.totalDeaths ?? 0)"
                  } catch let error {
                     print(error)
                  }
               }
           }.resume()
        }
    }
}
// Present the view controller in the Live View window
PlaygroundPage.current.liveView = MyViewController()

【讨论】:

  • 谢谢你我做了你说的剩下的就是将数据分配给标签怎么做?
  • 就位而不是打印你需要做 Infected.setText("Your_number") developer.apple.com/documentation/watchkit/wkinterfacelabel/…
  • 是的,我知道该怎么做,我现在只想知道如何获取 JSON 信息并将其分配给变量如何做到这一点
  • 让 profile = try decoder.decode(ProfileResponse.self, from: data) self.Deaths.setText("(profile.countrydata.first.totalDeaths)")
【解决方案2】:

countrydata 显示为一个数组,但模型中的相应属性是 String 类型。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-06-07
    • 2016-07-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多