使用参数Swift从URL获取数据

时间:2019-04-06 10:17:53

标签: json swift parsing

我需要从网址获取数据。 例如,使用邮递员,如果我尝试使用我的私有url = "http://127.0.0.1/MyWebService/api/fetch_image.php"进行get请求并添加params: id_key-> id_team 值-> 2 该软件将其返回给我:

  

{“ 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}]}

现在在Swift中,我已经编写了这些类:

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;
}    
}

问题是:如何提出请求并将日期保存在班级中?

(我正在使用Swift 4)

1 个答案:

答案 0 :(得分:3)

对不起,但这是可怕的 objective-c-ish 代码。

您显然希望在类中使用常量,因此声明常量,并且在几乎所有情况下,您根本不需要类

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" }
}

就是这样。没有其他的。没有奇怪的公共获取者和私人安装者。处理(De)codable时没有初始化程序。而且,如果您使用 swiftier 键,则可以完全省略CodingKeys声明。密钥imagePath甚至可以解码为URL

最后:没有结尾的分号!

要读取数据,请使用传统的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()

要添加参数,您必须在URL后面附加一个query

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

但这取决于您的后端。