【问题标题】:Swift alamofire does not pass anything to return string [duplicate]Swift alamofire 没有传递任何东西来返回字符串 [重复]
【发布时间】:2017-10-23 10:47:37
【问题描述】:

-第二次编辑- 我现在正在使用 Arpit Jain 的建议,但我该如何调用该函数?我想把函数的结果解析成一个变量。

getToken(completionHandler: { // here I should do something with in
    // what should I do here to pass the result of getToken to variable?
})

-编辑过的原始问题-

我是 Swift 的新手,正在尝试实现一个 API(作为一个学习项目)。但是由于我不熟悉语法,所以我在这个 PoC 中不断收到错误。

我有一个通过 alamofire 的 http 请求,我希望 testResult 包含“成功”或错误。但是函数一直返回“空”

我不知道为什么?

func getToken() -> String{
var testResult: String! = "empty"
let url: String! = "https://the.base.url/token"
let parameters: Parameters = [
    "grant_type":"password",
    "username":"the_username",
    "password":"the_password",
    "client_id":"the_clientID",
    "client_secret":"the_secret",
]
Alamofire.request(url, method: .post, parameters: parameters, encoding: URLEncoding(destination: .methodDependent)).validate().responseJSON { response in
    switch response.result {
        case .success:
            testResult = "succes"
        case .failure(let error):
            testResult = error as! String
        }
    }
return testResult // this line gives the error
}

【问题讨论】:

标签: swift alamofire


【解决方案1】:

在 Swift 中,Optional 是一个泛型类型,可以包含一个值(任何类型的),或者根本不包含值。

在许多其他编程语言中,通常使用特定的“哨兵”值来表示缺少值。例如,在 Objective-C 中,nil(空指针)表示缺少对象。

在 Swift 中,任何类型都可以设为可选。可选值可以采用原始类型中的任何值,或特殊值 nil。

选项用 ? 定义类型的后缀:

func getToken(tokenReturned:@escaping (_ stringResponse: String?) -> Void) {
    var testResult: String? = "empty"
    let url: String! = "https://the.base.url/token"
    let parameters: Parameters = [
        "grant_type":"password",
        "username":"the_username",
        "password":"the_password",
        "client_id":"the_clientID",
        "client_secret":"the_secret",
        ]
    Alamofire.request(url, method: .post, parameters: parameters, encoding: URLEncoding(destination: .methodDependent)).validate().responseJSON { response in
        switch response.result {
        case .success:
            testResult = "succes"
        case .failure(let error):
            testResult = error as! String // Crash occurred because you were getting nil here and have not unwrapped testResult
        }
        tokenReturned(testResult)
    }
}

调用函数:

   self.getToken { (strResponse) in
     // Now in strResponse you will get result of testResult
    }

在您的情况下,完成处理程序块未打开。尝试这样调用。

【讨论】:

  • 用户编辑了问题,答案也相应地编辑了。
  • 谢谢,但我怎么称呼它?我尝试将结果传递给变量
  • 再次根据您的需要进行编辑。
【解决方案2】:

您可以在异步调用时返回 nil。使用闭包作为返回值。

对于示例

请注意,例如,您可以根据自己的要求进行更改

func getResponseString(url: String, method : HTTPMethod,  parameter : [String : AnyObject],  callback: @escaping  (_ string : String) -> ()) -> Void{

        Alamofire.request(API_PREFIX + url, method: method, parameters: parameter).validate().responseJSON { response in
            switch response.result {
            case .success:
                if let result = response.result.value {
                    let JSON = result as! [String : AnyObject]
                    callback("succes")
                }
            case .failure(let error):
                print(error)
                callback("" as! String)
                UtilityClass .removeActivityIndicator()
            }
        }
    }

通话

  self .getResponseString(url: "url", method: .post, parameter: ["email":"" as AnyObject]) { (responseString) in
            // responseString your string
        }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-02-11
    • 2012-04-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-17
    • 2019-04-22
    • 1970-01-01
    相关资源
    最近更新 更多