I have an API for my user to login to the database . I am using the following code to send the credentials to the API and if they are valid I am going to get some JSON typed data about the users information . Otherwise I get a string saying that the username or password is wrong . Here is my HTTTP Post request :
let url = URL(string: "http://128.199.199.17:3000/api/login")!
var request = URLRequest(url: url)
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.httpMethod = "POST"
let postString = "email=22222@gmail.com&password=123456"
request.httpBody = postString.data(using: .utf8)
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data, error == nil else {
print("error=\(String(describing: error))")
return
}
if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {
print("statusCode should be 200, but is \(httpStatus.statusCode)")
print("\(String(describing: response))")
}
let responseString = String(data: data, encoding: .utf8)
print("responseString = \(responseString!)")
}
task.resume()
It works fine and I get the following information in the console :
{
"user_id": 2,
"email": "22222@gmail.com",
"password": "123456",
"user_name": "number 2 name",
"full_name": "danial kosarifar",
"sex": "male",
"height": 0,
"weight": 0,
"number_of_meal_per_day": 3,
"water_amount": 0,
"calories": 0,
"number_of_hours_to_sleep_per_day": 3,
"createdAt": "2017-11-14T17:23:31.000Z",
"updatedAt": "2017-11-14T17:25:37.000Z"
}
I've also created a decodable structure like so :
struct User : Decodable {
let user_id : Int
let email : String
let password : String
let username : String
}
my question is instead of decoding the data to string how can I decode them in such way that I can put them in the structure thats I've defined . I am completely new to this topic please bear with me if my question too of much of a beginner . Thanks