swift - 如何捕获通过 SwiftUI 中的函数更改的值更改?

标签 swift swiftui observableobject

我的 View 不检查值是否已更改。你能告诉我为什么或者你能帮助我吗?

您可以在下面看到重要的代码。

我的类(class)

import SwiftUI
import SwiftyStoreKit

class Foo: ObservableObject {
 @Published var Trigger : Bool = false
  
 func VerifyPurchase() { 
      let appleValidator = AppleReceiptValidator(service: .production, sharedSecret: "your-shared-secret")
      SwiftyStoreKit.verifyReceipt(using: appleValidator) { result in
           switch result {
                case .success(let receipt):
                     let productId = "com.musevisions.SwiftyStoreKit.Purchase1"
                     // Verify the purchase of Consumable or NonConsumable
                     let purchaseResult = SwiftyStoreKit.verifyPurchase(
                          productId: productId,
                          inReceipt: receipt) 
                     
                     switch purchaseResult {
                          case .purchased(let receiptItem):
                               print("\(productId) is purchased: \(receiptItem)")
                               
                               self.Trigger.toggle()
                               
                          case .notPurchased:
                               print("The user has never purchased \(productId)")
                               
                               self.Trigger.toggle()
                     }
                case .error(let error):
                     print("Receipt verification failed: \(error)")
                     
                     self.Trigger.toggle()
                     
           }
      }
 } 
} 

在 SceneDelegate 中,我在 sceneDidbecom 的重要代码将值触发为 true,然后如果函数完成,那么我希望触发返回 false

 func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) { 

      let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext

      let foo = Foo()
      let contentView =  ContenView(foo: Foo).environment(\.managedObjectContext, context) 
       
      if let windowScene = scene as? UIWindowScene {
          let window = UIWindow(windowScene: windowScene)
          window.rootViewController = UIHostingController(rootView: contentView)
          self.window = window
          window.makeKeyAndVisible()
      }
 }


 func sceneDidBecomeActive(_ scene: UIScene) {
 let foo = Foo()
 foo.Trigger = true
 foo.VerifyPurchase()
 }

我的 View 在值更改时不会更新自身。

struct ContentView: View {
   @ObservedObject var foo: Foo
 
    var body: some View {
      Text(self.foo.Trigger ? "true" : "false")
    }
}

最佳答案

SwiftyStoreKit.verifyReceipt 是一个异步函数,@Published 变量必须在主线程上更新。

当您在后台更改 Trigger 变量时,尝试添加 DispatchQueue.main.async:

SwiftyStoreKit.verifyReceipt(using: appleValidator) { result in
    ...
    DispatchQueue.main.async {
        self.Trigger = false
    }
}

另请注意,Swift 中的变量通常是小写的 - 即。 触发器而不是触发器


您还在项目中使用了两个不同 Foo 实例。

我建议您从 func sceneDidBecomeActive(_ scene: UIScene) 中删除代码,并将其移至 ContentView 中的 .onAppear :

struct ContentView: View {
   @ObservedObject var foo: Foo
 
    var body: some View {
      Text(self.foo.Trigger ? "true" : "false")
        .onAppear {
            foo.Trigger = true
            foo.VerifyPurchase()
        }
    }
}

也可以代替

Text(self.foo.Trigger ? "true" : "false")

你可以做到

Text(String(describing: self.foo.Trigger))

关于swift - 如何捕获通过 SwiftUI 中的函数更改的值更改?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63937867/

相关文章:

ios - 通过另一个 ObObject 传递 ObservableObject 模型?

折叠列表中的 SwiftUI 导航

swiftui - 如何在 tvOS 上使用 SwiftUI 在多个水平列表之间导航

arrays - SWIFTUI:使用 Array 属性创建类 - 符合 'ObservableObject' 。类(class)!不是结构体

swift - 货币代码返回 nil

swift - 在 SwiftUI 中显示详细 View 的导航标题

SwiftUI - 通过嵌套引用类型传播更改通知

ios - Swift - 从完成处理程序中获取结果

ios - 返回在 UIAlertControllerStyle.ActionSheet 中选择的 Action

Swift 创建一个按钮作为类变量/成员变量