了解 swift Alamofire finishHandler

2023-11-22

我的 API 类中有这两个方法来从 API 获取数据:

func authenticateUser(completionHandler: (responseObject: String?, error: NSError?) -> ()) {
        makeAuthenticateUserCall(completionHandler)
    }

    func makeAuthenticateUserCall(completionHandler: (responseObject: String?, error: NSError?) -> ()) {
        Alamofire.request(.GET, loginUrlString)
            .authenticate(user: "a", password: "b")
            .responseString { request, response, responseString, responseError in
                completionHandler(responseObject: responseString as String!, error: responseError)
        }
    }

然后在另一个类中我使用以下代码来访问数据:

API().authenticateUser{ (responseObject, error) in
    println(responseObject)
}

该代码可以工作,但我不完全理解它。

  1. func verifyUser 有参数completionHandler: (responseObject: String?, error: NSError?) -> (),这是对completionHandler方法的引用吗?或者它是一个物体? -> () 的目的是什么?
  2. 当我调用authenticateUser函数时,我如何实际访问响应?我的任何 api 函数中都没有返回, .. } 语法中的 funcname{(parameter,parameter) 看起来真的很奇怪。

completionHandler是一个闭包参数。正如 Swift 文档所说:

闭包是独立的功能块,可以在代码中传递和使用。 Swift 中的闭包类似于 C 和 Objective-C 中的块以及其他编程语言中的 lambda。

因此,闭包的用途是添加一些您自己想要添加到函数执行中的功能。

在你的情况下,你打电话authenticateUser并且你传递了一个接收的闭包(responseObject, error)并执行println(responseObject). authenticateUser()根据以下规定收到您的结案completionHandler参数,然后调用makeAuthenticateUserCall()通过你的completionHandler关闭它。

话又说回来,看看定义你可以看到func makeAuthenticateUserCall(completionHandler: (responseObject: String?, error: NSError?) -> ())这意味着就像authenticateUser() makeAuthenticateUserCall()是一个接收闭包作为参数的函数,其名称为completionHandler. makeAuthenticateUserCall()使用发出网络请求阿拉莫火然后您再次捕获作为参数传递的闭包下的响应responseString()方法。所以你有了:

//here you call authenticateUser with a closure that prints responseObject
API().authenticateUser{ (responseObject, error) in
    println(responseObject)
}

Then:

//authenticateUser receives your closure as a parameter
func authenticateUser(completionHandler: (responseObject: String?, error: NSError?) -> ()) {
    //it passes your closure to makeAuthenticateUserCall
    makeAuthenticateUserCall(completionHandler)
}

//makeAuthenticateUserCall receives your closure
func makeAuthenticateUserCall(completionHandler: (responseObject: String?, 
error: NSError?) -> ()) {
    Alamofire.request(.GET, loginUrlString)
        .authenticate(user: "a", password: "b")
        //here you pass a new closure to the responseString method
        .responseString { request, response, responseString, responseError in
            //in this closure body you call your completionHandler closure with the 
            //parameters passed by responseString and your code gets executed 
            //(that in your case just prints the responseObject)
            completionHandler(responseObject: responseString as String!, error: responseError)
    }
}

有关更多信息,请阅读文档:迅速关闭

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

了解 swift Alamofire finishHandler 的相关文章

随机推荐