【发布时间】: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。
【问题讨论】: