【问题标题】:Trying to load list of repositories by name from GitHub in JSON format尝试以 JSON 格式从 GitHub 按名称加载存储库列表
【发布时间】:2019-09-05 11:52:35
【问题描述】:

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

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

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()
      }
    }

类似的错误:

致命错误:在展开可选值时意外发现 nil

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

【问题讨论】:

    标签: json swift api github


    【解决方案1】:

    URLComponentspath 必须以斜杠开头,不能以问号结尾

    searchUrlComponents.path = "/search/repositories"
    

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

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

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

    【讨论】:

      猜你喜欢
      • 2021-04-24
      • 2017-11-17
      • 1970-01-01
      • 1970-01-01
      • 2019-06-17
      • 1970-01-01
      • 2021-07-09
      • 2023-03-13
      • 1970-01-01
      相关资源
      最近更新 更多