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

时间:2017-05-25 16:37:21

标签: swift uitextfield mapkit optional

我的程序正在使用地图,我有一个UITextField,用户输入一个搜索短语,地图将在地图上显示搜索结果的注释。 该程序在模拟器中运行良好,但在我的手机上进行测试时,它会在打开一个Optional值时抛出一个" nil;如果我输入两个作品,例如"狗公园",则会出错。但如果我只是输入" dog"该程序不会在我的手机上抛出错误。例如。我在ViewDidLoad中设置了委托,并且我的所有插座都已正确链接。 我在这里搜索并尝试解决问题无济于事,所以我想我会问,看看你们是否注意到我错过了什么。

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

1 个答案:

答案 0 :(得分:0)

所以在研究了这个之后我找到了一个不需要添加到naturalLanguageQuery字符串的答案。问题是for循环返回一个空值。让警卫让响应解决了它。

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