I had a Massive View Controller and attempting to separate my code into different classes. I created a class CurrentLocation. In the View Controller I called the google maps method animateToLocation and I get an EXC Bad Instruction. Have done a fair amount of research on proper app architecture but still new and learning through experience. Using google maps for iOS and trying to implement this properly. Is it acceptable to put the updating location in a separate class from the ViewController Then just call the methods I desire to call in the ViewController? I am thinking that I've implemented Model-View-Controller correctly and maybe just inheriting something I should not have. Should be a simple fix just have no idea where to start.
import UIKit
import GoogleMaps
class ViewController: UIViewController, CLLocationManagerDelegate, GMSMapViewDelegate {
@IBOutlet weak var googleMapView: GMSMapView!
let locationManager = CLLocationManager()
let currentLocation = CurrentLocation()
override func viewDidLoad() {
super.viewDidLoad()
currentLocation.trackLocation
}
override func viewDidAppear(animated: Bool)
{
super.viewDidAppear(animated)
if CLLocationManager.locationServicesEnabled() {
googleMapView.myLocationEnabled = true
googleMapView.animateToLocation(currentLocation.coordinate) // EXC Bad Instruction
} else
{
locationManager.requestWhenInUseAuthorization()
}
}
import Foundation
import CoreLocation
import GoogleMaps
class CurrentLocation: NSObject,CLLocationManagerDelegate {
override init()
{
super.init()
}
var locationManager = CLLocationManager()
var location : CLLocation!
var coordinate : CLLocationCoordinate2D!
var latitude : CLLocationDegrees!
var longitude : CLLocationDegrees!
func trackLocation()
{
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestWhenInUseAuthorization()
locationManager.startUpdatingLocation()
}
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation])
{
if CLLocationManager.locationServicesEnabled() {
location = locations.last
coordinate = CLLocationCoordinate2DMake(location.coordinate.latitude, location.coordinate.longitude)
latitude = coordinate.latitude
longitude = coordinate.longitude
}
}
This error is happening because currentLocation.coordinate
is nil
and you're accessing it as an implicitly unwrapped optional. Basically, you're trying to access a variable before it has anything in in. You need to initialize a CLLocationManager
, ask for permissions, and then start updating the location. Check out this great writeup from NSHipster: Core Location in iOS 8.