【问题标题】:swift 3 completion handler to return stringswift 3完成处理程序返回字符串
【发布时间】:2017-01-27 07:59:56
【问题描述】:

我是 swift 的新手,从函数中获取字符串时遇到问题,我正在尝试使用完成处理程序,但出现了问题,你能帮帮我吗?

将 [String : String] 添加到 func 后,我无法获得 rezult,我想获得响应并打印它。错误:无法将类型 () 的返回表达式转换为返回类型 [String : String]

请求:

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

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

   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:
            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)
                print("Failure Response: \(json)")

            }

调用函数:

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

    print(rezultatas)

错误: enter image description here

【问题讨论】:

  • "something is wrong" 是无用的问题描述。

标签: json swift closures alamofire


【解决方案1】:

欢迎使用 Swift :)

您将同步和异步代码混合在一起。

当您调用login 时,您希望它立即返回[String : String] 类型的答案。

但是在您的 login 方法中,您随后会执行无法立即返回的网络调用...这就是对 Alamofire.request 的调用将完成块作为参数的原因。

所以...您需要更改您的 login 方法:

  1. 不会立即返回任何内容(它不能这样做...登录需要我们进行网络调用记住)
  2. 一旦登录成功,就会调用一个完成块。

可以这样做:

public func login(userName: String, password: String, loginCompletion: @escaping ([String : String]) -> ())

这里我们有一个函数,它接受 String 类型的 userNameString 类型的 passwordfunction 类型的 loginCompletion,它再次接受 [String : String] 字典作为参数.请注意,该方法不返回任何内容。

现在您可以像以前一样拨打您的makeWebServiceCall

let loginrequest = JsonRequests.loginRequest(userName: userName, password: password)
makeWebServiceCall(urlAddress: URL, requestMethod: .post, params: loginrequest, completion: { (JSON : Any) in
   //Now we are ready, the login call has returned some data to you. 

   //You have an attribute named JSON of type Any, which you need to convert to [String : String], and then you can call loginCompletion with that, like so:
   loginCompletion(yourConvertedDictionaryHere)
})

下面是完整的新 login 方法:

public func login(userName: String, password: String, loginCompletion: @escaping ([String : String]) -> ()) {
    let loginrequest = JsonRequests.loginRequest(userName: userName, password: password)
    makeWebServiceCall(urlAddress: URL, requestMethod: .post, params: loginrequest, completion: { (JSON : Any) in
       //Now we are ready, the login call has returned some data to you. 

       //You have an attribute named JSON of type Any, which you need to convert to [String : String], and then you can call loginCompletion with that, like so:
       loginCompletion(yourConvertedDictionaryHere)
    })
}

然后你像这样调用你的login 方法:

retur.login(userName: "root", password: "admin01") { stringDictionary: [String : String] in
    //here you have your stringDictionary which you can use as pleased
}

希望对你有所帮助。

【讨论】:

  • 谢谢你,你帮助了我,但我仍然得到错误,我用新图片更新了问题。
  • 我试着改变类型,就像你说的那样,但是我得到了错误,我需要从服务器获取大厅响应作为字符串并打印出来。我更新了我的问题
  • 哇,终于得到了我找了2天的大厅解释,我不知道该怎么说谢谢
  • @EgleMatutyte 不客气。一旦您了解了完成块和异步代码,它们就是在需要时使用的好工具。祝你好运:)
  • 还有一个问题,如何在不转换的情况下传递 JSON?
【解决方案2】:

这样定义函数

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

completion("Make a service call")

}

像这样调用函数

makeWebServiceCall(urlAddress: "", requestMethod: "", params: ["Key" : "value"], completion: { (JSON : Any) in

            print("\(JSON)")

        })

由于简单,我已经更改了参数的数据类型。您也可以在completion("Make a service call") 中传递任何类型的数据。 希望这会对您有所帮助。

【讨论】:

  • 好的,我想我明白了,但我仍然收到类型错误,你能检查我的问题吗,我用代码和错误图片编辑了它
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-06-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多