为什么我在swift中调用API会抛出两个错误?

06odsfpq  于 2023-02-15  发布在  Swift
关注(0)|答案(1)|浏览(99)

我得到的两个错误是:
"'async '调用不能出现在全局变量初始值设定项中"和
调用可以引发,但不能从全局变量初始值设定项中引发错误
我的代码如下:

func getReps() async{
    let apiService = APIService(urlString: (EnvSetup.baseUrl + EnvSetup.apiKey))
    
    await Task{
        let reps: [rep] = try await apiService.getJSON()
        FileManager.endcodeAndSave(objects: reps, fileName: "reps.json")
        print(reps.count)
    }
}

我尝试过不使用异步并等待,将它们添加到我的调用程序中(这只是:

async{
    await @Published var Reps: [rep] = getReps()
}

这是我第一次在Swift中使用API,所以这可能是一个简单的文件结构问题,但我已经在这方面工作了几个小时,没有任何效果。我将感谢任何帮助!
我试过修改async和await命令,但是,我总是得到同样的错误。我使用的APIService代码是Stewart Lynch的,如下所示:

import Foundation

public class APIService {
    public let urlString: String
    public init(urlString: String) {
        self.urlString = urlString
    }
    
    public func getJSON<T: Decodable>( dateDecodingStategy: JSONDecoder.DateDecodingStrategy = .deferredToDate,
                                       keyDecodingStrategy: JSONDecoder.KeyDecodingStrategy = .useDefaultKeys,
                                       completion: @escaping (T) -> Void) {
        guard let url = URL(string: urlString) else {
            fatalError("Error: Invalid URL.")
        }
        let request = URLRequest(url: url)
        URLSession.shared.dataTask(with: request) { (data, response, error) in
            if let error = error {
                fatalError("Error: \(error.localizedDescription)")
            }
            guard let data = data else {
                fatalError("Error: Data is corrupt.")
            }
            let decoder = JSONDecoder()
            decoder.dateDecodingStrategy = dateDecodingStategy
            decoder.keyDecodingStrategy = keyDecodingStrategy
            
            do {
                let decodedData = try decoder.decode(T.self, from: data)
                completion(decodedData)
            } catch {
                fatalError("Error: \(error.localizedDescription)")
            }
        }.resume()
    }
    
    @available(iOS 14, *)
    public func getJSON<T: Decodable>(dateDecodingStategy: JSONDecoder.DateDecodingStrategy = .deferredToDate,
                                      keyDecodingStrategy: JSONDecoder.KeyDecodingStrategy = .useDefaultKeys) async throws -> T {
        guard let url = URL(string: urlString) else {
           fatalError("Error: Invalid URL.")
        }
        let request = URLRequest(url: url)
        let (data, response) = try await URLSession.shared.data(for: request)
        guard let _ = response as? HTTPURLResponse else {
            fatalError("Error: Data Request error.")
        }
        let decoder = JSONDecoder()
        decoder.dateDecodingStrategy = dateDecodingStategy
        decoder.keyDecodingStrategy = keyDecodingStrategy
        guard let decodedData =  try? decoder.decode(T.self, from: data) else {
           fatalError("Error: Decoding error.")
        }
        return decodedData
    }
}
laik7k3q

laik7k3q1#

标记为async的函数在异步上下文中运行,不需要额外的任务。
并且你已经创建了函数throw或者添加了一个do - catch块(第二个错误)。如果你想返回数据,也添加一个返回值。
顺便说一句,请命名结构体和类与开始大写字母

func getReps() async throws -> [Rep] {
    let apiService = APIService(urlString: (EnvSetup.baseUrl + EnvSetup.apiKey))
    
    let reps: [Rep] = try await apiService.getJSON()
    FileManager.endcodeAndSave(objects: reps, fileName: "reps.json")
    print(reps.count)
    return reps
}

并且async { await @Published var ...是错误的(第一个错误)。

@Published var reps = [Rep]()

并实现init

init() {
    Task {
       reps = (try? await getReps()) ?? []
    }
}

相关问题