nils发现在MKLocalSearch请求中解包可选值

时间:2016-11-25 04:14:50

标签: ios swift xcode8.1

使用运行iOS 10.1.1的iPhone6,Xcode 8.1,执行以下Swift代码,我在这个简单的代码中间歇地得到fatal error: unexpectedly found nil unwrapping Optional value

它在50%的时间内没有错误地工作,这使我相信它与搜索调用在某种程度上相关需要更长时间才能完成,正如在我发现的类似MapKit问题的某些解决方案中所建议的那样。但是错误似乎发生在完成处理程序中,它不包含可选值,所以我不明白如何获得nil结果。

代码片段和控制台输出如下所示。任何见解将不胜感激。

class ViewController: UIViewController, UISearchBarDelegate, MKMapViewDelegate,UINavigationControllerDelegate {
    var searchController:UISearchController!


func searchBarSearchButtonClicked(_ searchBar: UISearchBar){
    //1
    print("Entered searchBarSearchButtonClicked")
    searchBar.resignFirstResponder()
    dismiss(animated: true, completion: nil)
    if self.mapView.annotations.count != 0{
        annotation = self.mapView.annotations[0] // both are type MKAnnotation
        self.mapView.removeAnnotation(annotation)
    }

    //2 make 1st search request
    print("Make 1st search request")
    let localSearchRequest1 = MKLocalSearchRequest()
    localSearchRequest1.naturalLanguageQuery = searchBar.text
    print("localSearchRequest1 initialized")

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

        if error != nil {
            print("Error occured in search:\(error!.localizedDescription)")
        } else  {

        //3 make annotation pin
        print("make annotation pin")
        self.pointAnnotation = MKPointAnnotation()
        print(searchBar.text ?? "searchBarText")
        self.pointAnnotation.title = searchBar.text
        print(response!.boundingRegion.center.latitude)
        self.pointAnnotation.coordinate = CLLocationCoordinate2D(latitude: response!.boundingRegion.center.latitude,           longitude:     response!.boundingRegion.center.longitude)
        self.coord1 = self.pointAnnotation.coordinate

        self.placeMark1 = MKPlacemark(coordinate: self.pointAnnotation.coordinate, addressDictionary: nil)


        self.pinAnnotationView = MKPinAnnotationView(annotation: self.pointAnnotation, reuseIdentifier: nil)
        self.mapView.centerCoordinate = self.pointAnnotation.coordinate
        self.mapView.addAnnotation(self.pinAnnotationView.annotation!)
        self.searchButtonClicked += 1

    }
})
  

****控制台日志****

Entered showSearchBar

Presented searchController

2016-11-24 22:07:41.409907 MapLocator 3 Match[1116:587460] [MC] System group container for systemgroup.com.apple.configurationprofiles path is /private/var/containers/Shared/SystemGroup/systemgroup.com.apple.configurationprofiles

2016-11-24 22:07:41.420495 MapLocator 3 Match[1116:587460] [MC] Reading from public effective user settings.

Entered searchBarSearchButtonClicked

Make 1st search request

localSearchRequest1 initialized

fatal error: unexpectedly found nil while unwrapping an Optional value

2016-11-24 22:07:46.072037 MapLocator 3 Match[1116:587460] fatal error: unexpectedly found nil while unwrapping an Optional value

1 个答案:

答案 0 :(得分:0)

检查response对象不是可选值。

如果您想使用response!.boundingRegion.center.latitude,请使用guard let response = response else确保response不是nil

更新

我从初始化localSearch1重写代码,希望它可能会有所帮助。

警卫让localSearch1 = MKLocalSearch(请求:localSearchRequest1)else {         // localSearch1在这里没有         返回     }

localSearch1.start(completionHandler: {(response, error) in

    if error != nil {
        // Has an error, return
        print("Error occured in search:\(error.localizedDescription)")
        return
    }

    guard let response = response else {
        // response = nil, return
        print("No response data")
        return
    }

    // Make annotation pin
    self.pointAnnotation = MKPointAnnotation()

    self.pointAnnotation.title = searchBar.text ?: ""
    self.pointAnnotation.coordinate = CLLocationCoordinate2D(latitude: response.boundingRegion.center.latitude,
                                                            longitude: response.boundingRegion.center.longitude)
    self.coord1 = self.pointAnnotation.coordinate
    self.placeMark1 = MKPlacemark(coordinate: self.pointAnnotation.coordinate, addressDictionary: nil)

    self.pinAnnotationView = MKPinAnnotationView(annotation: self.pointAnnotation, reuseIdentifier: nil)
    self.mapView.centerCoordinate = self.pointAnnotation.coordinate
    self.mapView.addAnnotation(self.pinAnnotationView.annotation!) // I don't know whether this annotation is nil or not
    self.searchButtonClicked += 1
}

另外,您应该知道在Swift中,self可以省略。