迅速3调用函数并返回完成闭包 [英] swift 3 calling function with completion closure in return

查看:84
本文介绍了迅速3调用函数并返回完成闭包的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Swift的新人,遇到了一些麻烦。我试图从我的请求中获取价值。我可以将其打印为闭包,但是我想在VC上以字符串形式获取并使用它,但是要在功能登录上使用它。我不知道如何从关闭中返回。

I am new at Swift and I am having some trouble. I am trying to get a value from my request. I can print it as closure, but I want to get as string on a VC and work with it, but on function login. I can't figure out how to return from a closure.

带关闭功能:

class Json {
var loginToken = ""


  public func login(userName: String, password: String) -> (Any){

let loginrequest = JsonRequests.loginRequest(userName: userName, password: password)
return makeWebServiceCall(urlAddress: URL, requestMethod: .post, params: loginrequest, completion: { (JSON : Any) in


  //let jsons = JSON
  print("\(JSON)")


})

}


private func makeWebServiceCall (urlAddress: String, requestMethod: HTTPMethod, params:[String:Any], completion: @escaping (_ JSON : Any) -> ()) {


    Alamofire.request(urlAddress, method: requestMethod, parameters: params, encoding: JSONEncoding.default).responseJSON { response in

        switch response.result {
        case .success(let data):
            if let jsonData = response.result.value {
                completion(jsonData)
            }
        case .failure(let error):
            if let data = response.data {
                let json = String(data: data, encoding: String.Encoding.utf8)
                completion("Failure Response: \(json)")

            }

在VC上的调用功能:

let retur = Json()
    let rezultatas = retur.login(userName: "root", password: "admin01")

    print(rezultatas)


推荐答案

您不能从闭包中返回。另外,请注意,您的函数正在进行网络服务调用。当遇到该部分时,控件不会立即进入该块,并且在执行该块之前,整个函数的执行将结束。除了返回值,您还可以在登录函数中添加另一个完成块。在您的 login 函数中添加另一个参数。

You can't return from a closure. Also, note that your function is making a webservice call. When that part is encountered, the control doesn't go into the block immediately and the entire function execution will be over before the block is executed. Instead of returning a value you can add another completion block to your login function. Add another argument to your login function.

public func login(userName: String, password: String, completion: @escaping(Any)->Void)

登录功能,删除return语句并执行类似的操作

Inside the login function, remove the return statement and do something like this

makeWebServiceCall(urlAddress: URL, requestMethod: .post, params: loginrequest, completion: { (JSON : Any) in
    completion(JSON)
})

然后,当您调用登录功能时,只需要做的就是

And when you call your login function all you have to do is,

login(userName: "", password:""){(response) in
    print(response)
}

您将拥有想要在此处传递的数据

You'll have the data that you wanted to pass here

这篇关于迅速3调用函数并返回完成闭包的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆