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

标签 ios swift xcode8

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

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

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

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

    }
})

**** Console Log ****

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

最佳答案

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

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

更新

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

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

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

关于ios - nils 在 MKLocalSearch 请求中发现解包可选值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40797629/

相关文章:

ios - 按下按钮时更改按钮 "+"、 "-"、 "/"、 "*"的背景(清晰且相等)。 (IOS)

ios - 在 xcode8 中找不到 ModuleName-Swift.h 文件

ios - ios 可以播放 h264-mpegts 格式吗?

ios - EKEvents 不会快速填充表格 View

objective-c - 在 Swift 3 中从 Objective-C calloc 重构

xcode - 升级到Xcode 8后,iPhone 4和iPhone 4s模拟器消失了。如何找回它们?

ios - 如何在 IOS 8 中制作像 Spotify 那样的侧边栏菜单

ios - 如何使两个 SKSpriteNode 的交集透明

ios - 如何在 iOS8 自定义键盘中使用自动更正和快捷键列表?

ios - 在 Swift Playground 的时间轴 View 中添加链接