WordPress REST API + Swift [英] Wordpress REST API + Swift

查看:96
本文介绍了WordPress REST API + Swift的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是一名新手开发人员,正在尝试编写一个简单的应用程序,以将来自Wordpress网站的帖子显示为提要.我正在使用Wordpress REST API,并迅速使用它.我陷入了解析JSON并快速呈现它的麻烦.

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.

下面有详细信息,但是如何编码REST API中"title" +"rendered"的双重标识符?

Detail below, but how do I code the dual identifier of 'title' + 'rendered' from the REST API?

到目前为止,我已经迅速了解了这一点:

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()
    }

,但"var title.rendered:String"不被Xcode接受,我得到错误行上的连续声明必须用';'分隔.因此,当在REST API中显示后贴图,内容等时,我该如何去做:

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 

(等)

推荐答案

按如下所示创建另一个Codable类型并更新Post

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
}

这篇关于WordPress REST API + Swift的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆