Swift 中从调用者到被调用者的回调函数

问题描述 投票:0回答:2

我有一个视图控制器和一个类,用于执行调用服务并从服务器获取数据的操作。 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")
        })
    }
}

现在在上面的示例代码中,我想将回调函数

gotDataFromServer
作为参数传递,当内部函数从服务器获取响应时,我想回调该函数。 有人可以帮忙吗?

ios swift asynchronous callback
2个回答
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")
        })
    }
}

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) {   }
}
© www.soinside.com 2019 - 2024. All rights reserved.