Finding Altitude in Swift - ios

I've been having trouble finding a way to get the altitude of the device. Could someone give me a pointer or put together a short script that gets the altitude of the device and prints it? Only in swift. Thanks!

Import CoreLocation
import CoreLocation
Create a locationManger variable
var locationManager:CLLocationManager = CLLocationManager()
Initialize and start updating location
override func viewDidLoad() {
super.viewDidLoad()
self.locationManager = CLLocationManager()
locationManager.requestWhenInUseAuthorization()
self.locationManager.delegate = self
self.locationManager.distanceFilter = kCLDistanceFilterNone
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
self.locationManager.startUpdatingLocation()
}
func locationManager(manager: CLLocationManager!, didUpdateToLocation newLocation: CLLocation!, fromLocation oldLocation: CLLocation!) {
var alt = newLocation.altitude
println("\(alt)")
manager.stopUpdatingLocation()
}

Related

Location manager stops working after reboot swift ios

I am trying to use location manager in my application. I set the code as I saw in many posts and examples and everything is working fine, and I get the location manager to show the current location as set in the simulator. I then change the location in the simulator and my app gets the new location.
I then reboot my machine, and restart my application, but the location manager stops working. I tried to change the code from using addObserver() to using didUpdateLocations, and sometimes I manage to restart the location manager to work. But when I reboot the machine it stops working again. I tried resetting the simulator and authorizing again the app to get location updates, but with no success. In all cases my app prints that it has authorization to get location update but it does not work. I also tried cleaning the app and rebuilding it, but with no success.
Below are the 2 versions of the code I use.
CODE with addObserver
class TViewController: UIViewController, GMSMapViewDelegate, CLLocationManagerDelegate {
var myLocation: CLLocation?
var locationManager = CLLocationManager()
#IBOutlet weak var mapView: GMSMapView!
override func viewDidLoad() {
super.viewDidLoad()
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
locationManager.distanceFilter = kCLDistanceFilterNone;
locationManager.delegate = self
locationManager.requestWhenInUseAuthorization()
mapView!.settings.myLocationButton = true
}
// get updates of myLocation
override func observeValueForKeyPath(keyPath: String?,
ofObject object: AnyObject?,
change: [String : AnyObject]?,
context: UnsafeMutablePointer<Void>)
{
myLocation = change![NSKeyValueChangeNewKey] as? CLLocation
print("in newlocation = \(myLocation)")
}
func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus) {
if status == CLAuthorizationStatus.AuthorizedWhenInUse {
print("in myLocation is authorized")
locationManager.startUpdatingLocation()
mapView!.myLocationEnabled = true
mapView!.addObserver(self, forKeyPath: "myLocation", options: NSKeyValueObservingOptions.New, context: nil)
}
}
}
CODE with didUpdateLocations
extension TViewController: CLLocationManagerDelegate {
func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus) {
if status == .AuthorizedWhenInUse {
print("in myLocation extension is authorized")
isLocationAvailable = true
locationManager.startUpdatingLocation()
mapView.myLocationEnabled = true
mapView.settings.myLocationButton = true
}
}
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
myLocation = locations.first
print("in newlocation extension = \(myLocation)")
mapView.camera = GMSCameraPosition(target: myLocation!.coordinate, zoom: 15, bearing: 0, viewingAngle: 0)
}
class TViewController: UIViewController, GMSMapViewDelegate {
var myLocation: CLLocation?
var locationManager = CLLocationManager()
#IBOutlet weak var mapView: GMSMapView!
override func viewDidLoad() {
super.viewDidLoad()
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
locationManager.distanceFilter = kCLDistanceFilterNone;
locationManager.delegate = self
locationManager.requestWhenInUseAuthorization()
mapView!.settings.myLocationButton = true
}

Getting My Location with google maps swift

I've got this code:
override func viewDidLoad() {
super.viewDidLoad()
locationManager.delegate = self
locationManager.requestWhenInUseAuthorization()
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.startUpdatingLocation()
}
and this code:
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let userLocation = locations.last
print(userLocation)
let camera = GMSCameraPosition.cameraWithLatitude(userLocation!.coordinate.latitude,
longitude: userLocation!.coordinate.longitude, zoom: 12.5)
self.mapView.camera = camera
self.mapView.myLocationEnabled = true
// self.mapView.settings.myLocationButton = true
locationManager.stopUpdatingLocation()
}
This was working earlier but now it seems like locationManager isn't even being called as the print statement isn't returning any information at all. There are no errors in the code and I can't seem to figure out why the function isn't being called. Can anyone spot anything obvious that I'm missing?
Thank you
I just implemented this and I'm going to say you what I've done
First, you create a locationManager variable
let locationManager: CLLocationManager = CLLocationManager()
You have to request permission in the viewDidLoad()
viewMap.delegate = self
locationManager.delegate = self
locationManager.requestWhenInUseAuthorization()
Then, I created an extension and I implemented the delegate
extension MyView: CLLocationManagerDelegate {
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
//here you configure the locationManager
locationManager.startUpdatingLocation()
viewMap.isMyLocationEnabled = true
viewMap.settings.myLocationButton = true
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
}
}
I hope this help you, here works properly.

Swift - Trying to get current location [duplicate]

This question already has answers here:
Get User's Current Location / Coordinates
(16 answers)
Closed 6 years ago.
I am trying to get the long and lat of my users locations, I have done the following:
imported Core Location
import CoreLocation
Add Core Location Delegate
class ViewController: UIViewController, CLLocationManagerDelegate, AVCaptureMetadataOutputObjectsDelegate, DTDeviceDelegate {
defined this variable:
var locationManager: CLLocationManager!
and then added this method:
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let userLocation:CLLocation = locations[0]
let long = userLocation.coordinate.longitude;
let lat = userLocation.coordinate.latitude;
print(long, lat)
//Do What ever you want with it
}
but the location does not get printed, my method does not even get it.
I add the items to use Core Location to my plist and the app ask me to use the location services when I first run it. But now location is getting printed....what am I doing wrong?
Maybe you forgot to set value for the delegate
In your viewDidLoad() add this:
if CLLocationManager.locationServicesEnabled() {
locationManager.requestAlwaysAuthorization()
locationManager.requestWhenInUseAuthorization()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.startUpdatingLocation()
mapView.showsUserLocation = true
}
Use this Code,
declare locationManager
var locationManager = CLLocationManager()
Set the Delegate in viewDidLoad, shown below code,
override func viewDidLoad() {
super.viewDidLoad()
locationManager.delegate = self
if CLLocationManager.authorizationStatus() == .NotDetermined {
self. locationManager.requestWhenInUseAuthorization()
}
locationManager.distanceFilter = kCLDistanceFilterNone
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.startUpdatingLocation()
}
Add this in viewdidload,
if (CLLocationManager.locationServicesEnabled())
{
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
if ((UIDevice.currentDevice().systemVersion as NSString).floatValue >= 8)
{
locationManager.requestWhenInUseAuthorization()
}
locationManager.startUpdatingLocation()
}
else
{
#if debug
println("Location services are not enabled");
#endif
}
Then add this two delegate method to get location,
func locationManager(manager: CLLocationManager!, didFailWithError error: NSError!)
{
locationManager.stopUpdatingLocation()
if ((error) != nil)
{
print(error)
}
}
func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!)
{
var locationArray = locations as NSArray
var locationObj = locationArray.lastObject as! CLLocation
var coord = locationObj.coordinate
print(coord.latitude)
print(coord.longitude)
}
This way you will get your current location.
You neeed to initialize the locationManageger and enable the location flag in xcode also, it appaear bottom of the xcode
self.locationManager = CLLocationManager()
self.locationManager.delegate = self
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
if #available(iOS 8.0, *) {
if Bundle.main.infoDictionary?["NSLocationAlwaysUsageDescription"] != nil {
self.locationManager.requestAlwaysAuthorization()
}
else {
self.locationManager.requestWhenInUseAuthorization()
}
}
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
self.locationManager.startUpdatingLocation()
You can add this code to your viewDidLoad() method:
locationManager = CLLocationManager()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestWhenInUseAuthorization()
locationManager.startUpdatingLocation()
This will call the locationManagers didUpdate delegate-methods if location services are available for your app

Value of distance between 2 CLLocation points does not appear on label text

I am trying to calculate the distance from the starting position I am (when i first start the app) to the current position and present it on a label (meters.text) but nothing appears on it..
Here is my code:
import UIKit
import CoreLocation
class CorrectViewController: UIViewController,CLLocationManagerDelegate {
#IBOutlet weak var meters: UILabel!
var wr: Int = 0
var distance = CLLocationDistance()
let locationManager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
self.locationManager.delegate = self
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
self.locationManager.requestWhenInUseAuthorization() //starts when i use the app
self.locationManager.distanceFilter = kCLHeadingFilterNone
self.locationManager.startUpdatingLocation()
}
//locatioManager delegate method
func locationManager(manager: CLLocationManager, didUpdateToLocation newLocation: CLLocation, fromLocation oldLocation: CLLocation) {
let currentLocation: CLLocation = newLocation
let startLocation: CLLocation = oldLocation
distance = startLocation.distanceFromLocation(currentLocation)
let tripString = NSString(format: "%.2f", distance)
meters.text = ("\(tripString)")
}
func locationManager(manager: CLLocationManager, didFailWithError error: NSError) {
meters.text = ("error!")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
Any help is appreciated:)
It appears that the location update delegate method is inside the viewDidLoad function and hence defines a local function rather than implementing the delegate method.
Move the following method out of the viewDidLoad scope:
locationManager(manager: CLLocationManager, didUpdateToLocation newLocation: CLLocation, fromLocation oldLocation: CLLocation)
In addition you are not requesting permission to use the users location. Make sure to do that and add the necessary string to your info plist.
Also: oldLocation will always be the previous location (not your initial one).
Alright, after a lot of searching and "trial and error" I found the solution here.
Instead of using the method didUpdateToLocation the method didUpdateLocations should be used. Moreover, it is really important to put NSLocationAlwaysUsageDescription or NSLocationWhenInUseUsageDescription keys in the .plist file (value may be an additional message that will be presented in location alert). These keys are required in iOS 8.

Getting user location in swift

This is my code:
import Foundation
import CoreLocation
class ViewController: UIViewController, CLLocationManagerDelegate {
let locationManager = CLLocationManager()
#IBOutlet weak var locationLabel: UILabel!
var coord: CLLocationCoordinate2D?
override func viewDidLoad() {
super.viewDidLoad()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestWhenInUseAuthorization()
if CLLocationManager.authorizationStatus() == CLAuthorizationStatus.Authorized {
locationManager.startUpdatingLocation()
println(coord!.longitude)
locationLabel.text = "location found"
}
func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
var locationArray = locations as NSArray
var locationObj = locationArray.lastObject as CLLocation
coord = locationObj.coordinate
}
}
}
This code does not return anything (it should print the longitude). Which seems O.K because if I move
locationManager.startUpdatingLocation()
println(coord!.longitude)
out of the if statement, Xcode throws a runtime error and says it unexpectedly found nil while unwrapping an Optional value. I do not understand why though? The systems asks me permission to use my location fine.
Thanks!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
locationManager = CLLocationManager()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestAlwaysAuthorization()
locationManager.startUpdatingLocation()
}
func locationManager(manager:CLLocationManager, didUpdateLocations locations:AnyObject[] {
println("locations = \(locations)")
gpsResult.text = "success"
}
Are you running on iOS8? Assuming so:
1.You need to initialize
self.locationManager = CLLocationManager()
2.Right after, call self.locationManager.requestAlwaysAuthorization(); (before self.locationManager.delegate = self )
3.Add these keys to Info.plist, using an external text editor (change the texts accordingly)
<key>NSLocationWhenInUseUsageDescription</key>
<string>This is needed for iOS8 and up (when in use)</string>
<key>NSLocationAlwaysUsageDescription</key>
<string>This is needed for iOS8 and up (always)</string>
4.The place where you call println(coord!.longitude) may be too early. Move it into the locationManager function.
Then it should display an alert asking for permission for using location services.

Resources