我有一些代码可以获取 API 响应,我想将响应存储在另一个脚本中,因为json
它是一个局部变量,所以我只能使用getData
函数中的数据。
这是代码:
import UIKit
class HomeViewController: UIViewController {
@IBOutlet weak var TestLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
let url = """
https://api.coronavirus.data.gov.uk/v1/data?filters=areaType=nation;areaName=england&structure=%7b%22date%22:%22date%22,%22areaName%22:%22areaName%22,%22areaCode%22:%22areaCode%22,%22newCasesByPublishDate%22:%22newCasesByPublishDate%22,%22cumCasesByPublishDate%22:%22cumCasesByPublishDate%22,%22newDeathsByDeathDate%22:%22newDeathsByDeathDate%22,%22cumDeathsByDeathDate%22:%22cumDeathsByDeathDate%22%7d
"""
getData(from: url)
// Do any additional setup after loading the view.
}
func getData(from url: String) {
guard let theURL = URL(string: url) else { print ("oops"); return }
let getfromurl = URLSession.shared.dataTask(with: theURL, completionHandler: {data, response, error in
guard let data = data, error == nil else{
print("Something Went Wrong")
return
}
//Have data
var result: Response?
do {
result = try JSONDecoder().decode(Response.self, from: data)
}
catch{
print("failed to convert \(error)")
}
guard let json = result else {
return
}
print(json)
})
getfromurl.resume()
}
}
struct Response: Codable {
let data: [MyData]
}
struct MyData: Codable{
let date: String
let areaName: String
let areaCode: String
let newCasesByPublishDate: Int
let cumCasesByPublishDate: Int?
let newDeathsByDeathDate: Int?
let cumDeathsByDeathDate: Int?
}