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