我有下面的curl命令,它在命令行上运行良好,但是我没有用Swift编写它。
curl -u web:web -k -i -d '{ "email":"[email protected]","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 = {
};
})
最佳答案
在cURL请求中,主体是JSON。但是,您的Alamofire代码将使用URL编码的参数发送请求。尝试改用JSON:
Alamofire.request(
.POST,
loginWithFacebook,
parameters: parameters,
encoding: .JSON
)
还要注意,cURL请求使用键
email
和fbId
,但Alamofire代码使用loginEmail
和facebookId
。如果您的服务器不同时支持这两种功能,您可能还需要更改这些功能。关于swift - 如何使用Alamofire在Swift中编写curl命令?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/38873967/