Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Swift alamofire不向返回字符串传递任何内容_Swift_Alamofire - Fatal编程技术网

Swift alamofire不向返回字符串传递任何内容

Swift alamofire不向返回字符串传递任何内容,swift,alamofire,Swift,Alamofire,-第二次编辑- 我现在使用的是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作为一个学习项目来实现。但由于我不熟悉语法,

-第二次编辑- 我现在使用的是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包含succes或erro。但函数始终返回空

我不知道为什么

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中,Optional是一种泛型类型,可以包含任何类型的值,也可以不包含任何值

在许多其他编程语言中,通常使用特定的sentinel值来表示缺少值。例如,在Objective-C中,null指针表示缺少对象

在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
    }

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

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

比如说

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

召唤


噢,对不起!在我阅读并添加这个var testResult:String!=empty结果现在为空。alamofire请求似乎没有做任何事情,或者我没有正确地将结果解析为字符串您正在执行异步请求–这将在函数返回后发生。比较&&&&&&是的,我发现请求的返回时间晚于函数返回的值。我会查链接的,谢谢!由于用户已经编辑了问题,答案也相应地被编辑了。谢谢,但是我怎么称呼它呢?我尝试将结果传递给根据您的需要进行编辑的用户。
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
        }