使用 MKMapView 时出现此错误! : "fatal error unexpectedley found nil while unwrapping optional value"

Getting this error when using MKMapView! : "fatal error unexpectedley found nil while unwrapping optional value"

我正在尝试使用 MKMapView 显示用户的位置和该位置的地图,但这样做时出现错误。这行代码出现错误:map.delegate = self.这是完整的代码,有人可以告诉我我做错了什么。我查看了其他教程,他们的设置方式与我设置的方式相同,并且适用于他们。谢谢!

import Foundation
import SpriteKit
import CoreLocation
import MapKit



class MapScene: SKScene, CLLocationManagerDelegate, MKMapViewDelegate {
var locationMangaer = CLLocationManager()
var map : MKMapView!

override func didMoveToView(view: SKView) {

    locationMangaer.delegate = self
    locationMangaer.desiredAccuracy = kCLLocationAccuracyBest
    locationMangaer.requestWhenInUseAuthorization()
    locationMangaer.startUpdatingLocation()
    locationMangaer.requestAlwaysAuthorization()

    map.delegate = self
    map.showsUserLocation = true


}



//DELEGATE METHODS

func locationManager(manager: CLLocationManager!, didFailWithError error: NSError!) {

    println("error")
}



func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {


    var userLocation: CLLocation = locations[0] as! CLLocation
    locationMangaer.stopUpdatingLocation()

    let location = CLLocationCoordinate2DMake(userLocation.coordinate.latitude, userLocation.coordinate.longitude)
    let span = MKCoordinateSpanMake(0.05, 0.05)
    let region = MKCoordinateRegion(center: location, span: span)

    map.setRegion(region, animated: true)
    map.centerCoordinate = userLocation.coordinate


    println("call")
}

当您声明您的地图变量时,您没有提供默认值,它也没有正确实例化。

您需要做的是使用 @IBOutlet,

将它连接到故事板中的视图
@IBOutlet weak var map : MKMapView!

或者,如果您手动创建视图层次结构,请使用默认值实例化 MKMapView。

var map : MKMapView! = MKMapView()

我推荐前者。

试过你的代码。通过以下更改使其工作:

注释掉

locationMangaer.requestAlwaysAuthorization()

注释掉

mapView.centerCoordinate = userLocation.coordinate

将以下字符串条目添加到 Info.plist:

NSLocationWhenInUseUsageDescription

任何文本。