Charlie Lomello
Charlie Lomello

Reputation: 67

Get data from URL with parameters Swift

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)

Upvotes: 0

Views: 218

Answers (1)

vadian
vadian

Reputation: 285240

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.

Upvotes: 3

Related Questions