问题
I'm a novice developer trying to write a simple app that presents posts from a Wordpress site as a feed. I'm using the Wordpress REST API and consuming that within swift. I'm getting stuck at parsing the JSON and presenting it in swift.
Detail below, but how do I code the dual identifier of 'title' + 'rendered' from the REST API?
So far I've got this in swift:
import SwiftUI
struct Post: Codable, Identifiable {
let id = UUID()
var title.rendered: String
var content.rendered: String
}
class Api {
func getPosts(completion: @escaping ([Post]) -> ()) {
guard let url = URL(string: "https://councillorzamprogno.info/wp-json/wp/v2/posts") else { return }
URLSession.shared.dataTask(with: url) { (data, _, _) in
guard let data = data else { return }
let posts = try! JSONDecoder().decode([Post].self, from: data)
DispatchQueue.main.async {
completion(posts)
}
}
.resume()
}
but the "var title.rendered: String" isn't accepted by Xcode, I get the error "Consecutive declarations on a line must be seperated by ';'. So how should I go about getting the post tile, content etc. when it appears like this in the REST API:
{
id: 1216,
date: "2020-11-18T00:51:37",
date_gmt: "2020-11-17T13:51:37",
guid: {
rendered: "https://councillorzamprogno.info/?p=1216"
},
modified: "2020-11-18T01:31:52",
modified_gmt: "2020-11-17T14:31:52",
slug: "the-nsw-2020-state-redistribution",
status: "publish",
type: "post",
link: "https://councillorzamprogno.info/2020/11/18/the-nsw-2020-state-redistribution/",
title: {
rendered: "The NSW 2020 State Redistribution"
},
content: {
rendered: " <figure class="wp-block-embed is-type-video is-provider-youtube
(etc.)
回答1:
Create another Codable
type as below and update Post
,
struct Rendered: Codable {
var rendered: String
}
struct Post: Codable, Identifiable {
let id = UUID()
var title: Rendered
var content: Rendered
}
来源:https://stackoverflow.com/questions/64951948/wordpress-rest-api-swift