【问题标题】:Trying to get data with Alamofire and swift 5尝试使用 Alamofire 和 swift 5 获取数据
【发布时间】:2021-04-25 08:17:56
【问题描述】:

我想用 Alamofire 加载一些 data

这是我的课

struct Welcome: Codable {
    let count: Int
    let next: String
    let previous: String
    let results: [Übungen]
}

// MARK: - Result
struct Übungen: Codable {
    let id, category: Int
    let resultDescription, name, nameOriginal: String
    let muscles, musclesSecondary, equipment: Int
    let creationDate: String
    let language: Int
    let uuid: String
    let variations: Int

接下来是我的协议

protocol ÜbungenGateway {
    func fetch(completion: @escaping (Result<[Übungen], Error>) -> Void)
}

最后一部分是 Alamofireclass

class ÜbungenAlamofireGateway : ÜbungenGateway  {
    
    let url = "https://wger.de/api/v2/"       
  
    func fetch(completion: @escaping (Result<[Übungen], Error>) -> Void) {
    
  AF.request(url)
      .validate()
          .responseJSON {
            switch $0.result{
            case .success:
                do {
                    let decoder = JSONDecoder()
                    let excercise = try! decoder.decode(Übungen.self, from: $0.data!)
                    completion(.success(excercise.name))
                }catch {
                    completion(.failure(error))
                }
            case .failure(let error):
                completion(.failure(error))
            }
        }
    }
}

我的问题是我收到以下错误:

"Cannot convert value of type 'String' to expected argument type '[Übungen]'"

排队

completion(.success(excercise.name))

我不知道为什么。

希望有人能帮帮我。

【问题讨论】:

    标签: swift api alamofire


    【解决方案1】:

    所以第一个问题是在fetch 方法中输入完成块。

    func fetch(completion: @escaping (Result<[Übungen], Error>) -> Void)
    

    完成时预期返回的类型是Übungen 对象的列表,但您正试图从Übungen 对象completion(.success(excercise.name)) 传递名称(这是一个字符串)。这就是您收到此错误的原因。

    第二个想法是您正在调用"https://wger.de/api/v2/" 端点,并且来自documentation 的响应将是链接列表,并且响应中不存在您对象的某些属性。

    【讨论】:

    • 你能给我一个提示如何解决它吗?我想列出一个列表中的所有练习
    • 所以你需要调用这个端点:https://wger.de/api/v2/exercise/ 并且 Alamofire 有方法将 JSON 序列化为可编码对象。 AF.request(url).validate().responseDecodable(of: [Übungen].self) { response in // and then on response.value you have your response struct }。然后在完成块中传递整个response.value
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-15
    • 1970-01-01
    相关资源
    最近更新 更多