我试图使用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")
}
答案 0 :(得分:3)
声明地图变量时,不提供默认值,也不会正确实例化。
您需要做的是使用@IBOutlet
将其连接到故事板中的视图,
@IBOutlet weak var map : MKMapView!
或者如果您手动创建视图层次结构,请使用默认值实例化MKMapView。
var map : MKMapView! = MKMapView()
我推荐前者。
答案 1 :(得分:0)
尝试了你的代码。使其适用于以下更改:
评论
locationMangaer.requestAlwaysAuthorization()
评论
mapView.centerCoordinate = userLocation.coordinate
将以下字符串条目添加到Info.plist:
NSLocationWhenInUseUsageDescription
带有任何文字。