iosswiftswift2sendasynchronousrequest

How to call a function on completion of an asynchronus request - Swift 2.0


I have an asynchronus request in a class like this,

class Req{
    func processRequest(){
        NSURLConnection.sendAsynchronousRequest(request, queue: queue, completionHandler:{ (response: NSURLResponse!, data: NSData!, error: NSError!) -> Void in
             //Do some operation here
        })
    }
}

And I am calling this method from one view controller like this,

class classOne{
    func classOneFun(){
        Req().processRequest()
        self.demoFun()
    }

    func demoFun(){
        //Do some operation here
    }
}

And I am calling the same function from another view controller like this,

class classTwo{

    func classTwoFun(){
        Req().processRequest()
        self.sampleFun()
    }

    func sampleFun(){
        //Do some operation here
    }
}

Now I want to call the demoFun() or sampleFun() only after the processRequest() is completed. If demoFun() or sampleFun() and processRequest() are in the same class, then I can call the functions in the completion handler of processRequest(). But, in my case I cannot do that, since I have nearly 20 view controllers that call the processRequest() function. I cannot use SynchronusRequest as it is deprecated in Swift 2.0. So how can I call the other functions once the asynchronus request is completed?


Solution

  • You will need to modify your processRequest function to receive a closure. For example:

    class Req{
    
            func processRequest(callback: Void ->Void){
                NSURLConnection.sendAsynchronousRequest(request, queue: queue, completionHandler:{ (response: NSURLResponse!, data: NSData!, error: NSError!) -> Void in
                     //Do some operation here
                     //Call the callback here:
                     callback()
                })
            }
        }
    

    Now wherever, you want to call the processRequest API, you can add the code you want to execute soon after your asynchronous callback processing. For example:

    class classOne{
        func classOneFun(){
            Req().processRequest(){   //Passing the closure as a trailing closure with the code that we want to execute after asynchronous processing in processRequest
             self.demoFun()
    
    }
        }
    
        func demoFun(){
            //Do some operation here
        }
    }
    

    HTH.