【问题标题】:Passing data between controllers using combine not working使用组合在控制器之间传递数据不起作用
【发布时间】:2021-02-14 02:20:12
【问题描述】:

我开始与 swift 结合,但遇到了一些困难(之前有在 swiftui 工作的经验)。 所以问题是如何执行某些操作:

  1. 可以说我有vc1。我从那里去vc2 2.然后我开始异步网络关闭并回到vc1(通过弹出vc2)。
  2. 现在假设当我回到 vc1 时,我只想将一个字符串从 vc2 的 asycnrhoss clousre 转到 vc1。 我怎样才能做到这一点?

我想使用 的发布者 如何订阅我的 vc1 并从 vc2 发布或发送?

我正在使用这种方法,但它不起作用,它永远不会出现在 sink 下的代码.....

public class Parent {
   public  static let shared = Parent()
   public var publisher = PassthroughSibject<String,Never>()
}

class vc1: ViewController {
   func viewdidLoad() {
     let subscription = Parent.shared.oublisehr.sink { (result) in
     print(result)
     }
  }
  func navigatetoVC1() {
  ///// some code to navigate to vc1
  }

  func button() {
    self.navigatetoVC1
  }

}


class vc2: ViewController {

   func viewDidload() {
   ///
   }
  func performsomeOperation() {
     someasyncoperation(completion: { result in
       switch result {
       case .success:
         //send some data to vc1
         Parent.shared.publisher.send("testdata")
       case .failure:
       //send some data to vc1
    })
  self.dismisVC2() //some method to pop out vc2
  } 

}

【问题讨论】:

    标签: swift combine


    【解决方案1】:

    您的代码几乎是正确的,只是您在 viewdidload 中使用了 Anycancellable,因此它的范围越来越大。所以在视图控制器外部使用它作为可选的 AnyCancellable 类型。 下面的代码应该可以工作。

    class vc1: ViewController {
    var subscription = AnyCancellable?
    
       func viewdidLoad() {
         self.subscription = Parent.shared.oublisehr.sink { (result) in
             print(result)
         }
       }
      func navigatetoVC1() {
      ///// some code to navigate to vc1
      }
    
      func button() {
        self.navigatetoVC1
      }
    
    }
    

    【讨论】:

    • 你能分享一些示例代码或一些文章吗?
    • 我还有一个问题,使用单例视图模型是一种好习惯吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-14
    • 2015-05-24
    • 1970-01-01
    相关资源
    最近更新 更多