Can i turn on location service by the code programmatically - swift

I am new to the tvOS platform. I want to know how to get current location latitude and longitude at the application launch. I am writing this code to get the location coordinate.
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
dispatch_async(dispatch_get_main_queue()) { () -> Void in
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
self.locationManager.delegate = self
self.locationManager.requestLocation()
self.locationManager.requestWhenInUseAuthorization()
}
return true
}
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
locationValue = manager.location?.coordinate
print("=========didUpdateLocations==========Latitude>>>>>",locationValue.latitude)
print("=========didUpdateLocations==========Longitude>>>>",locationValue.longitude)
}
func locationManager(manager: CLLocationManager, didFailWithError error: NSError) {
print("localizedDescription===================",error.localizedDescription)
}
This code provide the coordinate after the view controller loads. While my requirement is that I want to get coordinate before loading the view controller. Can i enable location service programmatically for single application?

The location service determines the location on demand and it requires time to do so. For that reason, it only offers an asynchronous interface.
So there is now way you can retrieve the location before the view controller is shown. You will need to write your app such that it can display the view controller without knowing the location and later update the screen when the location information is available.

It requires setting the app information and grants, see the discussion Here
I also found the solution and explanation for this identical question Here

Related

Custom locations on Xcode 9+ only causes didUpdateLocations to only fire once

I have an app where I leverage CoreLocation. For some reason when I use Xcode 9 or even the 9.1 beta 2, setting custom location coordinates under Debug > Locations > Custom Location in the iPhone simulator doesn't work as expected.
When I apply the custom coordinates, didUpdateLocations is only called once, or three times, then the location services turn off, and the location arrow turns into an outline. I know most of you guys will say that I shouldn't be testing location services on the simulator, but I do not have a choice, as I do not have access to a device at the moment.
I have provided some simple code bellow for accessing the users location and update it continuously. If you could, please test this out on your iPhone simulator in Xcode 9+ (ios 11+) and set a custom latitude and longitude to Debug > Locations > Custom Location and see if you get the same issue.
import UIKit
import CoreLocation
class ViewController: UIViewController, CLLocationManagerDelegate {
let locationManager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
locationManager.requestWhenInUseAuthorization()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.startUpdatingLocation()
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
if let location = locations.first {
print(location.coordinate)
}
}
}

CLLocationManager is slow getting location, Swift

Im creating this app, and it needs to get the users location - its all working properly, the thing is, that the time from accepting the use of location services, to getting the actual location takes like 5 seconds - is this normal?
I've used other apps, where it goes much faster..
Here's what my code looks like:
override func viewDidLoad() {
super.viewDidLoad()
// Ask for Location-Authorisation from the User.
self.locationManager.requestWhenInUseAuthorization()
if CLLocationManager.locationServicesEnabled() {
locationManager.delegate = self
locationManager.requestLocation()
}
mapView.delegate = self
}
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let locValue: CLLocationCoordinate2D = manager.location!.coordinate
let initialLocation = CLLocation(latitude: locValue.latitude, longitude: locValue.longitude)
self.centerMapOnLocation(initialLocation)
}
func locationManager(manager: CLLocationManager, didFailWithError error: NSError) {
print("could not get location")
}
But the time from the application gets the location to put into the centerMapOnLocation-function, seems just to be quite long. What is to be expected, when getting a users location? I'm testing on a wifi connection, so I know its not because the internet is slow, or its a bad connection...
Anyone have an idea? :)
Best regards!
Try setting the accuracy and use locationManager.startUpdatingLocation(). I do that, and get answer within a second (on the device).
From the documentation of requestLocation():
This method returns immediately. Calling it causes the location manager to obtain a location fix (which may take several seconds) and call the delegate’s locationManager(_:didUpdateLocations:) method with the result.
Source
So basically, everything is fine with your code, it's just how the framework is built.
When initializing your location manager, add startUpdatingLocation():
let manager = CLLocationManager()
manager.delegate = self
manager.requestWhenInUseAuthorization()
manager.requestLocation()
manager.startUpdatingLocation()
Without startUpdatingLocation() geo-location takes about 5 seconds, with it, the request executes nearly immediately.
If you don't want to delay the app's launch for the location manager, consider deploying two location managers (in the app delegate), tasking one with generating a location quickly and the other with generating a location accurately:
fastLoc.delegate = self
fastLoc.desiredAccuracy = kCLLocationAccuracyThreeKilometers
fastLoc.requestWhenInUseAuthorization()
fastLoc.startUpdatingLocation()
bestLoc.delegate = self
bestLoc.desiredAccuracy = kCLLocationAccuracyBest
bestLoc.requestWhenInUseAuthorization()
bestLoc.requestLocation()
The combination of 3 km accuracy with startUpdatingLocation() should return a location almost instantly, almost always before the root view controller is even ready to go. bestLoc manager is likely to return a location well after the user has launched the app but it will be very accurate.
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
switch manager {
case fastLoc:
fastLoc.stopUpdatingLocation()
deviceLocation = locations.last! // set property with fast loc
case bestLoc:
deviceLocation = locations.last! // overwrite property with best loc
default:
break
}
}

Trouble getting one-time user location in Swift

I am trying to get the user's location at the time of a button press, however I am having trouble setting up the location code. I've been looking between various answers on Stackoverflow but I can't get anything to work for me.
class MyViewController: UIViewController, CLLocationManagerDelegate {
var locationManager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters
locationManager.requestWhenInUseAuthorization()
locationManager.startUpdatingLocation()
}
func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus) {
if status == .AuthorizedAlways || status == .AuthorizedWhenInUse {
let latitude = self.locationManager.location?.coordinate.latitude
let longitude = self.locationManager.location?.coordinate.longitude
print("coordinates:")
print(latitude)
print(longitude)
}
}
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let locationValue : CLLocationCoordinate2D = manager.location!.coordinate
print("locations = \(locationValue.latitude) \(locationValue.longitude)")
}
However I just get nils from the prints in didChangeAuthorizationStatus and nothing ever prints from didUpdateLocations. Im also really confused about where to put startUpdatingLocation(). Some answers place it directly in viewDidLoad as I have here, others place it in didChangeAuthorizationStatus, and I saw another place it inside an if CLLocationManager.locationServicesEnabled() in didLoad. What is the correct way to do this? And also what have I done wrong that I'm not getting any values printing? I'm running on the emulator, have location turned on and allowed permissions in the pop-up, and have the emulator set to a lat/long custom location, and I have added the values in pList.
edit: even tried copy/pasting the code from this to get user's location only once but it returns (kCLErrorDomain error 0.). I added a 'requestWhenInUseAuthorization()` to their code but it still fails.
get nils from the prints in didChangeAuthorizationStatus
Because we don't have any locations yet. That's the wrong place to ask for that information. All that happened is that we are now authorized.
nothing ever prints from didUpdateLocations
Because you're running on the simulator, perhaps. Try running on a device.
And, if your goal is just to get the location and stop, don't use startUpdatingLocation; call requestLocation. That's what it's for.

Using Core Location to get coordinates and calcule who is 100 meters round wing

Currently in my app I'm fetching the user coordinates. I need to keep this coordinates always updated so I placed the location code in app delegate in didFinishLaunchingWithOptions. The code is:
let location = CLLocationManager()
class AppDelegate: UIResponder, UIApplicationDelegate, CLLocationManagerDelegate {
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
location.delegate = self
location.desiredAccuracy = kCLLocationAccuracyBest
location.requestAlwaysAuthorization()
location.requestWhenInUseAuthorization()
return true
Then, in the same AppDelegate.swift I implemented the delegate method to catch every location update as following:
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
print(locations)
}
The thing is that I'm always receiving nil values.
It is important to mention that I'm running the app over the simulator but in debug menu I simulate bicycle ride or even the Apple location.
What am I missing?
Of course I edited the plist with NSLocationAlwaysUsageDescription and NSLocationWhenInUseUsageDescription
manager.startUpdatingLocation()

IOS 9 background iBeacon detection

While working with xCode 7 in swift, i can´t range beacons in background only when the app is in foreground.
My core location didRangeBeacons is that follows
func locationManager(manager: CLLocationManager, didRangeBeacons beacons: [CLBeacon], inRegion region: CLBeaconRegion) {
let near = beacons[0]
print(near)
}
The didFinishLaunchingWithOptions is the one that follows. Location manager object is global to the class.
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
if(locationManager.respondsToSelector("requestAlwaysAuthorization")) {
locationManager.requestAlwaysAuthorization()
}
locationManager.delegate = self
locationManager.pausesLocationUpdatesAutomatically = false
locationManager.startMonitoringForRegion(region)
locationManager.startRangingBeaconsInRegion(region)
locationManager.startUpdatingLocation()
return true
}
In my .plist file i have the NSLocationAlwaysUsageDescription set and in the capabilities i have the background modes on with the location updates and uses bluetooth LE accessories checked.
Also i have the CoreLocation Framework added to the project.
Would very much appreciate the help or some URL´S that may help. Thank you.
I managed to solve that. Core location adds the allowsBackgroundLocationUpdates witch defaults to no. You can see the video (https://developer.apple.com/videos/wwdc/2015/?id=714).