-1

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

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

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

4

2 回答 2

1

创建块

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
    }
}
于 2016-03-02T14:11:01.753 回答
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。

于 2016-03-02T14:00:35.950 回答