Reputation: 689
Im trying to show the user's location and a map of the location using MKMapView but I get an error when doing so. I get an error for this line of code: map.delegate = self. Here's the full code, can someone tell me what I'm doing wrong. I looked at other tutorials and they have it the same way I have it setup and it works for them. Thank you!
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")
}
Upvotes: 0
Views: 1366
Reputation: 4176
Tried your code. Make it work with the following changes:
Comment out
locationMangaer.requestAlwaysAuthorization()
Comment out
mapView.centerCoordinate = userLocation.coordinate
Add the following String entry to Info.plist:
NSLocationWhenInUseUsageDescription
with any text.
Upvotes: 0
Reputation: 1754
When you declare your map variable, you do not provide a default value, and it doesn't instantiate properly.
What you need to do is hook it up to a view in your storyboard with an @IBOutlet
,
@IBOutlet weak var map : MKMapView!
or if you are manually creating your view hierarchy, instantiate a MKMapView with a default value.
var map : MKMapView! = MKMapView()
I recommend the former.
Upvotes: 3