如何在完成异步请求时调用函数 - Swift 2.0

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

我在这样的 class 中有一个异步请求,

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

我正在从一个视图控制器调用此方法,

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

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

我正在从另一个视图控制器调用相同的函数,

class classTwo{

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

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

现在我只想在 processRequest() 完成后才调用 demoFun()sampleFun()。如果 demoFun() or sampleFun()processRequest() 在同一个 class 中,那么我可以调用 processRequest() 的完成处理程序中的函数。但是,就我而言,我不能这样做,因为我有将近 20 个调用 processRequest() 函数的视图控制器。我无法使用 SynchronusRequest,因为它在 Swift 2.0 中已弃用。那么异步请求完成后如何调用其他函数呢?

您将需要修改您的 processRequest 函数以接收闭包。例如:

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()
            })
        }
    }

现在,无论您在何处调用 processRequest API,您都可以在异步回调处理后立即添加要执行的代码。例如:

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.

创建区块

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
    }
}