Search code examples
swiftblock

How to create multiple instance of block in Swift?


I have defined a block which return after webservice call.

typealias Receive  = ([AnyHashable : Any]) -> Void

func method(_ paramter: paramter, block:@escaping Register){
   //some code
}

And I have called this method from appDelegate.swift.

handler.shared.method(_ paramter) { (isGranted, token, error) in
   //some code
}

This is working as expected.

Now If I call the same method from viewcontroller.swift The block enters only in viewcontroller after getting response.

I want to to create multiple instance of the same block so that when I get response it should enter appdelegate's as well as viewcntroller's background block.


Solution

  • It is not good idea to do that but as you insist, please follow following code.

    You can add blocks into whereToPassData and whenever you get the response notify to all.

    import Foundation
    import UIKit
    
    public class AppGlobalManager:NSObject {
        static let sharedManager = AppGlobalManager()
    
        private override init() {
            super.init()
            //This prevents others from using the default '()' initializer for this class.
        }
    
        var whereToPassData:[Register?] = []
    
        typealias Register  = ([AnyHashable : Any]) -> Void
    
        func method(_ paramter:Any, block:@escaping Register){
            //some code
            for ref in whereToPassData {
                ref?(["test":"test"])
            }
            self.whereToPassData.removeAll()
        }
    }
    
    public class yourvc :UIViewController {
        public override func viewDidLoad() {
            var block = { (test:[AnyHashable : Any]) in
            }
    
            AppGlobalManager.sharedManager.whereToPassData.append(block)
            AppGlobalManager.sharedManager.method(for: "test")
        }
    }