json - 尝试从 GitHub 按名称加载 JSON 格式的存储库列表

标签 json swift api github

我尝试执行 HTTP 请求,以 JSON 格式从 GitHub 获取存储库列表。

这是我的应用程序,它将包含存储库列表和搜索存储库名称的功能。

import Foundation

class NetworkService {

    private init() {}

    static let shared = NetworkService()

    func getData(matching query: String, completionHandler: @escaping (Any) -> ()) {
        let session = URLSession.shared
        var searchUrlComponents = URLComponents()
        searchUrlComponents.scheme = "https"
        searchUrlComponents.host = "api.github.com"
        searchUrlComponents.path = "search/repositories?"
        searchUrlComponents.queryItems = [URLQueryItem(name: "q", value: query)]
        let searchURL = searchUrlComponents.url!
        print(searchUrlComponents.url!
)

        session.dataTask(with: searchURL) { (data, response, error) in
            guard let data = data else { return }

            do {
                let json = try JSONSerialization.jsonObject(with: data, options: [])
                print(json)
            } catch {
                print(error)
            }
            }.resume()
    }
}

在这部分我遇到了错误。

我尝试不使用URLComponent,并得到相同的错误,代码如下所示:

import Foundation

class NetworkService {

    private init() {}

    static let shared = NetworkService()

    func getData(matching query: String, completionHandler: @escaping (Any) -> ()) {
        let session = URLSession.shared
        let searchURL = URL(string: "https://api.github.com/search/repositories?q={swift}")!
        print(searchURL)


        session.dataTask(with: searchURL) { (data, response, error) in
            guard let data = data else { return }

            do {
                let json = try JSONSerialization.jsonObject(with: data, options: [])
                print(json)
            } catch {
                print(error)
            }
            }.resume()
      }
    }

错误如下:

Fatal error: Unexpectedly found nil while unwrapping an Optional value

但是当我在浏览器中使用这样的 URL 发出请求时 ("https://api.github.com/search/repositories?q={swift}") 然后加载 JSON

最佳答案

URLComponents路径必须以斜杠开头,并且不能以问号结尾

searchUrlComponents.path = "/search/repositories"

在第二个示例中,如果省略大括号,则 URL 有效

let searchURL = URL(string: "https://api.github.com/search/repositories?q=swift")!

原因是与浏览器不同,API URL(string: 不会隐式编码 URL

关于json - 尝试从 GitHub 按名称加载 JSON 格式的存储库列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57804904/

相关文章:

ruby-on-rails - rails : validation error codes in JSON

ios - 获取 IOS 模拟器中文本字段中的值

swift - 为什么 'throws' 在 Swift 中不是类型安全的?

api - 为分页 API 制作 Scala 迭代器

php - Alamofire JSON 无法序列化

javascript - 在 Django 中,我知道如何构建模板。渲染到响应 ('something.html' )。但是,如何在其中包含 JSON 对象呢?

api - CRM 4.0 使用 API 发送电子邮件时遇到问题...请帮忙!

api - 在预请求脚本中调用来自集合的请求

php - 通过某些路由前缀捕获未找到错误 [Laravel]

ios - SpriteKit 简单形状不绘制