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

标签 ios swift mkmapview mapkit

我试图使用 MKMapView 显示用户的位置和位置的 map ,但这样做时出现错误。这行代码出现错误: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")
}

最佳答案

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

您需要做的是使用 @IBOutlet 将它连接到 Storyboard中的 View ,

@IBOutlet weak var map : MKMapView!

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

var map : MKMapView! = MKMapView()

我推荐前者。

关于ios - 使用 MKMapView 时出现此错误! : "fatal error unexpectedley found nil while unwrapping optional value",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32209124/

相关文章:

ios - 发送信息到另一个 View Controller

android - 移动应用程序 : how to show the OTP my app sends in a popup without leaving my app?

ios - 使用第二个 UIViewController 启动 ViewPagerController

ios - 声明函数时 "->"在swift中意味着什么?

ios - 使用 GPUImage 重现 iOS 7 玻璃效果

ios - 应用程序无法从 iCloud Drive 中的文档启动

ios - 应用程序开始在 iOS 9.1 Beta 2 上崩溃

Swift 如何在星级评定中显示评级值

ios - 如何识别无法识别的选择器和无法识别的对象?

ios - 使用 MapKit 和 CoreLocation 时的 Xcode 警告