【发布时间】:2020-08-05 15:49:31
【问题描述】:
我有以下 json 的样子:
"message": "Something message here"
"data": [
{ "_id": "671672167bhw2hw"
"photo": "https://uploads.example.com/671672167bhw2hw.jpg"
"description": "Something description here"
"date": "2020-07-01T09:44:15.448Z"
"user": "John Doe"
}
]
}
我使用 SwiftifyJSON 库来解码和解析 JSON。我的代码是这样的:
class Post: NSObject {
var message: String
var text: String?
var photoURL: URL?
var date: Date?
}
init(json: JSON) {
self.user = User(id: json["user_id"].stringValue,
name: json["user"].stringValue,
photoURL: URL(string: json["user_photo"].stringValue))
self.message = json["message"].stringValue
self.objectId = json["data"]["_id"].stringValue
self.text = json["data"]["description"].string
self.date = DateFormatter.iso8601.date(from: json["data"]["date"].stringValue)
}
和我的 ApiManager 扩展
static func getPosts(before date: Date? = nil, withSuccess success: @escaping (Bool, [Post]) -> Void) {
guard let url = URL(string: ApiEndpoint.Wall.getPosts) else {
success(false, [Post]())
return
}
var json = [String: String]()
DispatchQueue.global(qos: .background).async {
ApiManager.request(url: url, method: .post, parameters: json) { response, statusCode in
switch statusCode {
case 200:
success(true, ApiManager.getWallPostsFrom(response: response))
return
default: break
}
success(false, [Post]())
return
}
}
}
private static func getPostsFrom(response: DataResponse<Any>) -> [Post] {
var result = [Post]()
guard let value = response.result.value,
let jsonArray = JSON(value).array else { return result }
for json in jsonArray {
let object = Post(json: json)
result.append(object)
}
return result
}
}
我得到 200 的响应,没关系。 但仍然无法在 PostViewController 中显示数据。怎么了?另外,我将自己的库用于应用程序中的选项卡,例如联系人、消息、讨论面板等,因此我将自己的库用于任何选项卡的一些文件、模型、视图和资产。
下面是我的 PostViewController,用于显示来自 JSON 的数据。
private func tryGetPosts() {
canLoadPosts = false
tableView.dataState = .downloading
ApiManager.getPosts(before: Posts.last?.date) { [weak self] (success, objects) in
self?.tableView.dataState = .noData
print("Objects count: ", objects)
guard objects.count > 0 else { return }
#warning("Insert animation")
self?.tableView.beginUpdates()
self?.Posts += objects
let indexPaths = (self!.Posts.count - objects.count ..< self!.Posts.count)
.map { IndexPath(row: $0, section: 0) }
self?.tableView.insertRows(at: indexPaths, with: .top)
self?.tableView.endUpdates()
self?.Posts.insert(contentsOf: objects, at: self?.Posts.count ?? 0)
self?.tableView.reloadData()
self?.canLoadWallPosts = true
}
请给予任何回复和建议。 最好的问候。
【问题讨论】:
-
删除
SwiftyJSON并使用Decodable。您对字典键的处理看起来非常混乱。例如,JSON(value).array也应该指向什么。 -
你得到的 json 是一个数组,你试图解析的数据在该数组的 0 索引上,我在你的 json 中看不到一些键也使用 json["_id"] .stringValue 而不是 json["data"]["_id"].stringValue 因为我猜这里数据不可用,请在 init mathod 中使用 print 语句来确定
标签: ios json swift tableview cell