SwiftUI从API.city.bik获取JSON API数据



我在获取这些数据时遇到问题。我听说有个把戏。任何人都可以创建一个简单的调用来查看这个api中的数据吗?真的很感激。我已经试了一个星期了。我一辈子都不能让这个简单的api调用工作。

http://api.citybik.es/v2/networks

无线型号

import Foundation
// MARK: - Welcome
struct Dataset: Codable {
let networks: [Network]
}
// MARK: - Network
struct Network: Codable {
let company: [String]
let href, id: String
let location: Location
let name: String
}
// MARK: - Location
struct Location: Codable {
let city, country: String
let latitude, longitude: Double
}

Contentview.swift

import SwiftUI
struct ContentView: View {

@State var results = [Network]()

func loadData() {
guard let url = URL(string: "http://api.citybik.es/v2/networks") else {
print("Your API end point is Invalid")
return
}
let request = URLRequest(url: url)
URLSession.shared.dataTask(with: request) { data, response, error in
if let data = data {
if let response = try? JSONDecoder().decode([Network].self, from: data) {
DispatchQueue.main.async {
self.results = response
}
return
}
}
}.resume()
}

var body: some View {
List(results, id: .name) { item in
VStack(alignment: .leading) {
Text("(item.name)")
}
}.onAppear(perform: loadData)
}


}

从以下位置复制整个json:"https://api.citybik.es/v2/networks"变成";https://app.quicktype.io/"并从中获得(正确的(swift数据结构。重命名"欢迎"至";响应";并在代码中使用它。

使用:";https://api.citybik.es/v2/networks"注意https。

编辑:在您的代码中:

struct ContentView: View {
@State var networks = [Network]()

var body: some View {
List(networks, id: .id) { network in
VStack {
Text(network.name)
Text(network.location.city)
}
}.onAppear(perform: loadData)
}

func loadData() {
guard let url = URL(string: "https://api.citybik.es/v2/networks") else {
print("Your API end point is Invalid")
return
}
let request = URLRequest(url: url)
URLSession.shared.dataTask(with: request) { data, response, error in
if let data = data {
if let response = try? JSONDecoder().decode(Response.self, from: data) {
DispatchQueue.main.async {
self.networks = response.networks
}
return
}
}
}.resume()
}
} 

一旦你有了所有的数据结构,如果你在ios 15或macos 12上使用Swift 5.5,你可以使用这样的东西:

struct ContentView: View {
@State var networks = [Network]()

var body: some View {
List(networks, id: .id) { network in
VStack {
Text(network.name)
Text(network.location.city)
}
}
.task {
let response: Response? = await fetchNetworks()
if let resp = response {
networks = resp.networks
}
}
}

func fetchNetworks<T: Decodable>() async -> T? {
let url = URL(string: "https://api.citybik.es/v2/networks")!
let request = URLRequest(url: url)
do {
let (data, response) = try await URLSession.shared.data(for: request)
guard let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode == 200 else {
// throw URLError(.badServerResponse)   //  todo
print(URLError(.badServerResponse))
return nil
}
let results = try JSONDecoder().decode(T.self, from: data)
return results
}
catch {
return nil
}
}
}

相关内容

  • 没有找到相关文章

最新更新