Corelocation, what we're talking about here is one of the most commonly used things, which is to use location manger to get the user's current position.
The whole thing is very simple. As long as this:
import CoreLocation
Need to use the entire framework, then the introduction of the entire framework is necessary. Then you need to implement a protocol in your class. It is CLLocationManagerDelegate, and the relevant methods in the protocol are implemented in the code. Drink like this:
class ViewController: UIViewController, CLLocationManagerDelegate
// MARK: CoreLocationManagerDelegate
func locationManager (manager: CLLocationManager !, didUpdateLocations locations: [AnyObject]!) {
println ("get location")
var location: CLLocation = locations [locations.count-1] as CLLocation
if (location.horizontalAccuracy> 0) {
self.locationManager.stopUpdatingLocation ()
println (location.coordinate)
self.textLabel.text = "latitude \ (location.coordinate.latitude) longitude \ (location.coordinate.longitude)"
}
}
func locationManager (manager: CLLocationManager !, didFailWithError error: NSError!) {
println (error)
self.textLabel.text = "get location error"
}
The function of these codes is also very simple. Get the user's longitude and latitude, and then display it in the UILabel of the interface.
This code alone does not work. Because, the policy was modified in iOS8. Look here
if self.locationManager.respondsToSelector ("requestAlwaysAuthorization") {
println ("requestAlwaysAuthorization")
self.locationManager.requestAlwaysAuthorization ()
}
This is to be compatible with the code of iOS7 and iOS8, adding a judgement. In iOS8, you need to ask the user if they agree to use the location information, otherwise the function is not available. So is it OK to add this? NO! !! !! Need to be here, here is the point. Configure an option in the plist file.
When it comes to specific configuration, there are two request methods: requestWhenInUseAuthorization () and requestAlwaysAuthorization (). One is to use positioning when the user uses it, and the other is to obtain updated positioning information in the background. The last one will trigger a system reminder at a certain time, saying that the app has been obtaining your location information in the background whether it is allowed or not. The plist configurations corresponding to these two request methods are also different, namely NSLocationAlwaysUsageDescription and NSLocationWhenInUseUsageDescription. As for the method of adding in the plist, it is to add a key-value pair in the plist, and then copy and paste the corresponding Key value of the request permission. The value can be anything, and this value will be displayed to the user in the dialog requesting permission. In short, you set it yourself.
Run your app, you will see the request prompt:
Swift uses CoreLocation, you must read this article