Wordpress REST API + Swift

*爱你&永不变心* 提交于 2021-01-28 04:49:34

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!