I'm new in swift programming and am trying to get the user data in JSON format from the server and then "paste" it into a struct :
This is my api :
app.get('/getUser/:username',(req,res)=>{
let user = req.params;
var sql = "SELECT * FROM users WHERE username = ? ";
mysqlConnection.query(sql,[user.username],
function(err, rows){
if(!err){
res.send(JSON.stringify({"userID" : rows}));
}
else {
console.log(err)
}
});
});
This is the JSON response:
{
userID = (
{
email = test;
id = 1;
money = 200;
password = test;
username = test;
}
);
}
This is my apiCall function :
class func getUser(username :String)
{
let url = "http://127.0.0.1:3000/getUser/"+username
Alamofire.request(url).responseJSON(completionHandler : { (response) in
switch response.result {
case .success( _):
// I want to append the user struct by the user data collected from JSON
print(response.result.value!)
case .failure(let error):
print (error)
}
})
}
And this My struct :
struct user {
var id : String
var username : String
var password : String
var email : String
var money : String
}
I Tried to create an array in my MainPageViewController and then append it but I don't know how :
class MainPageViewController: UIViewController {
var currentUser : String?
var userData = [user]()
override func viewDidLoad() {
API.getUser(username: currentUser!)
print(currentUser!)
super.viewDidLoad()
// API.getUserID(username: currentUser!)
// Do any additional setup after loading the view.
}
Well best way to do would be with Codeable:
let data: YourJSONData
struct User: Codable {
var id: String
var username: String
var password: String
var email: String
var money: String
}
let user = try? JSONDecoder().decode(User.self, from: data)
EDIT
To answer your further question, just use it like this:
static func getUserByUsername(_ username: String) {
let url = "http://127.0.0.1:3000/getUser/" + username
Alamofire.request(url).responseData(completionHandler : { (response) in
switch response.result {
case .success( let data):
do {
let user = try JSONDecoder().decode(Base.self, from: data)
}
catch {print(error)}
case .failure(let error):
print (error)
}
})
}
struct Base: Codable {
let userID: [User]
}
struct User: Codable {
var id: String
var username: String
var password: String
var email: String
var money: String
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With