3

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.
    }
3
  • Best way would be with codeable... Commented Dec 26, 2018 at 13:47
  • Your question is ambiguous because from the dictionary output you cannot determine if the type of id and money is String or Int Commented Dec 26, 2018 at 13:53
  • Hey louay baccary please share the answer/solution you went with, currently, I am stuck at the same stage Commented Dec 7, 2019 at 14:26

2 Answers 2

3

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
}
Sign up to request clarification or add additional context in comments.

12 Comments

and how can i use it ? where to put this code and how to relate it with my api
Well anywhere you want... Now it is a native Struct representing a User...
This throws a DecodingError if you wouldn't ignore it.
Well its exactly the same way you wrote above?!? @Sh_Khan
i did responseData not responseJSON , plus this is not a suitable place for struct
|
2

You can try

struct Root: Codable {
    let userID: [User]
}

struct User: Codable {
    let email: String
    let id, money: Int
    let password, username: String
}

do {
    let res = try JSONDecoder().decode(Root.self,from:data)
    users = res.userID
 }
 catch {
    print(error)
 }

and change Alamofire from responseJSON to responseData


Alamofire.request(url).responseData(completionHandler : { (response) in
    switch response.result {
    case .success( let data):
        // I want to append the user struct by the user data collected from JSON
        print(response.result.value!)
        do {
            let res = try JSONDecoder().decode(Root.self,from:data)
            userData = res.userID
        }
        catch {
            print(error)
        }

    case .failure(let error):
        print (error)
    }

})

2 Comments

I didn't understand , my problem is i want to convert the data from JSON to strings then append it to my struct
Well JSON in Swift is just a String... You have to serialize it to a Struct, and then you can use it as a Struct Wherever you want to...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.