How to fix Thread 1: Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value? - ios

I have a problem with the Users Location.
When im trying to build the program it gets this error code: (Thread 1: Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value)
My code:
import UIKit
import MapKit
class ViewController: UIViewController {
private let locationManager = CLLocationManager()
private var currentCoordinate: CLLocationCoordinate2D?
#IBOutlet weak var mapView: MKMapView!
override func viewDidLoad() {
super.viewDidLoad()
configerLocationServices()
}
private func configerLocationServices() {
locationManager.delegate = self
let status = CLLocationManager.authorizationStatus()
if status == .notDetermined {
locationManager.requestWhenInUseAuthorization()
} else if status == .authorizedAlways || status == .authorizedWhenInUse {
beginLocationUpdates(locationManager: locationManager)
}
}
private func beginLocationUpdates(locationManager: CLLocationManager) {
mapView.showsUserLocation = true //<--- the problem is here
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.startUpdatingLocation()
}
private func zoomToLastestLocation(with coordinate: CLLocationCoordinate2D) {
let zoomRegion = MKCoordinateRegion(center: coordinate, latitudinalMeters: 10000, longitudinalMeters: 10000)
mapView.setRegion(zoomRegion, animated: true)
}
}
extension ViewController: CLLocationManagerDelegate {
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
print("Did get latest Location")
guard let latestLocation = locations.first else { return }
if currentCoordinate == nil {
zoomToLastestLocation(with: latestLocation.coordinate)
}
currentCoordinate = latestLocation.coordinate
}
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
print("The Status changed")
if status == .authorizedAlways || status == .authorizedWhenInUse {
self.beginLocationUpdates(locationManager: manager)
}
}
}
I don't know what im doing wrong, has anyone the solution?
Thank you in advance.

private func setNewLoaction(lat:CLLocationDegrees,long:CLLocationDegrees,markerTitle:String){
let center = CLLocationCoordinate2D(latitude: lat, longitude: long)
let camera = GMSCameraPosition.camera(withLatitude: lat, longitude: long, zoom: 15)
self.googleMapsView?.camera = camera
self.googleMapsView?.isMyLocationEnabled = true
let marker = GMSMarker(position: center)
marker.map = self.googleMapsView
marker.title = markerTitle
locationManager.stopUpdatingLocation()
}
//MARK:- MAP VIEW
private func setUpMap(){
locationManager.delegate = self
locationManager.requestWhenInUseAuthorization()
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.startUpdatingLocation()
self.googleMapsView = GMSMapView (frame: CGRect(x: 0, y: 0, width: self.view.frame.width-30, height: self.mapView.frame.height))
self.googleMapsView?.settings.compassButton = true
self.googleMapsView?.isMyLocationEnabled = true
self.googleMapsView?.settings.myLocationButton = true
self.mapView.addSubview(self.googleMapsView!)
}
I have called setUpMap in ViewDidload and this setLoaction function in GMSAutocompleteViewControllerDelegate =:
func viewController(_ viewController: GMSAutocompleteViewController, didAutocompleteWith place: GMSPlace) {
destinationField.text = place.formattedAddress
destinationLatitude = place.coordinate.latitude
destinationLongitutude = place.coordinate.longitude
setNewLoaction(lat: destinationLatitude!, long: destinationLongitutude!, markerTitle: "Destination Location")
dismiss(animated: true, completion: nil)
}
you can call this anywhere as per you need, do remember to turn on location when asked for permission and if using in simlulator go to Features/Loaction/custom Location

I have now an other code for the same thing it is shorter than the old one.
Here is the code:
import UIKit
import MapKit
import CoreLocation
class ViewController: UIViewController {
#IBOutlet var mapView: MKMapView!
let locationManager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
locationManager.requestWhenInUseAuthorization()
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.distanceFilter = kCLDistanceFilterNone
locationManager.startUpdatingLocation()
mapView.showsUserLocation = true // <--- Crash
}
}
And now it gets the same problem as the old one :(

Related

How to fix the error begin LocationUpdates?

I'm working on an App that shows the user's location and other Annotations.
I'm following a Youtube Tutorial to show the user's location.
(If you want to look at the tutorial). here: https://www.youtube.com/watch?v=SayMogu530A&t=132s
(I'm on 18:55 min right now.)
My code:
import UIKit
import MapKit
class ViewController: UIViewController {
private let locationManager = CLLocationManager()
private var currentCoordinate: CLLocationCoordinate2D?
#IBOutlet weak var mapView: MKMapView!
override func viewDidLoad() {
super.viewDidLoad()
configerLocationServices()
}
private func configerLocationServices() {
locationManager.delegate = self
let status = CLLocationManager.authorizationStatus()
if status == .notDetermined {
locationManager.requestWhenInUseAuthorization()
} else if status == .authorizedAlways || status == .authorizedWhenInUse {
beginLocationUpdates(LocatioManager: locationManager)
}
}
private func beginLocationUpdates(LocatioManager: CLLocationManager) {
mapView.showsUserLocation = true
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.startUpdatingLocation()
}
private func zoomToLastestLocation(with coordinate: CLLocationCoordinate2D) {
let zoomRegion = MKCoordinateRegion(center: coordinate, latitudinalMeters: 10000, longitudinalMeters: 10000)
mapView.setRegion(zoomRegion, animated: true)
}
}
extension ViewController: CLLocationManagerDelegate {
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
print("Did get latest Location")
guard let latestLocation = locations.first else { return }
if currentCoordinate == nil {
zoomToLastestLocation(with: latestLocation.coordinate)
}
currentCoordinate = latestLocation.coordinate
}
}
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
print("The Status changed")
if status == .authorizedAlways || status == .authorizedWhenInUse {
beginLocationUpdates(locationManager: manager) //Error: Cannot find'beginLocationUpdates' in scope
}
}
I don't know what I'm doing wrong. The guy in the Tutorial hasn't the problem.
Thank you in advance :)
It's typing mistake. You have to write the function inside the extension and use the correct parameter name.
class ViewController: UIViewController {
private let locationManager = CLLocationManager()
private var currentCoordinate: CLLocationCoordinate2D?
#IBOutlet weak var mapView: MKMapView!
override func viewDidLoad() {
super.viewDidLoad()
configerLocationServices()
}
private func configerLocationServices() {
locationManager.delegate = self
let status = CLLocationManager.authorizationStatus()
if status == .notDetermined {
locationManager.requestWhenInUseAuthorization()
} else if status == .authorizedAlways || status == .authorizedWhenInUse {
beginLocationUpdates(locationManager: locationManager) //<-- Here
}
}
private func beginLocationUpdates(locationManager: CLLocationManager) { //<-- Here
mapView.showsUserLocation = true
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.startUpdatingLocation()
}
private func zoomToLastestLocation(with coordinate: CLLocationCoordinate2D) {
let zoomRegion = MKCoordinateRegion(center: coordinate, latitudinalMeters: 10000, longitudinalMeters: 10000)
mapView.setRegion(zoomRegion, animated: true)
}
}
extension ViewController: CLLocationManagerDelegate {
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
print("Did get latest Location")
guard let latestLocation = locations.first else { return }
if currentCoordinate == nil {
zoomToLastestLocation(with: latestLocation.coordinate)
}
currentCoordinate = latestLocation.coordinate
}
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
print("The Status changed")
if status == .authorizedAlways || status == .authorizedWhenInUse {
self.beginLocationUpdates(locationManager: manager) //<-- Here
}
}
} //<-- Here

How do I make "Center location on Map" work?

I am new to programing.
I have found the code below and it does everything but center location.(zoom in, map, blue dot all work.)
If I run in simulator, (city run) the blue dot just runs off the page.
import UIKit
import MapKit
import CoreLocation
import Foundation
class ViewController: UIViewController, CLLocationManagerDelegate {
#IBOutlet weak var map: MKMapView!
var locationManager: CLLocationManager?
override func viewDidLoad() {
super.viewDidLoad()
locationManager = CLLocationManager()
locationManager!.delegate = self
map.showsUserLocation = true
if CLLocationManager.authorizationStatus() == .authorizedWhenInUse {
locationManager!.startUpdatingLocation()
} else {
locationManager!.requestWhenInUseAuthorization()
}
}
private func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus) {
switch status {
case .notDetermined:
print("NotDetermined")
case .restricted:
print("Restricted")
case .denied:
print("Denied")
case .authorizedAlways:
print("AuthorizedAlways")
case .authorizedWhenInUse:
print("AuthorizedWhenInUse")
locationManager!.startUpdatingLocation()
}
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let location = locations.first!
let coordinateRegion = MKCoordinateRegionMakeWithDistance(location.coordinate, 500, 500)
map.setRegion(coordinateRegion, animated: true)
locationManager?.stopUpdatingLocation()
locationManager = nil
}
}
Delete your implementation of
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
Just get authorization, set map.showsUserLocation = true, and stand back.
Here is my Swift 3 code that works and is tested. It loads mapView, ask user's permission and zoom in into his location.
import UIKit
import MapKit
class ViewController: UIViewController, CLLocationManagerDelegate {
#IBOutlet weak var mapView: MKMapView!
let locationManager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
locationManager.activityType = .automotiveNavigation
locationManager.distanceFilter = 10.0
mapView.showsUserLocation = true
mapView.mapType = .standard
self.mapView.delegate = self
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
locationManager.requestWhenInUseAuthorization()
locationManager.startUpdatingLocation()
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let userLocation:CLLocation = locations[0] as CLLocation
locationManager.stopUpdatingLocation()
let location = CLLocationCoordinate2D(latitude: userLocation.coordinate.latitude, longitude: userLocation.coordinate.longitude)
let span = MKCoordinateSpanMake(0.05, 0.05)
let region = MKCoordinateRegion (center: location,span: span)
mapView.setRegion(region, animated: true)
}
}

myLocationEnabled changing to isMyLocationEnabled on swift when using GoogleMaps

Im trying to get a users current location to show with google maps API. I have been struggling with this issue for weeks and the code runs but doesn't update to current location when I change the location in the simulator.
My code is below and after looking how other people are doing it they all have mapView.myLocationEnabled = true whereas for me this produces an error saying 'myLocationEnabled has been renamed to 'isMylocationEnabled'. I've seen some up to date posts (from 2 months ago) and everyone is using myLocationEnabled without an error it seems, why am I getting this? could this be the reason why my current location is not updating?
import UIKit
import GoogleMaps
class FirstViewController: UIViewController, CLLocationManagerDelegate {
#IBOutlet weak var mapView: GMSMapView!
let locationManager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
locationManager.delegate = self
mapView.settings.myLocationButton = true
mapView.settings.compassButton = true
}
override func viewDidAppear(_ animated: Bool) {
locationManager.requestWhenInUseAuthorization()
}
func locationManager(manager: CLLocationManager , didChangeAuthorizationStatus status: CLAuthorizationStatus) {
if status == .authorizedWhenInUse {
locationManager.startUpdatingLocation()
mapView.isMyLocationEnabled = true
mapView.settings.myLocationButton = true
}
}
func locationManager(manager: CLLocationManager ,didUpdateLocations locations: [CLLocation]) {
if let location = locations.first {
mapView.camera = GMSCameraPosition(target: location.coordinate, zoom: 15, bearing: 0, viewingAngle: 0)
let marker = GMSMarker()
marker.title = "Current Location"
marker.map = mapView
locationManager.stopUpdatingLocation()
}
}
}
SO I FINALLY SOLVED THIS! Basically I updated my existing Podfile with GoogleMaps and GooglePlaces and then updated pod to ensure all the frameworks are working. Then I used this code to get my current location to work
import UIKit
import GoogleMaps
class FirstViewController: UIViewController, CLLocationManagerDelegate {
#IBOutlet weak var mapView: GMSMapView!
var locationManager = CLLocationManager()
var vwGMap = GMSMapView()
override func viewDidLoad() {
super.viewDidLoad()
let camera: GMSCameraPosition = GMSCameraPosition.camera(withLatitude: 22.300000, longitude: 70.783300, zoom: 10.0)
vwGMap = GMSMapView.map(withFrame: self.view.frame, camera: camera)
vwGMap.camera = camera
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyKilometer
locationManager.distanceFilter = 500
locationManager.requestWhenInUseAuthorization()
locationManager.requestAlwaysAuthorization()
locationManager.startUpdatingLocation()
self.view = vwGMap
}
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
if (status == CLAuthorizationStatus.authorizedWhenInUse)
{
vwGMap.isMyLocationEnabled = true
}
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let newLocation = locations.last
vwGMap.camera = GMSCameraPosition.camera(withTarget: newLocation!.coordinate, zoom: 15.0)
vwGMap.settings.myLocationButton = true
self.view = self.vwGMap
let marker = GMSMarker()
marker.position = CLLocationCoordinate2DMake(newLocation!.coordinate.latitude, newLocation!.coordinate.longitude)
marker.map = self.vwGMap
}
}

Can't get User Location Using MKMapViewDelegate

I have been reading tutorials about getting user location for several hours, yet I cannot seem to get it. I have my ViewController class implementing CLLocationManagerDelegate and MKMapViewDelegate.
override func viewDidLoad() {
super.viewDidLoad()
self.locationManager.requestWhenInUseAuthorization()
self.mapView.delegate = self
self.mapView.showsUserLocation = true
print("Is User Location Visible: \(self.mapView.userLocation.location?.coordinate.latitude)")
if CLLocationManager.locationServicesEnabled() {
locationManager.delegate = self
print("Authorization Status = \(CLLocationManager.authorizationStatus() == .Denied || CLLocationManager.authorizationStatus() == CLAuthorizationStatus.NotDetermined)")
locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
locationManager.startUpdatingLocation()
locationManager.delegate = self
}
else{
print("location services disabled")
}
}
This seems like it would work, as I have set showsUserLocation to true with MKMapView and started updating location services with CLLocationManager.
However, the printout of viewDidLoad() is:
Is User Location Visible: nil
Authorization Status = false
Whenever I try to access user location, it's nil.
I have NSLocationWhenInUseUsageDescription set in Info.plist as well, it successfully asked me if I want to allow location services and I clicked yes.
Thanks
EDIT:
Here is the full code of MapViewController.swift:
import UIKit
import MapKit
class MapViewController: UIViewController, MKMapViewDelegate, CLLocationManagerDelegate {
var mapView: MKMapView!
let locationManager = CLLocationManager()
override func loadView() {
// create a map view
mapView = MKMapView()
// set the map view we just created as the view for this controller
view = mapView
let ​​​​​​​​​​​​​​​​segmentedControl = UISegmentedControl(items: ["Standard", "Hybrid", "Satellite", "My Location"])
​​​​​​​​​​​​​​​​segmentedControl.backgroundColor = UIColor.whiteColor().colorWithAlphaComponent(0.5)
​​​​​​​​​​​​​​​​segmentedControl.selectedSegmentIndex = 0
​​​​​​​​​​​​​​​​segmentedControl.addTarget(self, action: #selector(MapViewController.mapTypeChanged(_:)), forControlEvents: .ValueChanged)
​​​​​​​​​​​​​​​​segmentedControl.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(​​​​​​​​​​​​​​​​segmentedControl)
let topConstraint = ​​​​​​​​​​​​​​​​segmentedControl.topAnchor.constraintEqualToAnchor(topLayoutGuide.bottomAnchor, constant: 8)
let margins = view.layoutMarginsGuide
let leadingConstraint = ​​​​​​​​​​​​​​​​segmentedControl.leadingAnchor.constraintEqualToAnchor(margins.leadingAnchor)
let trailingConstraint = ​​​​​​​​​​​​​​​​segmentedControl.trailingAnchor.constraintEqualToAnchor(margins.trailingAnchor)
topConstraint.active = true
leadingConstraint.active = true
trailingConstraint.active = true
}
override func viewDidLoad() {
super.viewDidLoad()
self.locationManager.requestWhenInUseAuthorization()
mapView.delegate = self
mapView.showsUserLocation = true
print("Is User Location Visible: \(mapView.userLocation.location?.coordinate.latitude)")
if CLLocationManager.locationServicesEnabled() {
locationManager.delegate = self
print("Authorization Status = \(CLLocationManager.authorizationStatus() == .AuthorizedWhenInUse)")
locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
locationManager.startUpdatingLocation()
locationManager.delegate = self
}
else{
print("location services disabled")
}
}
func mapTypeChanged(segControl: UISegmentedControl) {
switch segControl.selectedSegmentIndex {
case 0:
mapView.mapType = .Standard
case 1:
mapView.mapType = .Hybrid
case 2:
mapView.mapType = .Satellite
case 3:
zoomOnLocation()
default:
break
}
}
//Zoom to last known location
func zoomOnLocation() {
print("locations = \(self.mapView.userLocation.coordinate.longitude) ")
var location:CLLocationCoordinate2D = CLLocationCoordinate2DMake(self.mapView.userLocation.coordinate.latitude, self.mapView.userLocation.coordinate.longitude)
var region:MKCoordinateRegion = MKCoordinateRegionMake(location, MKCoordinateSpanMake(0.5, 0.5))
print("zooming")
mapView.setRegion(region, animated: true)
}
//Delegate if Location has Changed
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]){
var locValue:CLLocationCoordinate2D = manager.location!.coordinate
print("locations = \(locValue.latitude) \(locValue.longitude)")
}
//Delegate if Authorization Status has Changed
func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus){
locationManager.startUpdatingLocation()
}
func mapView(mapView: MKMapView!, didUpdateUserLocation userLocation: MKUserLocation!){
let coord = userLocation.coordinate
print("delegate: coord = \(coord.longitude)")
}
func mapViewDidFinishLoadingMap(mapView: MKMapView!){
print("finished loading mapview")
self.mapView.showsUserLocation = true
print("Is User Location Visible: \(self.mapView.userLocationVisible)")
}
func mapView(mapView: MKMapView!, mapViewWillStartLocatingUser userLocation: MKUserLocation!){
let coord = userLocation.coordinate
print("delegate: coord = \(coord.longitude)")
}
}

How to get Location user with CLLocationManager in swift?

I have this code on my view controller but this not working:
import UIKit
import CoreLocation
class ViewController: UIViewController, CLLocationManagerDelegate {
var location: CLLocationManager!
override func viewDidLoad() {
super.viewDidLoad()
location=CLLocationManager()
location.delegate = self
location.desiredAccuracy=kCLLocationAccuracyBest
location.startUpdatingLocation()
}
func locationManager(location:CLLocationManager, didUpdateLocations locations:AnyObject[]) {
println("locations = \(locations)")
label1.text = "success"
}
I have the permissions how I read in other post. but I don't obtain never, no println..
Thanks!!
first add this two line in plist file
1) NSLocationWhenInUseUsageDescription
2) NSLocationAlwaysUsageDescription
Then this is class working complete implement this
import UIKit
import CoreLocation
#UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, CLLocationManagerDelegate {
var window: UIWindow?
var locationManager: CLLocationManager!
var seenError : Bool = false
var locationFixAchieved : Bool = false
var locationStatus : NSString = "Not Started"
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: NSDictionary?) -> Bool {
initLocationManager();
return true
}
// Location Manager helper stuff
func initLocationManager() {
seenError = false
locationFixAchieved = false
locationManager = CLLocationManager()
locationManager.delegate = self
locationManager.locationServicesEnabled
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestAlwaysAuthorization()
}
// Location Manager Delegate stuff
func locationManager(manager: CLLocationManager!, didFailWithError error: NSError!) {
locationManager.stopUpdatingLocation()
if (error) {
if (seenError == false) {
seenError = true
print(error)
}
}
}
func locationManager(manager: CLLocationManager!, didUpdateLocations locations: AnyObject[]!) {
if (locationFixAchieved == false) {
locationFixAchieved = true
var locationArray = locations as NSArray
var locationObj = locationArray.lastObject as CLLocation
var coord = locationObj.coordinate
println(coord.latitude)
println(coord.longitude)
}
}
func locationManager(manager: CLLocationManager!,
didChangeAuthorizationStatus status: CLAuthorizationStatus) {
var shouldIAllow = false
switch status {
case CLAuthorizationStatus.Restricted:
locationStatus = "Restricted Access to location"
case CLAuthorizationStatus.Denied:
locationStatus = "User denied access to location"
case CLAuthorizationStatus.NotDetermined:
locationStatus = "Status not determined"
default:
locationStatus = "Allowed to location Access"
shouldIAllow = true
}
NSNotificationCenter.defaultCenter().postNotificationName("LabelHasbeenUpdated", object: nil)
if (shouldIAllow == true) {
NSLog("Location to Allowed")
// Start location services
locationManager.startUpdatingLocation()
} else {
NSLog("Denied access: \(locationStatus)")
}
}
}
Following are the simple steps for getting user location in Swift 3
1) First add this line in plist file with description
NSLocationWhenInUseUsageDescription
2) Add CoreLocation.framework in your project(Under section Build Phases-> Link Binary With Library)
3) In AppDelegate class
import CoreLocation
4) Create locationManager Object as follows
var locationManager:CLLocationManager!
5) Write following code in didFinishLaunchingWithOptions
locationManager = CLLocationManager()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.distanceFilter = 200
locationManager.requestWhenInUseAuthorization()
locationManager.startUpdatingLocation()
6) Confirm CLLocationManagerDelegate delegate like as follows
class AppDelegate: UIResponder, UIApplicationDelegate, CLLocationManagerDelegate
7) Write CLLocationManagerDelegate delegate method for getting user location
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
print("location error is = \(error.localizedDescription)")
}
func locationManager(_ manager: CLLocationManager,
didUpdateLocations locations: [CLLocation]) {
let locValue:CLLocationCoordinate2D = (manager.location?.coordinate)!
print("Current Locations = \(locValue.latitude) \(locValue.longitude)")
}
Since you're declaring location as an explicitly unwrapped optional (CLLocationManager!) it requires an initializer, either in an init method as suggested by jhurray, or just inline, as:
var location: CLLocationManager! = nil
Note that you've got other possible problems as well, including that iOS 8 has new requirements for querying the user for permission to use CoreLocation. See this question for more information.
This is the same code as above but cleaned up to work with Swift as of the date of this posting. This worked for me.
Kudos to the original poster.
(note, stick this into whatever class you will use to handle your location stuff.)
var lastLocation = CLLocation()
var locationAuthorizationStatus:CLAuthorizationStatus!
var window: UIWindow?
var locationManager: CLLocationManager!
var seenError : Bool = false
var locationFixAchieved : Bool = false
var locationStatus : NSString = "Not Started"
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
self.initLocationManager()
}
// Location Manager helper stuff
func initLocationManager() {
seenError = false
locationFixAchieved = false
locationManager = CLLocationManager()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestAlwaysAuthorization()
}
// Location Manager Delegate stuff
func locationManager(manager: CLLocationManager!, didFailWithError error: NSError!) {
locationManager.stopUpdatingLocation()
if ((error) != nil) {
if (seenError == false) {
seenError = true
print(error)
}
}
}
func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
if (locationFixAchieved == false) {
locationFixAchieved = true
var locationArray = locations as NSArray
var locationObj = locationArray.lastObject as CLLocation
var coord = locationObj.coordinate
println(coord.latitude)
println(coord.longitude)
}
}
func locationManager(manager: CLLocationManager!, didChangeAuthorizationStatus status: CLAuthorizationStatus) {
var shouldIAllow = false
switch status {
case CLAuthorizationStatus.Restricted:
locationStatus = "Restricted Access to location"
case CLAuthorizationStatus.Denied:
locationStatus = "User denied access to location"
case CLAuthorizationStatus.NotDetermined:
locationStatus = "Status not determined"
default:
locationStatus = "Allowed to location Access"
shouldIAllow = true
}
NSNotificationCenter.defaultCenter().postNotificationName("LabelHasbeenUpdated", object: nil)
if (shouldIAllow == true) {
NSLog("Location to Allowed")
// Start location services
locationManager.startUpdatingLocation()
} else {
NSLog("Denied access: \(locationStatus)")
}
}
Do following stuff in viewcontroller [Using swift] -
class ViewController:
UIViewController,MKMapViewDelegate,CLLocationManagerDelegate {
var locationManager: CLLocationManager?
var usersCurrentLocation:CLLocationCoordinate2D?
override func viewDidLoad() {
super.viewDidLoad()
self.locationManager = CLLocationManager()
if CLLocationManager.authorizationStatus() == .NotDetermined{
locationManager?.requestAlwaysAuthorization()
}
locationManager?.desiredAccuracy = kCLLocationAccuracyBest
locationManager?.distanceFilter = 200
locationManager?.delegate = self
startUpdatingLocation()
usersCurrentLocation = CLLocationCoordinate2DMake(LATTITUDE, LONGITUDE)
let span = MKCoordinateSpanMake(0.005, 0.005)
let region = MKCoordinateRegionMake(usersCurrentLocation!, span)
mapview.setRegion(region, animated: true)
mapview.delegate = self
mapview.showsUserLocation = true
}
//MARK: CLLocationManagerDelegate methods
func startUpdatingLocation() {
self.locationManager?.startUpdatingLocation()
}
func stopUpdatingLocation() {
self.locationManager?.stopUpdatingLocation()
}
// MARK: MKMapViewDelegate
func mapView(mapView: MKMapView, didUpdateUserLocation userLocation: MKUserLocation){
mapview.centerCoordinate = userLocation.location!.coordinate
mapview.showsUserLocation = true
regionWithGeofencing()
}
You need to have init functions.
Override init(coder:) and init(nibName: bundle:) and add any custom init you want.
Because you have said that location is not optional, you must initialize it before your super init calls in ALL of your init functions.
func init() {
...
location = CLLocationManager()
// either set delegate and other stuff here or in viewDidLoad
super.init(nibName:nil, bundle:nil)
// other initialization below
}
It should be written as
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {

Resources