【问题标题】:Getting this error when using MKMapView! : "fatal error unexpectedley found nil while unwrapping optional value"使用 MKMapView 时出现此错误! :“在展开可选值时发现意外的致命错误为零”
【发布时间】:2015-08-25 16:20:29
【问题描述】:

我正在尝试使用 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")
}

【问题讨论】:

    标签: ios swift mkmapview mapkit


    【解决方案1】:

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

    您需要做的是使用@IBOutlet 将其连接到情节提要中的视图,

    @IBOutlet weak var map : MKMapView!
    

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

    var map : MKMapView! = MKMapView()
    

    我推荐前者。

    【讨论】:

    • 我没有再收到错误但地图由于某种原因没有显示出来。只有一个黑色的画面。
    • 这篇文章建议将您的项目与 CoreGraphics.framework stackoverflow.com/questions/26037700/… 链接起来
    • 还是黑屏,没有地图。
    【解决方案2】:

    尝试了您的代码。使其适用于以下更改:

    注释掉

    locationMangaer.requestAlwaysAuthorization()
    

    注释掉

    mapView.centerCoordinate = userLocation.coordinate
    

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

    NSLocationWhenInUseUsageDescription
    

    任何文字。

    【讨论】:

    • 我按照你说的做了,但我没有看到地图。我只得到一个黑屏。
    • 我在 SpriteKit 中重要吗?
    • @coding22 尝试手动将MKMapView 实例化为let map = MKMapView()。我使用IBOutlet 进行测试。觉得没关系。尝试在错误委托函数中添加println(error),很好奇可能有什么。
    • 执行此操作时没有收到错误消息,控制台中没有打印任何内容,也没有地图。我还尝试使用 IBOutlet 并显示地图,但是当我按下按钮时我需要它来。我该怎么做?
    • @coding22 使用alpha = 0.0 制作地图,然后通过UIView.animateWithDuration(0.5, animations: { () -> Void in map.alpha = 1.0 }) 在按钮按下时对其进行动画处理
    猜你喜欢
    • 1970-01-01
    • 2016-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多