我需要从url获取数据。
例如,使用postman,如果我尝试使用这个my privateurl = "http://127.0.0.1/MyWebService/api/fetch_image.php"
和add-in参数执行get请求:
id U键->id U团队
在值->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)
最佳答案
抱歉,这是一个很糟糕的目标代码。
很明显,您希望类中包含常量,所以声明常量,在几乎所有情况下,您根本不需要类
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
时没有初始化器。如果使用快捷键,则可以完全省略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()
要添加参数,必须将
query
附加到URL,例如http://127.0.0.1/MyWebService/api/fetch_image.php?id_team=2
但这取决于你的后台。
关于json - 使用参数Swift从URL获取数据,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/55548087/