I'm a beginner in iOS Swift and writing iOS Swift code and using UIWebView to load my web page.
And my web page will ask user to enable the user location.
I would like to do the similar behavior in iOS Swift code (popup an dialog and say something like "TestApp would like to access your location. Would you agree?")
I'm running on Simulator and I failed while using CLLocationManager
The following 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.
}
}
Anyone knows how to request location?
Thanks in advance.
Eric
Only once location authorization can be requested by using the CLLocationManager method requestLocation() . Implement the CLLocationManagerDelegate method locationManager(:, didUpdateLocations:) to handle the requested user location. This method will be called once after using locationManager.
Go to Settings > Privacy, then select Location Services. Select an app, then turn Precise Location on or off.
To access an actual user location data, we need to use the didUpdateLocations()method which is a part of CLLocationManagerDelegate. So add the CLLocationManagerDelegate in the class definition. Then, set delegate property of locationManager to self.
Open your phone's Settings app. Under "Personal," tap Location access. At the top of the screen, turn Access to my location on or off.
A couple of thoughts:
You've defined your CLLocationManager
as a local variable, which will get released when it falls out of scope.
Make this a property of your class.
If you really need requestAlwaysAuthorization
, don't forget to set the NSLocationAlwaysUsageDescription
in the plist as outlined in the documentation.
(And if you don't need always authorization, but are ok with "in use" authorization, call requestWhenInUseAuthorization
and set NSLocationWhenInUseUsageDescription
value.)
You need to add a key NSLocationWhenInUseUsageDescription in yours info.plist file and in the value you write something that you want to show the user in the popup dialog. You need to test it on a real device cause Simulator accepts only custom locations. Select the Simulator -> Debug -> Location -> Custom Location...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With