Last active
February 14, 2020 02:13
-
-
Save rugbyprof/67a61003d8f95cd33f20 to your computer and use it in GitHub Desktop.
core location example swift
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import UIKit | |
import CoreLocation | |
class CurrentLocationViewController: UIViewController, CLLocationManagerDelegate { | |
let locationManager = CLLocationManager() | |
var location: CLLocation? | |
override func viewDidAppear() { | |
super.viewDidLoad() | |
let authStatus: CLAuthorizationStatus = CLLocationManager.authorizationStatus() | |
if authStatus == .Denied || authStatus == .Restricted { | |
showLocationServicesDeniedAlert() | |
return | |
} | |
if authStatus == .NotDetermined { | |
locationManager.requestWhenInUseAuthorization() | |
return | |
} | |
locationManager.delegate = self | |
locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters | |
locationManager.startUpdatingLocation() | |
} | |
func showLocationServicesDeniedAlert() { | |
let alert = UIAlertController(title: "Location Services Disabled", | |
message: "Please enable location services for this app in Settings.", | |
preferredStyle: .Alert) | |
let okAction = UIAlertAction(title: "OK", style: .Default,handler: nil) | |
alert.addAction(okAction) | |
presentViewController(alert, animated: true, completion: nil) | |
} | |
func locationManager(manager: CLLocationManager!, didFailWithError error: NSError!) { | |
println("didFailWithError \(error)") | |
} | |
func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) { | |
let newLocation = locations.last as CLLocation | |
location = newLocation | |
let lat = String(format: "%.8f", location.coordinate.latitude) | |
let lon = String(format: "%.8f", location.coordinate.longitude) | |
println("\(lat),\(lon)") | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment