How can I get the current location from user in iOS?
如何从iOS用户获取当前位置?
8 个解决方案
#1
328
The answer of RedBlueThing worked quite well for me. Here is some sample code of how I did it.
RedBlueThing的回答对我来说很管用。这是一些我如何做的示例代码。
Header
#import <UIKit/UIKit.h>
#import <CoreLocation/CoreLocation.h>
@interface yourController : UIViewController <CLLocationManagerDelegate> {
CLLocationManager *locationManager;
}
@end
MainFile
In the init method
在init方法中
locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
locationManager.distanceFilter = kCLDistanceFilterNone;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
[locationManager startUpdatingLocation];
Callback function
回调函数
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
NSLog(@"OldLocation %f %f", oldLocation.coordinate.latitude, oldLocation.coordinate.longitude);
NSLog(@"NewLocation %f %f", newLocation.coordinate.latitude, newLocation.coordinate.longitude);
}
iOS 6
In iOS 6 the delegate function was deprecated. The new delegate is
在ios6中,委托函数被废弃了。新的委托
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
Therefore to get the new position use
因此得到新的位置使用
[locations lastObject]
iOS 8
In iOS 8 the permission should be explicitly asked before starting to update location
在ios8中,应该在开始更新位置之前显式地询问权限
locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
locationManager.distanceFilter = kCLDistanceFilterNone;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0)
[self.locationManager requestWhenInUseAuthorization];
[locationManager startUpdatingLocation];
You also have to add a string for the NSLocationAlwaysUsageDescription
or NSLocationWhenInUseUsageDescription
keys to the app's Info.plist. Otherwise calls to startUpdatingLocation
will be ignored and your delegate will not receive any callback.
当inuseusagedescription键进入应用程序的Info.plist时,您还必须为NSLocationAlwaysUsageDescription或nslocationadd一个字符串。否则,对startUpdatingLocation的调用将被忽略,您的委托将不会收到任何回调。
And at the end when you are done reading location call stopUpdating location at suitable place.
最后,当你完成读取位置时调用停止更新位置在合适的位置。
[locationManager stopUpdatingLocation];
#2
76
In iOS 6, the
在iOS 6,
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
is deprecated.
弃用。
Use following code instead
使用以下代码而不是
- (void)locationManager:(CLLocationManager *)manager
didUpdateLocations:(NSArray *)locations {
CLLocation *location = [locations lastObject];
NSLog(@"lat%f - lon%f", location.coordinate.latitude, location.coordinate.longitude);
}
For iOS 6~8, the above method is still necessary, but you have to handle authorization.
对于iOS 6~8,仍然需要使用上述方法,但必须处理授权。
_locationManager = [CLLocationManager new];
_locationManager.delegate = self;
_locationManager.distanceFilter = kCLDistanceFilterNone;
_locationManager.desiredAccuracy = kCLLocationAccuracyBest;
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0 &&
[CLLocationManager authorizationStatus] != kCLAuthorizationStatusAuthorizedWhenInUse
//[CLLocationManager authorizationStatus] != kCLAuthorizationStatusAuthorizedAlways
) {
// Will open an confirm dialog to get user's approval
[_locationManager requestWhenInUseAuthorization];
//[_locationManager requestAlwaysAuthorization];
} else {
[_locationManager startUpdatingLocation]; //Will update location immediately
}
This is the delegate method which handle user's authorization
这是处理用户授权的委托方法
#pragma mark - CLLocationManagerDelegate
- (void)locationManager:(CLLocationManager*)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status
{
switch (status) {
case kCLAuthorizationStatusNotDetermined: {
NSLog(@"User still thinking..");
} break;
case kCLAuthorizationStatusDenied: {
NSLog(@"User hates you");
} break;
case kCLAuthorizationStatusAuthorizedWhenInUse:
case kCLAuthorizationStatusAuthorizedAlways: {
[_locationManager startUpdatingLocation]; //Will update location immediately
} break;
default:
break;
}
}
#3
60
You use the CoreLocation framework to access location information about your user. You will need to instantiate a CLLocationManager object and call the asynchronous startUpdatingLocation message. You will get callbacks with the user's location via the CLLocationManagerDelegate that you supply.
您可以使用CoreLocation框架来访问用户的位置信息。您需要实例化CLLocationManager对象并调用异步startUpdatingLocation消息。您将通过您提供的CLLocationManagerDelegate获得用户位置的回调。
#4
29
Try this Simple Steps....
NOTE: Please check device location latitude & logitude if you are using simulator means. By defaults its none only.
注意:如果您使用的是模拟器方式,请检查设备的位置、纬度和逻辑。它的默认值是零。
Step 1: Import CoreLocation
framework in .h File
步骤1:在.h文件中导入CoreLocation框架
#import <CoreLocation/CoreLocation.h>
Step 2: Add delegate CLLocationManagerDelegate
步骤2:添加delegate CLLocationManagerDelegate
@interface yourViewController : UIViewController<CLLocationManagerDelegate>
{
CLLocationManager *locationManager;
CLLocation *currentLocation;
}
Step 3: Add this code in class file
步骤3:在类文件中添加此代码
- (void)viewDidLoad
{
[super viewDidLoad];
[self CurrentLocationIdentifier]; // call this method
}
Step 4: Method to detect current location
步骤4:检测当前位置的方法
//------------ Current Location Address-----
-(void)CurrentLocationIdentifier
{
//---- For getting current gps location
locationManager = [CLLocationManager new];
locationManager.delegate = self;
locationManager.distanceFilter = kCLDistanceFilterNone;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
[locationManager startUpdatingLocation];
//------
}
Step 5: Get location using this method
步骤5:使用此方法获取位置
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
currentLocation = [locations objectAtIndex:0];
[locationManager stopUpdatingLocation];
CLGeocoder *geocoder = [[CLGeocoder alloc] init] ;
[geocoder reverseGeocodeLocation:currentLocation completionHandler:^(NSArray *placemarks, NSError *error)
{
if (!(error))
{
CLPlacemark *placemark = [placemarks objectAtIndex:0];
NSLog(@"\nCurrent Location Detected\n");
NSLog(@"placemark %@",placemark);
NSString *locatedAt = [[placemark.addressDictionary valueForKey:@"FormattedAddressLines"] componentsJoinedByString:@", "];
NSString *Address = [[NSString alloc]initWithString:locatedAt];
NSString *Area = [[NSString alloc]initWithString:placemark.locality];
NSString *Country = [[NSString alloc]initWithString:placemark.country];
NSString *CountryArea = [NSString stringWithFormat:@"%@, %@", Area,Country];
NSLog(@"%@",CountryArea);
}
else
{
NSLog(@"Geocode failed with error %@", error);
NSLog(@"\nCurrent Location Not Detected\n");
//return;
CountryArea = NULL;
}
/*---- For more results
placemark.region);
placemark.country);
placemark.locality);
placemark.name);
placemark.ocean);
placemark.postalCode);
placemark.subLocality);
placemark.location);
------*/
}];
}
#5
14
In Swift (for iOS 8+).
Info.plist
Info.plist
First things first. You need to add your descriptive string in the info.plist file for the keys NSLocationWhenInUseUsageDescription
or NSLocationAlwaysUsageDescription
depending on what kind of service you are requesting
先做重要的事。您需要在信息中添加描述性字符串。plist文件用于键nslocationwhen inuseagedescription或NSLocationAlwaysUsageDescription,这取决于您请求的服务类型
Code
代码
import Foundation
import CoreLocation
class LocationManager: NSObject, CLLocationManagerDelegate {
let manager: CLLocationManager
var locationManagerClosures: [((userLocation: CLLocation) -> ())] = []
override init() {
self.manager = CLLocationManager()
super.init()
self.manager.delegate = self
}
//This is the main method for getting the users location and will pass back the usersLocation when it is available
func getlocationForUser(userLocationClosure: ((userLocation: CLLocation) -> ())) {
self.locationManagerClosures.append(userLocationClosure)
//First need to check if the apple device has location services availabel. (i.e. Some iTouch's don't have this enabled)
if CLLocationManager.locationServicesEnabled() {
//Then check whether the user has granted you permission to get his location
if CLLocationManager.authorizationStatus() == .NotDetermined {
//Request permission
//Note: you can also ask for .requestWhenInUseAuthorization
manager.requestWhenInUseAuthorization()
} else if CLLocationManager.authorizationStatus() == .Restricted || CLLocationManager.authorizationStatus() == .Denied {
//... Sorry for you. You can huff and puff but you are not getting any location
} else if CLLocationManager.authorizationStatus() == .AuthorizedWhenInUse {
// This will trigger the locationManager:didUpdateLocation delegate method to get called when the next available location of the user is available
manager.startUpdatingLocation()
}
}
}
//MARK: CLLocationManager Delegate methods
@objc func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus) {
if status == .AuthorizedAlways || status == .AuthorizedWhenInUse {
manager.startUpdatingLocation()
}
}
func locationManager(manager: CLLocationManager, didUpdateToLocation newLocation: CLLocation, fromLocation oldLocation: CLLocation) {
//Because multiple methods might have called getlocationForUser: method there might me multiple methods that need the users location.
//These userLocation closures will have been stored in the locationManagerClosures array so now that we have the users location we can pass the users location into all of them and then reset the array.
let tempClosures = self.locationManagerClosures
for closure in tempClosures {
closure(userLocation: newLocation)
}
self.locationManagerClosures = []
}
}
Usage
使用
self.locationManager = LocationManager()
self.locationManager.getlocationForUser { (userLocation: CLLocation) -> () in
print(userLocation)
}
#6
12
The Xcode Documentation has a wealth of knowledge and sample apps - check the Location Awareness Programming Guide.
Xcode文档包含丰富的知识和示例应用程序——请参阅位置感知编程指南。
The LocateMe sample project illustrates the effects of modifying the CLLocationManager's different accuracy settings
LocateMe示例项目演示了修改CLLocationManager不同精度设置的效果
#7
1
You can use this service I wrote to handle everything for you.
你可以用我写的这个服务为你处理一切。
This service will request the permissions and handle dealing with the CLLocationManager so you don't have to.
该服务将请求权限并处理与CLLocationManager的关系,这样您就不必这么做了。
Use like this:
使用这样的:
LocationService.getCurrentLocationOnSuccess({ (latitude, longitude) -> () in
//Do something with Latitude and Longitude
}, onFailure: { (error) -> () in
//See what went wrong
print(error)
})
#8
1
iOS 11.x Swift 4.0 Info.plist needs these two properties
iOS 11。4.0 x迅速的信息。plist需要这两个属性。
<key>NSLocationAlwaysAndWhenInUseUsageDescription</key>
<string>We're watching you</string>
<key>NSLocationWhenInUseUsageDescription</key>
<string>Watch Out</string>
And this code ... making sure of course your a CLLocationManagerDelegate
和这段代码……确保您的CLLocationManagerDelegate
let locationManager = CLLocationManager()
// MARK location Manager delegate code + more
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
switch status {
case .notDetermined:
print("User still thinking")
case .denied:
print("User hates you")
case .authorizedWhenInUse:
locationManager.stopUpdatingLocation()
case .authorizedAlways:
locationManager.startUpdatingLocation()
case .restricted:
print("User dislikes you")
}
And of course this code too which you can put in viewDidLoad().
当然,这段代码也可以放到viewDidLoad()中。
locationManager.delegate = self
locationManager.requestAlwaysAuthorization()
locationManager.distanceFilter = kCLDistanceFilterNone
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestLocation()
And these two for the requestLocation to get you going, aka save you having to get out of your seat :)
这两张是让你出发的请求地址,也就是让你不必离开座位
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
print(error)
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
print(locations)
}
#1
328
The answer of RedBlueThing worked quite well for me. Here is some sample code of how I did it.
RedBlueThing的回答对我来说很管用。这是一些我如何做的示例代码。
Header
#import <UIKit/UIKit.h>
#import <CoreLocation/CoreLocation.h>
@interface yourController : UIViewController <CLLocationManagerDelegate> {
CLLocationManager *locationManager;
}
@end
MainFile
In the init method
在init方法中
locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
locationManager.distanceFilter = kCLDistanceFilterNone;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
[locationManager startUpdatingLocation];
Callback function
回调函数
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
NSLog(@"OldLocation %f %f", oldLocation.coordinate.latitude, oldLocation.coordinate.longitude);
NSLog(@"NewLocation %f %f", newLocation.coordinate.latitude, newLocation.coordinate.longitude);
}
iOS 6
In iOS 6 the delegate function was deprecated. The new delegate is
在ios6中,委托函数被废弃了。新的委托
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
Therefore to get the new position use
因此得到新的位置使用
[locations lastObject]
iOS 8
In iOS 8 the permission should be explicitly asked before starting to update location
在ios8中,应该在开始更新位置之前显式地询问权限
locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
locationManager.distanceFilter = kCLDistanceFilterNone;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0)
[self.locationManager requestWhenInUseAuthorization];
[locationManager startUpdatingLocation];
You also have to add a string for the NSLocationAlwaysUsageDescription
or NSLocationWhenInUseUsageDescription
keys to the app's Info.plist. Otherwise calls to startUpdatingLocation
will be ignored and your delegate will not receive any callback.
当inuseusagedescription键进入应用程序的Info.plist时,您还必须为NSLocationAlwaysUsageDescription或nslocationadd一个字符串。否则,对startUpdatingLocation的调用将被忽略,您的委托将不会收到任何回调。
And at the end when you are done reading location call stopUpdating location at suitable place.
最后,当你完成读取位置时调用停止更新位置在合适的位置。
[locationManager stopUpdatingLocation];
#2
76
In iOS 6, the
在iOS 6,
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
is deprecated.
弃用。
Use following code instead
使用以下代码而不是
- (void)locationManager:(CLLocationManager *)manager
didUpdateLocations:(NSArray *)locations {
CLLocation *location = [locations lastObject];
NSLog(@"lat%f - lon%f", location.coordinate.latitude, location.coordinate.longitude);
}
For iOS 6~8, the above method is still necessary, but you have to handle authorization.
对于iOS 6~8,仍然需要使用上述方法,但必须处理授权。
_locationManager = [CLLocationManager new];
_locationManager.delegate = self;
_locationManager.distanceFilter = kCLDistanceFilterNone;
_locationManager.desiredAccuracy = kCLLocationAccuracyBest;
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0 &&
[CLLocationManager authorizationStatus] != kCLAuthorizationStatusAuthorizedWhenInUse
//[CLLocationManager authorizationStatus] != kCLAuthorizationStatusAuthorizedAlways
) {
// Will open an confirm dialog to get user's approval
[_locationManager requestWhenInUseAuthorization];
//[_locationManager requestAlwaysAuthorization];
} else {
[_locationManager startUpdatingLocation]; //Will update location immediately
}
This is the delegate method which handle user's authorization
这是处理用户授权的委托方法
#pragma mark - CLLocationManagerDelegate
- (void)locationManager:(CLLocationManager*)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status
{
switch (status) {
case kCLAuthorizationStatusNotDetermined: {
NSLog(@"User still thinking..");
} break;
case kCLAuthorizationStatusDenied: {
NSLog(@"User hates you");
} break;
case kCLAuthorizationStatusAuthorizedWhenInUse:
case kCLAuthorizationStatusAuthorizedAlways: {
[_locationManager startUpdatingLocation]; //Will update location immediately
} break;
default:
break;
}
}
#3
60
You use the CoreLocation framework to access location information about your user. You will need to instantiate a CLLocationManager object and call the asynchronous startUpdatingLocation message. You will get callbacks with the user's location via the CLLocationManagerDelegate that you supply.
您可以使用CoreLocation框架来访问用户的位置信息。您需要实例化CLLocationManager对象并调用异步startUpdatingLocation消息。您将通过您提供的CLLocationManagerDelegate获得用户位置的回调。
#4
29
Try this Simple Steps....
NOTE: Please check device location latitude & logitude if you are using simulator means. By defaults its none only.
注意:如果您使用的是模拟器方式,请检查设备的位置、纬度和逻辑。它的默认值是零。
Step 1: Import CoreLocation
framework in .h File
步骤1:在.h文件中导入CoreLocation框架
#import <CoreLocation/CoreLocation.h>
Step 2: Add delegate CLLocationManagerDelegate
步骤2:添加delegate CLLocationManagerDelegate
@interface yourViewController : UIViewController<CLLocationManagerDelegate>
{
CLLocationManager *locationManager;
CLLocation *currentLocation;
}
Step 3: Add this code in class file
步骤3:在类文件中添加此代码
- (void)viewDidLoad
{
[super viewDidLoad];
[self CurrentLocationIdentifier]; // call this method
}
Step 4: Method to detect current location
步骤4:检测当前位置的方法
//------------ Current Location Address-----
-(void)CurrentLocationIdentifier
{
//---- For getting current gps location
locationManager = [CLLocationManager new];
locationManager.delegate = self;
locationManager.distanceFilter = kCLDistanceFilterNone;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
[locationManager startUpdatingLocation];
//------
}
Step 5: Get location using this method
步骤5:使用此方法获取位置
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
currentLocation = [locations objectAtIndex:0];
[locationManager stopUpdatingLocation];
CLGeocoder *geocoder = [[CLGeocoder alloc] init] ;
[geocoder reverseGeocodeLocation:currentLocation completionHandler:^(NSArray *placemarks, NSError *error)
{
if (!(error))
{
CLPlacemark *placemark = [placemarks objectAtIndex:0];
NSLog(@"\nCurrent Location Detected\n");
NSLog(@"placemark %@",placemark);
NSString *locatedAt = [[placemark.addressDictionary valueForKey:@"FormattedAddressLines"] componentsJoinedByString:@", "];
NSString *Address = [[NSString alloc]initWithString:locatedAt];
NSString *Area = [[NSString alloc]initWithString:placemark.locality];
NSString *Country = [[NSString alloc]initWithString:placemark.country];
NSString *CountryArea = [NSString stringWithFormat:@"%@, %@", Area,Country];
NSLog(@"%@",CountryArea);
}
else
{
NSLog(@"Geocode failed with error %@", error);
NSLog(@"\nCurrent Location Not Detected\n");
//return;
CountryArea = NULL;
}
/*---- For more results
placemark.region);
placemark.country);
placemark.locality);
placemark.name);
placemark.ocean);
placemark.postalCode);
placemark.subLocality);
placemark.location);
------*/
}];
}
#5
14
In Swift (for iOS 8+).
Info.plist
Info.plist
First things first. You need to add your descriptive string in the info.plist file for the keys NSLocationWhenInUseUsageDescription
or NSLocationAlwaysUsageDescription
depending on what kind of service you are requesting
先做重要的事。您需要在信息中添加描述性字符串。plist文件用于键nslocationwhen inuseagedescription或NSLocationAlwaysUsageDescription,这取决于您请求的服务类型
Code
代码
import Foundation
import CoreLocation
class LocationManager: NSObject, CLLocationManagerDelegate {
let manager: CLLocationManager
var locationManagerClosures: [((userLocation: CLLocation) -> ())] = []
override init() {
self.manager = CLLocationManager()
super.init()
self.manager.delegate = self
}
//This is the main method for getting the users location and will pass back the usersLocation when it is available
func getlocationForUser(userLocationClosure: ((userLocation: CLLocation) -> ())) {
self.locationManagerClosures.append(userLocationClosure)
//First need to check if the apple device has location services availabel. (i.e. Some iTouch's don't have this enabled)
if CLLocationManager.locationServicesEnabled() {
//Then check whether the user has granted you permission to get his location
if CLLocationManager.authorizationStatus() == .NotDetermined {
//Request permission
//Note: you can also ask for .requestWhenInUseAuthorization
manager.requestWhenInUseAuthorization()
} else if CLLocationManager.authorizationStatus() == .Restricted || CLLocationManager.authorizationStatus() == .Denied {
//... Sorry for you. You can huff and puff but you are not getting any location
} else if CLLocationManager.authorizationStatus() == .AuthorizedWhenInUse {
// This will trigger the locationManager:didUpdateLocation delegate method to get called when the next available location of the user is available
manager.startUpdatingLocation()
}
}
}
//MARK: CLLocationManager Delegate methods
@objc func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus) {
if status == .AuthorizedAlways || status == .AuthorizedWhenInUse {
manager.startUpdatingLocation()
}
}
func locationManager(manager: CLLocationManager, didUpdateToLocation newLocation: CLLocation, fromLocation oldLocation: CLLocation) {
//Because multiple methods might have called getlocationForUser: method there might me multiple methods that need the users location.
//These userLocation closures will have been stored in the locationManagerClosures array so now that we have the users location we can pass the users location into all of them and then reset the array.
let tempClosures = self.locationManagerClosures
for closure in tempClosures {
closure(userLocation: newLocation)
}
self.locationManagerClosures = []
}
}
Usage
使用
self.locationManager = LocationManager()
self.locationManager.getlocationForUser { (userLocation: CLLocation) -> () in
print(userLocation)
}
#6
12
The Xcode Documentation has a wealth of knowledge and sample apps - check the Location Awareness Programming Guide.
Xcode文档包含丰富的知识和示例应用程序——请参阅位置感知编程指南。
The LocateMe sample project illustrates the effects of modifying the CLLocationManager's different accuracy settings
LocateMe示例项目演示了修改CLLocationManager不同精度设置的效果
#7
1
You can use this service I wrote to handle everything for you.
你可以用我写的这个服务为你处理一切。
This service will request the permissions and handle dealing with the CLLocationManager so you don't have to.
该服务将请求权限并处理与CLLocationManager的关系,这样您就不必这么做了。
Use like this:
使用这样的:
LocationService.getCurrentLocationOnSuccess({ (latitude, longitude) -> () in
//Do something with Latitude and Longitude
}, onFailure: { (error) -> () in
//See what went wrong
print(error)
})
#8
1
iOS 11.x Swift 4.0 Info.plist needs these two properties
iOS 11。4.0 x迅速的信息。plist需要这两个属性。
<key>NSLocationAlwaysAndWhenInUseUsageDescription</key>
<string>We're watching you</string>
<key>NSLocationWhenInUseUsageDescription</key>
<string>Watch Out</string>
And this code ... making sure of course your a CLLocationManagerDelegate
和这段代码……确保您的CLLocationManagerDelegate
let locationManager = CLLocationManager()
// MARK location Manager delegate code + more
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
switch status {
case .notDetermined:
print("User still thinking")
case .denied:
print("User hates you")
case .authorizedWhenInUse:
locationManager.stopUpdatingLocation()
case .authorizedAlways:
locationManager.startUpdatingLocation()
case .restricted:
print("User dislikes you")
}
And of course this code too which you can put in viewDidLoad().
当然,这段代码也可以放到viewDidLoad()中。
locationManager.delegate = self
locationManager.requestAlwaysAuthorization()
locationManager.distanceFilter = kCLDistanceFilterNone
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestLocation()
And these two for the requestLocation to get you going, aka save you having to get out of your seat :)
这两张是让你出发的请求地址,也就是让你不必离开座位
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
print(error)
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
print(locations)
}