Alamofire中的CURL命令与swift

时间:2016-07-25 07:58:26

标签: swift curl alamofire

我有以下工作curl命令,我需要使用Alamofire在Swift中运行。

curl -k -i -d '{ "user": {"displayName":"My Test" ,"email":"test@xxtest.com","pwd":"test","roles":["stu"]}}' -H "Content-Type: application/json;charset=UTF-8" -u web:web -X POST 'https://test.herokuapp.com/xtest/auth/register'

我使用Alamofire使用Swift尝试了以下方法。我的印象是我做了-u web:web错误,但我无法确认。 控制台给我以下错误,我不明白:

print response object
  nil
print error
  Optional(Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character 0." UserInfo={NSDebugDescription=Invalid value around character 0.})

有人可以指出这里有什么问题吗? THX。

这是将CURL命令转换为Swift

的函数
func registerNewStudent(displayName: String, email: String, password: String, completionHandler: (AnyObject?, NSError?) -> ()) {

//Basic HTTP auth
    let user = "web"
    let password = "web"

    let credentialData = "\(user):\(password)".dataUsingEncoding(NSUTF8StringEncoding)!
    let base64Credentials = credentialData.base64EncodedStringWithOptions([])

    let headers = ["Authorization": "Basic \(base64Credentials)"]

//example for a nested array query
  let parameters = [
        "user": [
            "displayName": displayName,
            "email": email,
            "pwd": password,
            "roles":["stu"]
        ]
    ]

    Alamofire.request(
        .POST,
        registerURL,
        headers: headers,
        parameters: parameters
        )
        .responseJSON { response in
            switch response.result {
            case .Success(let value):
                completionHandler(value, nil)
            case .Failure(let error):
                completionHandler(nil, error)
            }
    }
}

我通过以下方式调用此函数:

func okButtonTapped(sender: UIButton) {

   let displayNameText = displayNameInput.text
    let emailText = emailInput.text
    let passwordText = passwordInput.text

    restApi.registerNewStudent(displayNameText!,emailInput: emailText!, passwordInput: passwordText!) {responseObject, error in
        // use responseObject and error here

        print("print response object")
        print(responseObject)
        print("print error")
        print(error)
    }

来自CURL电话的回复:

{"result":{"email":"trrrrrest@xxtest.com","display_name":"My Test","pwd":"test","fb_id":null,"roles":["stu"]

1 个答案:

答案 0 :(得分:0)

我可以从这里解决它:http://www.ceus-now.com/curl-d-to-alamofire/

在JSON响应之后添加以下行(不是之前)。

<expiration-cache>0</expiration-cache>

所以方法如下:

    .authenticate(user: "web", password: "web")