I am trying to parse my JSON response coming from rest api but constantly getting an error.
My request sending and JSON parsing code is below and also I added Xcode's error message.
I appreciate any help in advance.
My JSON format:
{
"error":1,
"name":"batuhan",
"mail":"[email protected]",
"password":"e10adc3949ba59abbe56e057f20f883e",
"user_type":"user"
}
My code:
@IBAction func registerButton(_ sender: Any) {
let name: String = self.name.text!
let mail: String = self.mail.text!
let password: String = self.password.text!
var responseString: String = ""
let url = URL(string: "http://my_webserver/index.php?process=register")!
var request = URLRequest(url: url)
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.httpMethod = "POST"
let postString = "mail=\(String(describing: mail))&name=\(String(describing: name))&password=\(String(describing: password))®ister_type=user"
request.httpBody = postString.data(using: .utf8)
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data, error == nil else { // check for fundamental networking error
print("error=\(String(describing: error))")
return
}
if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 { // check for http errors
print("statusCode should be 200, but is \(httpStatus.statusCode)")
print("response = \(String(describing: response))")
}
responseString = String(data: data, encoding: .utf8)!
}
struct RegisteredUser: Codable {
let error: String
let name: String
let mail: String
let password: String
let user_type: String
}
let jsonData = responseString.data(using: .utf8)!
let decoder = JSONDecoder()
let user_data = try! decoder.decode(RegisteredUser.self, from: jsonData)
print(user_data.name)
print(user_data.mail)
task.resume()
}
The error:
fatal error: 'try!' expression unexpectedly raised an error: Swift.DecodingError.dataCorrupted(Swift.DecodingError.Context(codingPath: [], debugDescription: "The given data was not valid JSON.", underlyingError: Optional(Error Domain=NSCocoaErrorDomain Code=3840 "No value." UserInfo={NSDebugDescription=No value.}))): file /Library/Caches/com.apple.xbs/Sources/swiftlang/swiftlang-900.0.65/src/swift/stdlib/public/core/ErrorType.swift, line 181
jsonData
andresponseString
before you decode, what do you see? – Itai FerberresponseString
retains its default value of””
, which is why you can’t parse it – Itai Ferber