gpt4 book ai didi

ios - 如何从 json 按日期排序帖子

转载 作者:行者123 更新时间:2023-11-29 00:25:33 24 4
gpt4 key购买 nike

注意:重新格式化以使代码更具可读性,必须在此处添加文本,以便系统可以接受编辑。:

我的 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()

我不知道如何按日期排序,请帮助我编写代码

最佳答案

您应该对 API 调用的响应进行建模,然后对建模数据的数组调用排序函数。这是 Apple 关于“使用 json”的博客: 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
}

}

关于ios - 如何从 json 按日期排序帖子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43132535/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com