gpt4 book ai didi

输入多个单词时,Swift UIText 字段抛出 nil 错误

转载 作者:行者123 更新时间:2023-11-28 08:09:09 25 4
gpt4 key购买 nike

我的程序正在使用 map ,我有一个 UITextField,用户可以在其中输入搜索短语,然后 map 将在 map 上显示搜索结果的注释。该程序在模拟器中运行良好,但在我的手机上测试时,如果我输入两个作品(如“dog park”),它会抛出“nil while unwrapping an Optional value”错误。但是如果我只输入“狗”,程序不会在我的手机上抛出错误。我在 ViewDidLoad 中设置了委托(delegate),并且我的所有网点都已正确链接。我在这里搜索并尝试解决问题无济于事,所以我想我会问问你们是否注意到我遗漏了什么。

这是 UITextLabel 搜索的函数:

@IBAction func searchField(_ sender: UITextField) {
let allAnnotations = self.mapView.annotations
self.mapView.removeAnnotations(allAnnotations)
let request = MKLocalSearchRequest()
request.naturalLanguageQuery = textField.text!
request.region = mapView.region

let search = MKLocalSearch(request: request)
search.start(completionHandler: {(response, error) in

if error != nil{
print("Error occured in search: \(error!.localizedDescription)")
}else if response!.mapItems.count == 0{
self.textField.text = "No matches found"
}else{
print("Matches found")
for item in response!.mapItems{
let annotation = MKPointAnnotation()
annotation.coordinate = item.placemark.coordinate
annotation.title = item.name
annotation.subtitle = item.placemark.thoroughfare! + ", " + item.placemark.locality! + ", " + item.placemark.administrativeArea!
self.mapView.addAnnotation(annotation)
}
}
})
sender.resignFirstResponder()
}

最佳答案

所以在进一步研究之后,我发现了一个不需要添加到 naturalLanguageQuery 字符串的答案。问题是 for 循环返回了一个空值。让一名 guard 进来响应解决了这个问题。

@IBAction func searchField(_ sender: UITextField) {
let allAnnotations = self.mapView.annotations
self.mapView.removeAnnotations(allAnnotations)
let request = MKLocalSearchRequest()
request.naturalLanguageQuery = textField.text!
request.region = mapView.region

let search = MKLocalSearch(request: request)
search.start(completionHandler: {(response, error) in

if error != nil{
print("Error occured in search: \(error!.localizedDescription)")
}else if response!.mapItems.count == 0{
self.textField.text = "No matches found"
}else{
print("Matches found")
guard let response = response?.mapItems else { return }
for item in response{
let annotation = MKPointAnnotation()
annotation.coordinate = item.placemark.coordinate
annotation.title = item.name
annotation.subtitle = item.placemark.thoroughfare! + ", " + item.placemark.locality! + ", " + item.placemark.administrativeArea!

self.mapView.addAnnotation(annotation)
}
}
})
sender.resignFirstResponder()
}

关于输入多个单词时,Swift UIText 字段抛出 nil 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44185608/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com