首页 > 解决方案 > 请求 github Swift 的 api gist

问题描述

我很难快速提出对 github api gist 的请求。以下是代码:我想知道如何从 gist 返回中获取这些数据以显示在屏幕上。

回复:( https://api.github.com/gists/95fcf71eb72f2ea1e3836d192c788ebc

   {
    "url": "https://api.github.com/gists/95fcf71eb72f2ea1e3836d192c788ebc",
    "forks_url": "https://api.github.com/gists/95fcf71eb72f2ea1e3836d192c788ebc/forks",
    "commits_url": "https://api.github.com/gists/95fcf71eb72f2ea1e3836d192c788ebc/commits",
    "id": "95fcf71eb72f2ea1e3836d192c788ebc",
    "node_id": "MDQ6R2lzdDk1ZmNmNzFlYjcyZjJlYTFlMzgzNmQxOTJjNzg4ZWJj",
    "git_pull_url": "https://gist.github.com/95fcf71eb72f2ea1e3836d192c788ebc.git",
    "git_push_url": "https://gist.github.com/95fcf71eb72f2ea1e3836d192c788ebc.git",
    "html_url": "https://gist.github.com/95fcf71eb72f2ea1e3836d192c788ebc",
    "files": {
        "gist.swift": {
            "filename": "gist.swift",
            "type": "text/plain",
            "language": "Swift",
            "raw_url": "https://gist.githubusercontent.com/arjdev69/95fcf71eb72f2ea1e3836d192c788ebc/raw/60db0c3f01cffdd56bcfd3474d19d533c02dc0f2/gist.swift",
            "size": 2534,
            "truncated": false,
            "content": "//\n//  SceneDelegate.swift\n//"
        }
    },
    "public": true,
    "created_at": "2021-04-21T00:48:19Z",
    "updated_at": "2021-04-21T01:31:18Z",
    "description": "Ios Gist App",
    "comments": 1,
    "user": null,
    "comments_url": "https://api.github.com/gists/95fcf71eb72f2ea1e3836d192c788ebc/comments"....continue
}

模型:

import UIKit

struct GistModel: Decodable {
  let id:String;

  var files:String;
  let created_at:String;
  let updated_at:String;
  let comments:Int;

  enum CodingKeys: String, CodingKey {
    case files
    case created_at
    case updated_at
    case comments
    case id
  }


}

struct GistList: Decodable {
  let all: [GistModel]

  enum CodingKeys: String, CodingKey {
     case all
  }
}

接口:

 func getGistById(_ id:String, completion:@escaping(_ data:GistModel) -> Void){
    guard let url = URL(string: urlService + "\(id)") else {return}
    
    let request = AF.request(url)

    request.responseDecodable(of: GistModel.self) { (response) in
        print(response)
      guard let gist = response.value else { return }
        completion(gist)
   }

}

我在解码响应时遇到问题,尤其是“文件”属性。

这是错误:

failure(Alamofire.AFError.responseSerializationFailed(reason: Alamofire.AFError.ResponseSerializationFailureReason.decodingFailed(error: Swift.DecodingError.typeMismatch(Swift.String, Swift.DecodingError.Context(codingPath: [CodingKeys(stringValue: "files", intValue: nil)], debugDescription: "Expected to decode String but found a dictionary instead.", underlyingError: nil)))))

标签: iosswiftapi

解决方案


推荐阅读