【发布时间】:2017-06-04 13:47:53
【问题描述】:
我需要列出 json 的内容并按日期(部分)排序。到目前为止,我成功获取了 json 并列出了主要内容(名称和时间),但我需要按日期排序。
编辑: 如果我有超过 100 个“项目”(json 对象)并且在某些情况下重复了日期(如下面 json 的前两个对象),那么我希望这些项目位于以日期为标题的部分中每个部分。
Json:
[
{"date_raw":"1/18/2017 12:00:00 AM","name":"Hello 2","hour":"12:00 - 14:00","audio_url":"http://example.com/file2.mp4"},
{"date_raw":"1/18/2017 12:00:00 AM","name":"Hello 1","hour":"10:00 - 12:00","audio_url":"http://example.com/file1.mp4"},
{"date_raw":"1/17/2017 12:00:00 AM","name":"Hello","hour":"10:00 - 12:00","audio_url":"http://example.com/file.mp4"},
{"date_raw":"1/16/2017 12:00:00 AM","name":"Hello","hour":"10:00 - 12:00","audio_url":"http://example.com/file.mp4"}
]
主类:
class MyVC: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var tableView: UITableView!
// date_raw
var section: [String] = []
// date_raw, name, hour, audio_url
var items: [(String, String, String, String)] = []
var dateV:String = ""
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return items.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell:UITableViewCell = UITableViewCell(style: UITableViewCellStyle.subtitle, reuseIdentifier: "cell")
cell.textLabel!.text = items[indexPath.row].1 // get name
cell.detailTextLabel!.text = items[indexPath.row].2 // get hour
return cell;
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
print(items[indexPath.row])
}
func getJson(_ url:String) {
// Asynchronous Http call to your api url, using NSURLSession:
URLSession.shared.dataTask(with: URL(string: url)!, completionHandler: { (data, response, error) -> Void in
if error != nil || data == nil {
print("error")
} else {
do {
let json:NSArray = try (JSONSerialization.jsonObject(with: data!, options:JSONSerialization.ReadingOptions.mutableContainers) as? NSArray)!
for i in 0...json.count-1 {
if let date_raw = (json[i] as AnyObject).value(forKey: "date_raw") as? String,
let name = (json[i] as AnyObject).value(forKey: "name") as? String,
let hour = (json[i] as AnyObject).value(forKey: "hour") as? String,
let audio_url = (json[i] as AnyObject).value(forKey: "audio_url") as? String {
if date_raw != self.dateV {
self.section.append(date_raw)
self.dateV = date_raw;
}
self.items.append(date_raw, name, hour, audio_url)
}
}//End for
//print(self.section)
self.do_table_refresh();
} catch {
print("error")
}
}
}).resume()
// TODO: butonu disable et
}
func do_table_refresh() {
DispatchQueue.main.async(execute: {
self.tableView.reloadData()
self.tableView.isHidden = false
return
})
}
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
tableView.isHidden = true
getJson("http://example.com/my-json-file.json")
}
}
【问题讨论】:
标签: ios json uitableview swift3