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

How do I catch a value change that was changed via a function in SwiftUI?

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

重要代码见下方

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

我的视图在值更改时不会自我更新。

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 中的变量通常是 小写的 - 即。 trigger 而不是 Trigger.


您还在项目中使用了两个 不同 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))