【问题标题】:Swift: "mapView.showUserLocation = true" returns "fatal error: unexpectedly found nil while unwrapping an Optional value (lldb) "Swift:“mapView.showUserLocation = true”返回“致命错误:在展开可选值(lldb)时意外发现 nil”
【发布时间】:2015-04-26 19:06:02
【问题描述】:

所以我尝试使用“bar”或“pizza”等关键字在 Swift 中搜索本地企业。我将搜索链接到一个按钮操作,以便这些位置将在定义区域内的地图上弹出。但是,我什至无法让应用程序加载用户位置,因为我得到一个 nil 错误。

这是我的 AppDelegate:

import UIKit
import CoreLocation

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

var window: UIWindow?
var locationManager: CLLocationManager?

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
    // Override point for customization after application launch.
    locationManager = CLLocationManager()
    locationManager?.requestWhenInUseAuthorization()
    return true
}

func applicationWillResignActive(application: UIApplication) {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

func applicationDidEnterBackground(application: UIApplication) {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

func applicationWillEnterForeground(application: UIApplication) {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

func applicationDidBecomeActive(application: UIApplication) {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

func applicationWillTerminate(application: UIApplication) {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}


}

这是我的 ViewController.swift:

import Foundation
import UIKit
import MapKit

class ViewController: UIViewController, MKMapViewDelegate {

@IBOutlet weak var mapView: MKMapView!

@IBAction func searchBars(sender: AnyObject) {
    let request = MKLocalSearchRequest()
    request.naturalLanguageQuery = "Bar"
    request.region = mapView.region

    let search = MKLocalSearch(request: request)
    search.startWithCompletionHandler({(response: MKLocalSearchResponse!, error: NSError!) in

        if error != nil {
            println("Error occurred in search: \(error.localizedDescription)")
        } else if response.mapItems.count == 0 {
            println("No matches found")

            for item in response.mapItems as [MKMapItem] {
                println("Name = \(item.name)")
                println("Phone = \(item.phoneNumber)")
            }
        }
        })

}

func mapView(mapView: MKMapView!, didUpdateUserLocation userLocation: MKUserLocation!) {
    mapView.centerCoordinate = userLocation.location.coordinate
}

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
    mapView.showsUserLocation = true
    mapView.delegate = self
}

@IBAction func zoomIn(sender: AnyObject) {
    let userLocation = mapView.userLocation

    let region = MKCoordinateRegionMakeWithDistance(userLocation.location.coordinate, 2000, 2000)
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}


}

返回 nil 错误的行在我的 ViewController.swift 文件中 @IBAction func zoomIn 下,其中包含以下行:let region = MKCoordinateRegionMakeWithDistance(userLocation.location.coordinate, 2000, 2000)。由于某种原因,它给出了一个 nil 值。

【问题讨论】:

  • 你没有分配weak var mapView: MKMapView!。如果你想让它连接到插座,你可能没有这样做。
  • 所以我必须将它连接到插座?我无法理解您的回答。

标签: ios swift mapkit


【解决方案1】:

您对这一行所做的是创建一个尚未实例化的 mapView 对象。

weak var mapView: MKMapView!

您收到错误是因为您尝试将 showsUserLocation 属性更改为尚不存在的对象,它是 nil。

如果您在情节提要中创建地图,您需要做的是删除弱 var 行并改为放置 IBOutlet(Ctrl + 单击并从情节提要中拖动)。

【讨论】:

  • 好的,这样就清除了错误。但现在我得到了另一个零值。我觉得 techotopia 代码的解释真的很糟糕。我的下一个零值是:@IBAction func zoomIn(sender: AnyObject) { let userLocation = mapView.userLocation let region = MKCoordinateRegionMakeWithDistance(userLocation.location.coordinate, 2000, 2000) mapView.setRegion(region, animated: true) }
  • 是的。技术乌托邦是垃圾。你能更新你的代码和你得到的新错误吗?
  • 代码更新了!好的,所以我刚刚发现我必须 -> 播放我的应用程序 -> 回到 XCode -> 调试 -> 模拟位置 -> 选择一个位置。然后它将显示位置点。所以这个问题就解决了。但是(我讨厌 Enter 保存评论...)我的缩放按钮不起作用,当我选择按钮搜索附近的位置时,它没有显示任何结果。最终,我的目标是根本不显示搜索结果,只将其中的 5 个存储到一个表中。然而,现在我想确保我已经掌握了 MapKit 的基础知识,我显然不会大声笑。
  • 好的,我更新了代码。当我尝试在 Zoom In 上设置区域时出现错误。
【解决方案2】:

非常感谢Skoua 的帮助。在他帮助我使用 IBOutlet 之后,我自己弄清楚了哪里出了问题。

这是更正后的代码。

@IBAction func searchBars(sender: AnyObject) {
    matchingItems.removeAll()
    let request = MKLocalSearchRequest()
    request.naturalLanguageQuery = "bar"
    request.region = mapView.region

    let search = MKLocalSearch(request: request)
    search.startWithCompletionHandler({(response: MKLocalSearchResponse!, error: NSError!) in

        if error != nil {
            println("Error occurred in search: \(error.localizedDescription)")
        } else if response.mapItems.count == 0 {
            println("No matches found")
//This is where the problem occured
        } else {
            println("Matches found")
        //I needed to insert an else statement for matches being found
            for item in response.mapItems as [MKMapItem] {
                //This prints the 'matches' into [MKMapItem]
                println("Name = \(item.name)")
                println("Phone = \(item.phoneNumber)")

                self.matchingItems.append(item as MKMapItem)
                println("Matching items = \(self.matchingItems.count)")

                var annotation = MKPointAnnotation()
                annotation.coordinate = item.placemark.coordinate
                annotation.title = item.name
                self.mapView.addAnnotation(annotation)
            }
        }
        })

}

【讨论】:

    猜你喜欢
    • 2015-03-04
    • 1970-01-01
    • 2016-02-29
    相关资源
    最近更新 更多