Swift: Asynchronous callback

后端 未结 4 1162
傲寒
傲寒 2020-12-07 23:29

How do I make asynchronous callbacks in swift? I\'m writing a little Framework for my app because it\'s supposed to run on both, iOS und OS X. So I put the main code that is

4条回答
  •  悲&欢浪女
    2020-12-08 00:02

    I've just made this little example: Swift: Async callback block pattern example

    Basically there is ClassA:

    //ClassA it's the owner of the callback, he will trigger the callback when it's the time
    class ClassA {
        //The property of that will be associated to the ClassB callback
        var callbackBlock : ((error : NSError?, message : String?, adress : String? ) -> Void)?
    
        init() {
            //Do Your staff
        }
    
        //Define your function with the clousure as a parameter
        func yourFunctionWithCallback(#functionCallbackParameter : (error : NSError?,message : String?, adress : String?) -> ()) {
            //Set the calback with the calback in the function parameter
            self.callbackBlock = functionCallbackParameter
        }
    
        //Later On..
        func callbackTrigger() {
            self.callbackBlock?(error: nil,message: "Hello callback", adress: "I don't know")
    
        }
    }
    

    And ClassB:

    //ClassB it's the callback reciver the callback
    class ClassB {
        @IBAction func testCallbackFunction(sender: UIButton) {
            let classA = ClassA()
            classA.yourFunctionWithCallback { (error, message, adress) -> () in
                //Do your stuff
            }
        }
    }
    

    ClassA: it's the owns a property witch is the callbackBlock. ClassB will set this property by Call the yourFunctionWithCallback function. Later on then ClassA it's ready, will trigger the callback by calling the callBackBlock inside the callbackTrigger function.

    ClassB: will call the ClassA method to set the callback block and wait until the block has been triggered.

提交回复
热议问题