-1

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?

2 Answers2

1

Create blocks

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


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

    func demoFun(){
        //Do some operation here
    }
}
Sanjan Piya
  • 247
  • 2
  • 8
0

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.

Shripada
  • 6,296
  • 1
  • 30
  • 30