【发布时间】:2020-04-04 00:25:00
【问题描述】:
我正在编写一个从 Timezonedb API 提取数据以获取可用时区列表的应用:
https://timezonedb.com/references/list-time-zone
我正在尝试解析当前格式为“Europe/Andorra”的 zoneName。我的问题是如何拆分 JSON 字符串以仅在表格视图中显示城市名称,即“安道尔”?
这是我收到的回复:
{
"status":"OK",
"message":"",
"zones":[
{
"countryCode":"AD",
"countryName":"Andorra",
"zoneName":"Europe\/Andorra",
"gmtOffset":7200,
"timestamp":1464453737
},
{
"countryCode":"AE",
"countryName":"United Arab Emirates",
"zoneName":"Asia\/Dubai",
"gmtOffset":14400,
"timestamp":1464460937
},
{"
countryCode":"AF",
"countryName":"Afghanistan",
"zoneName":"Asia\/Kabul",
"gmtOffset":16200,
"timestamp":1464462737
}]}
这是我的代码:
型号:
struct TimeZones: Codable {
let status, message: String?
let zones: [Zone]?
}
struct Zone: Codable {
let countryCode, countryName, zoneName: String?
let gmtOffset, timestamp: Int?
}
这是网络代码:
var cities: [Zone] = []
func getAvailableTimeZones() {
let config = URLSessionConfiguration.default
let session = URLSession(configuration: config)
let url = Bundle.main.url(forResource: "data", withExtension: "json")!
let task = session.dataTask(with: url) { data, response, error in
// Check for errors
guard error == nil else {
print ("error: \(error!)")
return
}
// Check that data has been returned
guard let content = data else {
print("No data")
return
}
do {
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
let timeZones = try decoder.decode(TimeZones.self, from: content)
if let zones = timeZones.zones {
self.cities.append(contentsOf: zones)
}
} catch let err {
print("Err", err)
}
}
// Execute the HTTP request
task.resume()
}
TableViewController:
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "searchResultsCell", for: indexPath)
cell.textLabel?.text = cities[indexPath.row].zoneName
return cell
}
任何帮助表示赞赏。谢谢。
【问题讨论】:
-
如果格式始终相同(即大陆/国家/地区名称),请执行以下操作: let string = "Europe/Andorra" let str = string.split(separator: "/") let cityName = str [1]
-
这能回答你的问题吗? Split a String into an array in Swift?