0

我有一些代码可以获取 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?
}
4

1 回答 1

1

Swift 正在使用模块。数据结构Response将在您的整个应用程序中为您提供,因为它是它的一部分。我建议通过阅读这篇文章来扩展您关于 Swift 如何使用模块的知识。

至于应用程序的架构部分,我建议创建一个单独的类,该类将是一个服务,它将解析并将响应返回给调用它的任何人。您应该为此使用完成处理程序...

一些伪例子

final class CovidService {
    func getData(url: String, @escaping completion:((Result<Response,Error>) -> Void)) {
        // your get data function
        //.....
        guard let json = result else {
            completion(SomeError)
            return
        }
        completion(json)
    }
}

使用此服务,您可以在每个 ViewController 或您希望的其他实体中获取数据...

更多阅读内容可以扩展您对 Swift 完成 API 服务中的完成处理程序和服务的了解

于 2021-02-06T18:53:17.800 回答