我通过 Alamofire 从我的VM服务器获取密码盐时遇到了麻烦。我向服务器发出请求,它应该返回给我盐,所以我可以将我的密码加密,哈希并将其发送回服务器。
问题在于我不明白如何将Alamofire收到的盐保存到变量中,因此我可以将其添加到密码中并将其哈希:
let salted_password = user_password + salt
let hash = salted_password.sha1()
其中user_password
是用户输入密码字段的内容,salt
是我从Alamofire盐请求中获得的内容。
这是我的代码:
func getSalt(completionHandler: @escaping (DataResponse<String>, Error?) -> Void) {
Alamofire.request("http://192.168.0.201/salt", method: .post, parameters: salt_parameters).responseString { response in
switch response.result {
case .success(let value):
completionHandler(response as DataResponse<String>, nil)
case .failure(let error):
completionHandler("Failure", error)
}
}
}
let salt = getSalt { response, responseError in
return response.result.value!
}
它给了我以下错误:
Binary operator '+' cannot be applied to operands of type 'String' and '()'.
那么可以将请求值保存到变量中吗?我该怎么办?
感谢您的关注。
答案 0 :(得分:0)
The problem here is because of how you implemented your completion block
For example:
func someAsynchronousCall(a: Int, b: Int, @escaping block: (_ result: Int) -> Void) {
... some code here
... {
// let's just say some async call was done and this code is called after the call was done
block(a + b)
}
}
To use this code it would look like this:
var answer: Int = 0
someAsynchronousCall(100, b: 200) { result in // the `result` is like what you're returning to the user since API calls need to be called asynchronously you do it like this rather than creating a function that has a default return type.
answer = result
print(answer)
}
print(answer)
The print would look like this
0
300
Since we declared answer as 0
it printed that first since the async call wasn't done yet, after the async call was done (usually a few milliseconds after) it then printed 300
So all in all your code should look something like this
var salt: String?
getSalt { response, responseError in
salt = response.result.value
}