注意:重新格式化以使代码更具可读性,必须在此处添加文本,以便系统可以接受编辑。
我的json数据是:
[
{
"language": "en",
"polarity": 10,
"rating": "",
"source": "Facebook",
"text": "FortyLove Sport Centers likes a photo.",
"time": "2013-06-02",
"wordsCount": 6,
"details": "http://tour-pedia.org/api/getReviewDetails? id=53513431ae9eef9405b2f18c"
},
{
"language": "en",
"polarity": 10,
"rating": "",
"source": "Facebook",
"text": "FortyLove Sport Centers likes a status.",
"time": "2013-05-26",
"wordsCount": 6,
"details": "http://tour-pedia.org/api/getReviewDetails?id=53513431ae9eef9405b2f18d"
}
]
我的源代码是
let task = URLSession.shared.dataTask(with: URL(string: "http://tour-pedia.org/api/getReviews?location=Rome&category=poi")!) { (data, response , error) in
if error != nil {
print(error?.localizedDescription ?? "")
}
if let resultArray = (try? JSONSerialization.jsonObject(with: data!, options: [])) as? [[String:Any]] {
for jsonreviews in resultArray {
let review = Review()
review.rating = jsonreviews["rating"] as? Int ?? 0
review.text = jsonreviews["text"] as! String
review.time = jsonreviews["time"] as! String
reviews.append(review)
}
DispatchQueue.main.async {
self.tableview.reloadData() // if you use tableview
}
}
}
task.resume()
我不知道如何按日期排序,帮助我编写代码
答案 0 :(得分:0)
您应该对API调用的响应建模,然后在建模数据的数组上调用sort函数。这是一个关于"使用json"的博客。由Apple: https://developer.apple.com/swift/blog/?id=37
这是一种方法,因为您在评论数组中有数据
func sortByDate(){
let formatter = DateFormatter()
//define your date format
formatter.dateFormat = "yyyy-MM-dd "
formatter.timeZone = TimeZone(identifier: "UTC")
reviews.sort{
let date1 = formatter.date(from: $0.time)
let date2 = formatter.date(from: $1.time)
if date1 != nil && date2 != nil{
return date1! > date2!
}
return false
}
}