使用索引访问数组元素时出现错误 'Unexpectedly found nil while unwrapping an Optional value'
Getting the error 'Unexpectedly found nil while unwrapping an Optional value' when using index to access the array elements
我正在使用私有函数从我的 viewController 调用 API 服务。
private func updateCells() -> Void {
let cities: [String] = ["New York", "London", "Tokyo", "Toronto", "Sydney", "Paris"]
for cityName in cities {
print(cityName)
queryService.getSearchResults(cityName: cityName){results, errorMessage in
if let results = results{
self.myCity = results
self.CityGrid.reloadData()
self.list.append(results)
print("Test -> name: \(results.name)")
print("Test -> description: \(results.description)")
print("Test -> currentTemp: \(Int(results.currentTemperature))")
print(self.list[0])
}
if !errorMessage.isEmpty {
print("Search error: " + errorMessage)
let alert = UIAlertController(title: "Error", message: errorMessage, preferredStyle: UIAlertController.Style.alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertAction.Style.cancel, handler: nil))
self.present(alert, animated: true, completion: nil)
}
}
}
}
此处 QueryService class 函数处理 API 调用。
func getSearchResults(cityName: String, completion: @escaping QueryResult) {
dataTask?.cancel()
let url = URL(string: "http://api.openweathermap.org/data/2.5/weather?q=\(cityName)&units=metric&appid=zezfac1ecbe0511f1ac192add4ff112e")!
dataTask = defaultSession.dataTask(with: url) { [weak self] data, response, error in
defer {
self?.dataTask = nil
}
if let error = error {
self?.errorMessage += "Default Task Error: " + error.localizedDescription + "\n"
} else if
let data = data,
let response = response as? HTTPURLResponse,
response.statusCode == 200 {
self?.updateRestults(data)
DispatchQueue.main.async {
completion(self?.location, self?.errorMessage ?? "")
}
}
else if let res = response as? HTTPURLResponse,
res.statusCode == 404{
self?.errorMessage = "City Not Found"
DispatchQueue.main.async {
completion(self?.location, self?.errorMessage ?? "Not Found")
}
//print("City Not found")
}
}
dataTask?.resume()
}
但是在展开可选值时出现意外发现 nil 错误。但如果我使用硬编码字符串,它就可以正常工作。我在这里做错了什么?由于 cities 数组是 String 类型,
这里的问题是字符串"New York"
里面有space,而那些space直接放到了URL中,导致URL 的初始化失败。如果不先将空格编码为 %20
.
,则空格在 URL 中无效
您应该将 let cities: [String] = ...
行更改为 var cities: [String] = ...
并在其下方添加右行:
cities = cities.map { [=14=].replacingOccurrences(of: " ", with: "%20") }
这会将城市名称中的每个 space 替换为 %20
并将其存储回变量 cities
.
我正在使用私有函数从我的 viewController 调用 API 服务。
private func updateCells() -> Void {
let cities: [String] = ["New York", "London", "Tokyo", "Toronto", "Sydney", "Paris"]
for cityName in cities {
print(cityName)
queryService.getSearchResults(cityName: cityName){results, errorMessage in
if let results = results{
self.myCity = results
self.CityGrid.reloadData()
self.list.append(results)
print("Test -> name: \(results.name)")
print("Test -> description: \(results.description)")
print("Test -> currentTemp: \(Int(results.currentTemperature))")
print(self.list[0])
}
if !errorMessage.isEmpty {
print("Search error: " + errorMessage)
let alert = UIAlertController(title: "Error", message: errorMessage, preferredStyle: UIAlertController.Style.alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertAction.Style.cancel, handler: nil))
self.present(alert, animated: true, completion: nil)
}
}
}
}
此处 QueryService class 函数处理 API 调用。
func getSearchResults(cityName: String, completion: @escaping QueryResult) {
dataTask?.cancel()
let url = URL(string: "http://api.openweathermap.org/data/2.5/weather?q=\(cityName)&units=metric&appid=zezfac1ecbe0511f1ac192add4ff112e")!
dataTask = defaultSession.dataTask(with: url) { [weak self] data, response, error in
defer {
self?.dataTask = nil
}
if let error = error {
self?.errorMessage += "Default Task Error: " + error.localizedDescription + "\n"
} else if
let data = data,
let response = response as? HTTPURLResponse,
response.statusCode == 200 {
self?.updateRestults(data)
DispatchQueue.main.async {
completion(self?.location, self?.errorMessage ?? "")
}
}
else if let res = response as? HTTPURLResponse,
res.statusCode == 404{
self?.errorMessage = "City Not Found"
DispatchQueue.main.async {
completion(self?.location, self?.errorMessage ?? "Not Found")
}
//print("City Not found")
}
}
dataTask?.resume()
}
但是在展开可选值时出现意外发现 nil 错误。但如果我使用硬编码字符串,它就可以正常工作。我在这里做错了什么?由于 cities 数组是 String 类型,
这里的问题是字符串"New York"
里面有space,而那些space直接放到了URL中,导致URL 的初始化失败。如果不先将空格编码为 %20
.
您应该将 let cities: [String] = ...
行更改为 var cities: [String] = ...
并在其下方添加右行:
cities = cities.map { [=14=].replacingOccurrences(of: " ", with: "%20") }
这会将城市名称中的每个 space 替换为 %20
并将其存储回变量 cities
.