IOS Swift: User Location Request

I am new to iOS Swift and writing iOS Swift code and using UIWebView to load my web page.

And my webpage will ask the user to enable the user’s location .

I would like to do a similar behavior in the iOS Swift code (a pop-up dialog box and say something like "TestApp would like to access your location. Do you agree?")

I run the simulator and I was unable to use the CLLocationManager

Below is my Swift code

import UIKit import CoreLocation class ViewController: UIViewController, CLLocationManagerDelegate { @IBOutlet weak var customWebView: UIWebView! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. if let url = NSURL(string: "http://ctrlq.org/maps/where/") { let request = NSURLRequest(URL: url) customWebView.loadRequest(request) let locationManager = CLLocationManager() locationManager.delegate = self locationManager.desiredAccuracy = kCLLocationAccuracyBest locationManager.requestAlwaysAuthorization() locationManager.startUpdatingLocation() } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } 

Does anyone know how to request a location?

Thanks in advance.

Eric

+6
source share
6 answers

The correct way to request and update the location of the user (s) is via CLLocationManagerDelegate .

As long as your view controller inherits CLLocationManagerDelegate , it does not seem to perform the necessary delegate functions. As @Rob already mentioned, you should declare locationManager as a class property, and not as a local variable.

This delegate function allows you to implement logic if / when the user changes the authorization status:

 func locationManager(manager: CLLocationManager!, didChangeAuthorizationStatus status: CLAuthorizationStatus) { if status == .AuthorizedWhenInUse { // authorized location status when app is in use; update current location locationManager.startUpdatingLocation() // implement additional logic if needed... } // implement logic for other status values if needed... } 

This delegate function allows you to implement logic if / when changing a user's location:

 func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) { if let location = locations.first as? CLLocation { // implement logic upon location change and stop updating location until it is subsequently updated locationManager.stopUpdatingLocation() } } 

In addition, locationServicesEnabled() determines whether the user has location services enabled.

+6
source

A few thoughts:

  • You defined your CLLocationManager as a local variable that will be released when it falls out of scope.

    Make this a class property.

  • If you really need requestAlwaysAuthorization , be sure to set NSLocationAlwaysUsageDescription to plist, as stated in the documentation.

    (And if you do not always need authorization, but in order with authorization "in use", call requestWhenInUseAuthorization and set the value to NSLocationWhenInUseUsageDescription .)

+5
source

You show a call to do something like this in didFinishLaunchingWithOptions

 let status = CLLocationManager.authorizationStatus() if status == .NotDetermined || status == .Denied || status == .AuthorizedWhenInUse { // present an alert indicating location authorization required // and offer to take the user to Settings for the app via // UIApplication -openUrl: and UIApplicationOpenSettingsURLString dispatch_async(dispatch_get_main_queue(), { let alert = UIAlertController(title: "Error!", message: "GPS access is restricted. In order to use tracking, please enable GPS in the Settigs app under Privacy, Location Services.", preferredStyle: UIAlertControllerStyle.Alert) alert.addAction(UIAlertAction(title: "Go to Settings now", style: UIAlertActionStyle.Default, handler: { (alert: UIAlertAction!) in print("") UIApplication.sharedApplication().openURL(NSURL(string:UIApplicationOpenSettingsURLString)!) })) // self.presentViewController(alert, animated: true, completion: nil) self.window?.rootViewController?.presentViewController(alert, animated: true, completion: nil) }) locationManager.requestAlwaysAuthorization() locationManager.requestWhenInUseAuthorization() } 
+5
source

You need to add the NSLocationWhenInUseUsageDescription key to your info.plist file and to the value that you write what you want to show the user in a pop-up dialog box. You need to test it on a real device, because Simulator only accepts custom locations. Choose Simulator β†’ Debug β†’ Location β†’ Custom Location ...

+1
source
 import UIKit import CoreLocation class ViewController: UIViewController, CLLocationManagerDelegate { let locationManager = CLLocationManager() @IBOutlet weak var webview: UIWebView! override func viewDidLoad() { super.viewDidLoad() self.locationManager.delegate = self self.locationManager.desiredAccuracy = kCLLocationAccuracyBest self.locationManager.requestWhenInUseAuthorization() self.locationManager.startUpdatingLocation() let url = NSURL (string: "http://www.your-url.com"); let requestObj = NSURLRequest(URL: url!); webview.loadRequest(requestObj); } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { CLGeocoder().reverseGeocodeLocation(manager.location!, completionHandler: {(placemarks, error)->Void in if (error != nil) { print("Error: " + error!.localizedDescription) return } if placemarks!.count > 0 { let pm = placemarks![0] as CLPlacemark self.displayLocationInfo(pm) } else { print("Error with the data.") } }) } func displayLocationInfo(placemark: CLPlacemark) { self.locationManager.stopUpdatingLocation() print(placemark.locality) print(placemark.postalCode) print(placemark.administrativeArea) print(placemark.country) } func locationManager(manager: CLLocationManager, didFailWithError error: NSError) { print("Error: " + error.localizedDescription) } } 
+1
source

try it

 import UIKit import CoreLocation class ViewController: UIViewController, CLLocationManagerDelegate { let locationManager = CLLocationManager() @IBOutlet weak var webview: UIWebView! override func viewDidLoad() { super.viewDidLoad() self.locationManager.delegate = self self.locationManager.desiredAccuracy = kCLLocationAccuracyBest self.locationManager.requestWhenInUseAuthorization() self.locationManager.startUpdatingLocation() let url = NSURL (string: "http://www.your-url.com"); let requestObj = NSURLRequest(URL: url!); webview.loadRequest(requestObj); } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { CLGeocoder().reverseGeocodeLocation(manager.location!, completionHandler: {(placemarks, error)->Void in if (error != nil) { print("Error: " + error!.localizedDescription) return } if placemarks!.count > 0 { let pm = placemarks![0] as CLPlacemark self.displayLocationInfo(pm) } else { print("Error with the data.") } }) } func displayLocationInfo(placemark: CLPlacemark) { self.locationManager.stopUpdatingLocation() print(placemark.locality) print(placemark.postalCode) print(placemark.administrativeArea) print(placemark.country) } func locationManager(manager: CLLocationManager, didFailWithError error: NSError) { print("Error: " + error.localizedDescription) } } 
-1
source

Source: https://habr.com/ru/post/981901/


All Articles