我有以下curl命令在命令行上运行正常,但我无法在Swift中编写它。
curl -u web:web -k -i -d '{ "email":"fb@test.com","fbId":"FBXXXFB","accessToken":"accessNow","familyName":"FamName","givenName":"given"}' -H "Content-Type: application/json;charset=UTF-8" -X POST 'https://xweb.test.herokuapp.com/olweb/auth/login/fb'
当我尝试在Alamofire中翻译时,我总是从服务器收到错误。所以我假设auth工作正常,但参数不正确,因为我需要向服务器发送5个参数。 我怎么能这样做呢?
以下是代码段:
func loginWithFacebook(loginEmail: String, facebookId: String, accessToken: String,familyName: String, givenName: String, completionHandler: (AnyObject?, NSError?) -> ()) {
//Basic HTTP auth
let user = "web"
let password = "web"
// let headers = ["Authorization": "Basic \(base64Credentials)"] not working
// let headers = ["web": "web"] not working
//example for a nested array query
let parameters = [
"loginEmail": loginEmail,
"facebookId": facebookId,
"accessToken": accessToken,
"familyName": familyName,
"givenName": givenName
]
Alamofire.request(
.POST,
loginWithFacebook,
parameters: parameters
)
.responseJSON { response in
switch response.result {
case .Success(let value):
completionHandler(value, nil)
case .Failure(let error):
completionHandler(nil, error)
}
}
.authenticate(user: user, password: password)
}
我用以下方式调用此方法:
self.restApi.loginWithFacebook(email, facebookId: facebookId, accessToken: accessToken, familyName: familyName, givenName: firstName) {responseObject, error in
print("responseobject printed loginUserWithFacebook() ")
print(responseObject)
print("error printed")
print(error)
//get the JSON object
let response = responseObject as? [String:AnyObject]
print("response")
print(response)
//parse down the first layer of JSON object which is an NSDictionary (sometimes it is [AnyObject] )
if let result = response!["result"] as? [String: AnyObject]
{
print("self.result.count after calling loginUserWithFacebook()")
print(result.count)
print(result)
// self.getProfileFromUser()
}
}
来自服务器的错误响应:
responseobject printed loginUserWithFacebook()
Optional({
info = "Required fields missing.";
result = {
};
})
答案 0 :(得分:1)
在你的cURL请求中,正文是JSON。但是,您的Alamofire代码将使用URL编码的参数发送请求。请尝试使用JSON:
Alamofire.request(
.POST,
loginWithFacebook,
parameters: parameters,
encoding: .JSON
)
另请注意,您的cURL请求使用了密钥email
和fbId
,但您的Alamofire代码使用loginEmail
和facebookId
。如果您的服务器不支持这两者,您可能还需要更改它们。