0

I need get data from an url. Using postman, for example, if I try a get request with this my private url = "http://127.0.0.1/MyWebService/api/fetch_image.php" and add in params : id_key -> id_team in value -> 2 the software returns this to me:

{"image_team":[{"id":1,"img_path":"http://localhost/MyWebService/images/Schermata.png","id_team":2},{"id":2,"img_path":"http://localhost/MyWebService/images/Schermata.png","id_team":2},{"id":3,"img_path":"http://localhost/MyWebService/images/Schermata.png","id_team":2}]}

now in Swift I have written these classes:

class ClassJsonTeam: Codable {

private var teams: [JsonTeam]

init(teams: [JsonTeam]) {
    self.teams = teams
}

func getTeams()-> [JsonTeam]{
    return(self.teams);
}

func setTeams(teams:[JsonTeam]){
    self.teams = teams;
}

}

class JsonTeam: Codable {
private let id: Int
private var name: String
private var member: Int

init(id: Int, name: String, member: Int) {
    self.id = id
    self.name = name
    self.member = member
}

func getId()->Int{
    return(self.id);
}

func setId(id:Int){
    self.member = id;
}

func getName()->String{
    return(self.name);
}

func setName(name:String){
    self.name = name;
}

func getMembers()->Int{
    return(self.member);
}

func setMembers(members:Int){
    self.member = members;
}    
}

The question is: how can I make the request and save the date in the class?

(I'm using Swift 4)

1 Answer 1

3

Sorry, but this is horrible objective-c-ish code.

You obviously want constants in your classes so declare constants, and in almost all cases you don't need classes at all

struct Response: Decodable {
    let teams: [Team]

    private enum CodingKeys : String, CodingKey { case teams = "image_team" }
}

struct Team: Decodable {
    let id: Int
    let imagePath: URL
    let teamID: Int

    private enum CodingKeys : String, CodingKey { case id, imagePath = "img_path", teamID = "id_team" }
}

That's it. Nothing else. No weird public getters and private setters. No initializers when dealing with (De)codable. And if you would use swiftier keys you can omit the CodingKeys declarations completely. The key imagePath can be even decoded as URL.

And finally: No trailing semicolons!

To read the data use traditional URLSession

let url = URL(string: "http://127.0.0.1/MyWebService/api/fetch_image.php")!
let dataTask = URLSession.shared.dataTask(with: url) { data, response, error in
    if let error = error { 
       print(error) 
       return 
    }
    do {
        let result = try JSONDecoder().decode(Response.self, from: data!)
        print(result)
    } catch {
        print(error)
    }
}
dataTask.resume()

To add parameters you have to append a query to the URL for example

http://127.0.0.1/MyWebService/api/fetch_image.php?id_team=2

but this depends on your backend.

Sign up to request clarification or add additional context in comments.

5 Comments

Furthermore I would suggest that you unwrap the url and not use the bang operator. In addition, you can also remove the let dataTask and use .resume() at the end of the curly bracket.
@FloWy If the URL is a literal constant and you know it's valid there's nothing wrong with force unwrapping it. Omitting let dataTask is a matter of taste 😉
I totally agree, but in my opinion it is bad practice. If you are the only one in your team it is ok, but if you have a larger project with multiple teams it is better practice to unwrap the url.
@FloWy I strongly doubt that people working on larger projects in teams would ask such a question here on SO 😉
Everything is possible :D

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.