我尝试执行 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/