微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何使用带有 SwiftUI 的 Rest API 获取 Wordpress 帖子的帖子 ID

如何解决如何使用带有 SwiftUI 的 Rest API 获取 Wordpress 帖子的帖子 ID

我正在尝试将我的 wordpress 网站中的一些博客文章包含到我的应用中。我已经使用每个帖子的单独帖子 ID 测试了 API,我让它在我的视图中加载数据。但是,我现在正在尝试获取一个数组,但它似乎没有获取与帖子相关的 ID 来填充视图。我在这里做错了什么?

   let content: MarkdownData
@State var beholdarticles: BeholdArticle?
@State private var htmlContent = ""





let articles: [BeholdArticle] = []



private func loadArticle() {
    
    guard let url = URL(string: "https://behold.hagleyparksda.com/wp-json/wp/v2/posts") else {
        return
        
    }
    URLSession.shared.dataTask(with: url) {data,response,error in
        
        guard let data = data else { return }
        if let decodedData = try? JSONDecoder().decode(BeholdArticle.self,from: data){
            
            dispatchQueue.main.async {
                self.beholdarticles = decodedData
            }
        }
    }.resume()
}

这是 ForEach 循环

var body: some View {
    
    ScrollView (.horizontal) {
       
           
      
        ForEach(articles) { item in
            ZStack {
                     
                        if beholdarticles?.thumbnail != nil {
                            
                            WebImage(url: URL(string: beholdarticles!.thumbnail)!)
                                .resizable()
                                .aspectRatio(contentMode: .fill)
                                .frame(width:350,height: 450)
                            
                        } else {
                            
                            Image("behold_imagecard")
                                    .resizable()
                                    .aspectRatio(contentMode: .fill)
                        }
                        
                        
                        HStack {
                            vstack (alignment: .leading) {
                                Text(beholdarticles?.title.rendered ?? "Loading...")
                                        .font(.system(size: 30,weight: .bold))
                                        .foregroundColor(Color.white)
                                    .frame(width: 270)
    //                            Text(beholdarticles?.title.rendered ?? "Loading...")
    //                                    .font(.system(size: 18,weight: .regular))
    //                                    .foregroundColor(Color.white)
    //                                .frame(width: 270)
                            }
                            Spacer()
                        }
                        
                            
                         
                        vstack {
                            Spacer()
                            HStack {
                                Image(uiImage: #imageLiteral(resourceName: "healthicon"))
                                Text("Spirituality")
                                    .font(.system(size: 23))
                                    .foregroundColor(Color.white)
                                Spacer()
                            }
                            .background(VisualEffectBlurView(blurStyle: .systemUltraThinMaterial))
                        }.onAppear{
                            loadArticle()
                        }
                    
                   
            } .frame(width:350,height: 450)
            .shadow(color: Color(#colorLiteral(red: 0.2549019754,green: 0.2745098174,blue: 0.3019607961,alpha: 1)) .opacity(0.2),radius: 20,x: /*@START_MENU_TOKEN@*/0.0/*@END_MENU_TOKEN@*/,y:14)
            .cornerRadius(30)
        }
        
      
        }

我的数据模型

struct BeholdArticle: Decodable,Identifiable  {

var id: Int
var slug: String
var link: String
var thumbnail: String
var title: BeholdArticleTitle
var content: BeholdArticleContent

enum CodingKeys: String,CodingKey {

    case thumbnail = "jetpack_featured_media_url"
    case slug,link,title,content
    case id = "id"
}
}

struct BeholdArticleTitle: Decodable {

var rendered: String
 }

struct BeholdArticleContent: Decodable {

var rendered: String
}

我只是想用数据填充我的循环,但它似乎没有从 api 调用获取 ID。这里需要一些帮助

我仍然将图像 URL 包裹在条件语句中。目前图像不会通过。我如何将其调整为更新的设置?

  if beholdarticles?.thumbnail != nil {
                                
                                WebImage(url: URL(string: item.thumbnail)!)
                                    .resizable()
                                    .aspectRatio(contentMode: .fill)
                                    .frame(width:350,height: 450)
                                
                            } else {
                                
                                Image("behold_imagecard")
                                        .resizable()
                                        .aspectRatio(contentMode: .fill)
                            }

这是更新后的图片代码

ForEach(articles) { article in
                ZStack {
                         
                            if article.thumbnail != nil {
                                
                                WebImage(url: URL(string: article.thumbnail)!)
                                    .resizable()
                                    .aspectRatio(contentMode: .fill)
                                    .frame(width:350,height: 450)
                                
                            } else {

                                Image("behold_imagecard")
                                        .resizable()
                                        .aspectRatio(contentMode: .fill)
                            }

解决方法

如果您想从该 URL 端点解码 JSON,您将需要使用 [BeholdArticle].self 而不是 BeholdArticle.self,因为它是一个数据数组。

此外,不要在 loadArticle 的每个元素上调用 ForEach(永远不会被调用,因为它一开始没有数据),而是在顶层调用它视图。

这是一个精简的例子:

struct ContentView: View {
    @State private var articles : [BeholdArticle] = []
    
    var body: some View {
        ScrollView {
            VStack (alignment: .leading) {
                ForEach(articles) { article in
                    Text(article.title.rendered)
                        .multilineTextAlignment(.leading)
                    if let thumbnailURL = URL(string: article.thumbnail) {
                       WebImage(url: thumbnailURL)
                           .resizable()
                           .aspectRatio(contentMode: .fill)
                           .frame(width:350,height: 450)
                    }
                    
                }
            }
        }
        .onAppear {
            loadArticles()
        }
    }
    
    private func loadArticles() {
        guard let url = URL(string: "https://behold.hagleyparksda.com/wp-json/wp/v2/posts") else {
            return
        }
        URLSession.shared.dataTask(with: url) {data,response,error in
            
            guard let data = data else { return }
            if let decodedData = try? JSONDecoder().decode([BeholdArticle].self,from: data){
                
                DispatchQueue.main.async {
                    self.articles = decodedData
                }
            }
        }.resume()
    }
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。