2016-11-05 2 views
2

이전하려는 이전 코드베이스가 있습니다. 현재 네트워크 호출 Alamofire 4.0 사용하고 대신 URLSession 사용하려고합니다. 내가 뭘 잘못했는지 알아 내는데 어려움을 겪고 있습니다. 내가 400 상태 코드를 얻고, 어떤 이유URLSession에 Alamofire 호출을 번역합니다.

// old network request 
Alamofire.request(url, method: .post, parameters: newUser, encoding: JSONEncoding.default).responseJSON { response in 
    // ... 
} 

// new code 
var request = URLRequest(url: url) 
let jsonData = try! JSONSerialization.data(withJSONObject: params, options: .prettyPrinted) 
request.httpBody = jsonData 
request.httpMethod = "POST" 
let task = URLSession.shared.dataTask(with: request) { data, response, error in 
    guard let data = data, error == nil else { return print("error=\(error)") } 

    if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 { 
    print("status code should be 200, but is \(httpStatus.statusCode)") 
    print("response = \(response)") 
    } 

    let responseString = String(data: data, encoding: .utf8) 
    print("responseString = \(responseString)") 
} 

task.resume() 

:

// route to user creation 
let url = ... 

let params = ["user": ["first_name": "John", "last_name": "Appleseed", "email": "[email protected]", "password": "asdfgh"]] 

여기에 이전 및 새 네트워크 호출입니다 : 내가 게시 할 경로로 해, params로 시작 내 URLSession 시도. Alamofire는 잘 작동합니다.

감사의 말.

+0

@EricAya 질문에 쓰는 것을 잊어 버렸습니다. 업데이트 됨. 나는 그것을 프로젝트 코드로 작성했다. –

+0

그럼 내가 잘못 본 것이 없습니다. 어쩌면 예외를 제외하고 매개 변수 유형을 선언 해보십시오.'let params : [String : Any] = '도움이 될 수 있습니다. – Moritz

+0

또한'.prettyPrinted'를'[]'로 바꾸어보십시오. 일부 서버는 httpBody에 예쁜 JSON을 갖고 싶어하지 않습니다. – Moritz

답변

0

문제는 요청이 JSON 호출로 인식되지 않는다는 것입니다. URLRequest을 작성한 후 다음 과제를 작성하십시오.