2017-04-07 68 views
1

我在通过Alamofire从我的VM服务器获取密码盐时遇到了麻烦。我正在向服务器发出请求,并且它应该返回给我salt,所以我可以使用我的密码,散列它并将其发送回服务器。将Alamofire请求数据保存到变量中

的问题是,我不知道如何保存盐,即Alamofire接收到一个变量,这样我就可以把它添加到密码哈希会这样:

let salted_password = user_password + salt 
let hash = salted_password.sha1() 

哪里user_password是用户输入的密码字段和salt是我从Alamofire salt请求中获得的。

这里是我的代码:

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 '()'. 

所以是有可能的请求的值保存到一个变量?我该怎么办?

感谢您的关注。

+3

'getSalt()'的返回值是什么?看起来你正在试图将'String'与你不能使用的那个函数的结果结合起来(因为你已经发现了困难的方法:)) – pbodsk

+0

你应该做的是这样的代替。 'var salt:String ?; getSalt {response,responseError in salt = response.result.value; }' –

+0

@ZonilyJame非常感谢,它的作品! –

回答

0

这里的问题是,因为你如何实现你的completion block

例如:

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

要使用此代码,它应该是这样的:

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) 

打印看起来像这样

0 
300 

自从我们宣布答案0它打印出的第一,因为异步调用没有做呢,异步调用已完成后(通常在几毫秒),那么它印300

因此,所有的所有代码应该看起来像这样

var salt: String? 
getSalt { response, responseError in 
    salt = response.result.value 
}