2

使用 iPhone6,Xcode 8.1,运行 iOS 10.1.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
4

1 回答 1

0

检查您的response对象不是可选值。

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

更新

我重写了初始化代码localSearch1,希望对您有所帮助。

guard let localSearch1 = MKLocalSearch(request: localSearchRequest1) else { // localSearch1 在这里是 nil return }

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可以省略。

于 2016-11-25T04:34:54.463 回答