我试图使用 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/