尝试根据 API 调用的结果将 @published bool 设置为 true

问题描述

嗨,首先我对 swift 和编程非常陌生(来自设计领域)。 我正在尝试根据 posts.count 更新 dosNotificationsExist

我在 require 'pp' require 'base64' require 'uri' require 'rack' class Rack::Session::SessionId end c = gets cookie,signature = c.split("--") decoded = Base64.decode64(URI.decode(cookie)) begin object = Marshal.load(decoded) pp object rescue ArgumentError => e puts "Error: " + e.to_s end 我在哪里打印以下内容

Api().getPosts {}

但在外部(在 print("Api().getPosts") print(doesNotificationExist) 中)我仍然得到错误,而不是 @Publihed var doesNotificationExist:Bool = false 不会更新。

请帮帮我,我真的很感谢您对我做错了什么以及我需要做什么的指导。

这是我的代码

loadData() {}

查看我尝试根据 import SwiftUI import Combine public class DataStore: ObservableObject { @Published var posts: [Post] = [] @Published var doesNotificationExist:Bool = false init() { loadData() startApiWatch() } func loadData() { Api().getPosts { [self] (posts) in self.posts = posts if posts.count >= 1 { doesNotificationExist = true } else { doesNotificationExist = false } print("Api().getPosts") print(doesNotificationExist) } print("loadData") print(doesNotificationExist) } func startApiWatch() { Timer.scheduledTimer(withTimeInterval: 60,repeats: true) {_ in self.loadData() } } 设置图像的位置

状态栏控制器:

store.doesNotificationsExist

解决方法

这是一个结束,希望是@escaping@escaping 用于通知接受闭包的函数的调用者,该闭包可能会被存储或以其他方式超过接收函数的范围。因此,您的外部打印语句将首先使用 bool 值 false 被调用,一旦 timer 完成,将调用 closure 更改您的 Bool真实

检查下面的代码 -:

import SwiftUI


public class Model: ObservableObject {
    //@Published var posts: [Post] = []
    @Published var doesNotificationExist:Bool = false
    
    init() {
        loadData()
       // startApiWatch()
    }
    
    func loadData() {
        
        getPost { [weak self] (posts) in
            //self.posts = posts

            if posts >= 1 {
                self?.doesNotificationExist = true
            }
            else {
                self?.doesNotificationExist = false
            }
            
            print("Api().getPosts")
            print(self?.doesNotificationExist)
        }
        print("loadData")
        print(doesNotificationExist)
    }
    
    func getPost(completion:@escaping (Int) -> ()){
        Timer.scheduledTimer(withTimeInterval: 5,repeats: true) {_ in
            completion(5)
            
        }
    }
}

struct Test1:View {
    @ObservedObject var test = Model()
    var body: some View{
        Text("\(test.doesNotificationExist.description)")
    }
}