Search code examples
iosswiftasynchronouscallback

Callback function from caller to callee in swift


I have a view controller and a class for doing the bits to call the services and get the data from server. The ViewController code is below,

class ViewController : UIViewController
{

override func viewDidLoad() {
let parser  = Parser()
parser.connectServer("abc URL" , ..... <gotDataFromServer> ..... )
}

func gotDataFromServer(response:String)
{
...... Do our things here .......
}    
}

and the parser code is below:

class Parser
{
func connectServer(apiURL:String,...<call back function name>...)
    {
        let manager = RequestOperationManager.sharedManager()
        manager.GET(apiURL ,
            parameters: nil,
            success: { (operation,responseObject) ->Void in
                    .....<Call back the function which is passed in parameter> ....
            },
            failure: { (operation , error) in
               print ("error occurred")
        })
    }
}

Now in the above sample code I want to pass call back function gotDataFromServer as a parameter and when the inner function get the response from the server then I want to call this function back. Can anyone please help?


Solution

  • Here's an example how you can do it using closure

    class Parser {
        func connectServer(apiURL: String, completion: String -> Void) {
            // ... make call, get data
            // share the results via completion closure
            completion("data")
        }
    }
    
    class ViewController: UIViewController {
        override func viewDidLoad() {
            let parser = Parser()
    
            // Option #1
            parser.connectServer("mybackend.com/connect") {
                print("received data \($0)")
            }
    
            // Option #2 is the same as Option #1 but a bit longer
            parser.connectServer("mybackend.com/connect") { (data) -> Void in
                print("received data \(data)")
            }
    
            // Option #3 - Or if you have a separate funciton
            // be careful with retain cycle
            parser.connectServer("mybackend.com/connect", completion: gotDataFromServer)
        }
    
        func gotDataFromServer(response:String) {   }
    }