回调函数从调用者到被调用者在swift中

时间:2016-02-10 15:07:26

标签: ios swift api asynchronous callback

我有一个视图控制器和一个用于执行调用服务并从服务器获取数据的位的类。 ViewController代码如下,

class ViewController : UIViewController
{

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

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

,解析器代码在下面,

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

现在在上面的示例代码中,我想传递回调函数&#34; gotDataFromServer&#34;作为参数,当内部函数从服务器获得响应时,我想要回调用此函数。 任何人都可以帮忙。

2 个答案:

答案 0 :(得分:1)

您可以使用委托来实现这一目标。试试下面的代码

class ViewController : UIViewController, DataDelegate
{

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

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

在解析器中添加协议如下

protocol DataDelegate {
    func gotDataFromServer(response:String)
}
class Parser
{
var delegate : DataDelegate!
func connectServer(apiURL:String,...<call back function name>...)
    {
        let manager = RequestOperationManager.sharedManager()
        manager.GET(apiURL ,
            parameters: nil,
            success: { (operation,responseObject) ->Void in
                    delegate.gotDataFromServer("") //parameter is your data
            },
            failure: { (operation , error) in
               print ("error occurred")
        })
    }
}

答案 1 :(得分:0)

这是一个如何使用闭包

来做到这一点的例子
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) {   }
}