2016-07-25 91 views
0

我有以下工作捲曲命令,我需要使用Alamofire在Swift中運行。Alamofire的CURL命令與快速

curl -k -i -d '{ "user": {"displayName":"My Test" ,"email":"[email protected]","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.}) 

有人能說出什麼在這裏錯了嗎?謝謝。

這是平移CURL命令到夫特

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

我打電話以下列方式該功能的功能:

{"result":{"email":"[email protected]","display_name":"My Test","pwd":"test","fb_id":null,"roles":["stu"] 

回答

0
:從CURL呼叫

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

響應

我可以從這裏解決:http://www.ceus-now.com/curl-d-to-alamofire/

在JSON響應做了訣竅之後添加下面一行(不是之前)。

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

因此該方法是這樣的:

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