[iOS] 7.4 Location Service - > 2.1.2 Location - Official Framework CoreLocation: CLLocation Manager

Keywords: iOS github Attribute Swift

This article is not the final version. If you want to pay attention to the updated or corrected content, please pay attention to the anthology. The contact details are at the end of the article. If there are any omissions or omissions, please correct them.

Relevant catalogues of this article:
====================================== belongs to the collection: [iOS] 07 Device Tool ==================
7.4 Location Service - > 1.0 Brief Introduction
7.4 Location Service - > 2.1.1 Location - Official Framework CoreLocation: Requesting User Authorization
7.4 Location Service - > 2.1.2 Location - Official Framework CoreLocation: CLLocation Manager Location Manager
7.4 Location Service - > 2.1.3.1 Location - Official Framework CoreLocation Function 1: Geographical Location
7.4 Location Service - > 2.1.3.2 Location - Official Framework CoreLocation Function 2: Geocoding and Anti-Geocoding
7.4 Location Service - > 2.1.3.3 Location - Official Framework CoreLocation Function 3: Regional Monitoring
7.4 Location Service - > 2.1.4 Location - CoreLocation Case of the Official Framework: Compass Effect
7.4 Location Service - > 2.2 Location - Location Manager Framework
7.4 Location Service - > 3.1 MapKit Function of Map Framework 1: Map Display
7.4 Location Service - > 3.2 MapKit Map Framework Function 2: Route Planning (Navigation)
7.4 Location Service - > 3.3 MapKit Map Framework Function 3: 3D View
7.4 Location Service - > 3.4 MapKit Function of Map Framework 4: Map Screenshots
7.4 Location Service - > 3.5 MapKit Map Framework Function 5: POI Retrieval
====================================== belongs to the collection: [iOS] 07 Device Tool ==================

Location directory:

The official framework CoreLocation directory:

Contents of this article:

1 Introduction

2.0 Attribute Method

CLLocation Coordinate2D: A structure used to represent latitude and longitude

On longitude and latitude:

Distance Filter: Locate every few meters

Desired Accuracy: Setting positioning accuracy

3.0 Request Location: A single location request to obtain a location information

4.0 Two Location Services

4.1 Standard Location Service

The CLLocation object is described below:

CLLocation Object Attribute Method:

Main Method: Distance FromLocation

4.2 Location Service with Significant Location Change

Code example: Write a "single location" demo based on the above knowledge

Compiler environment: Xcode 8.0
Simulator version: iOS 10
Swift version: 3.0

[OC Language]
#import "ViewController.h"
#import <CoreLocation/CoreLocation.h>

@interface ViewController () <CLLocationManagerDelegate> // agent
@property(nonatomic, strong) CLLocationManager *locationM; // Location Manager
@end

@implementation ViewController

#pragma mark - lazy loading object and partial initialization in lazy loading method
- (CLLocationManager *)locationM {
    if (!_locationM) {
        // 1. After creating a location manager (strong reference is required, otherwise it will disappear as soon as it appears), the UI control is added to the subviews array when it is created, and the scope is not released at the end of the scope.
        _locationM = [[CLLocationManager alloc] init];
        
        // 2. Setting up proxy to receive location data (other ways: block, notification)
        _locationM.delegate = self;
        
        // 3. Request user authorization - - ios8 before (configure info.plist file)
        
        //Method 1: Judging System Version
        if ([UIDevice currentDevice].systemVersion.floatValue >= 8.0){
            
            [_locationM requestAlwaysAuthorization];    //Continuous authorization
            //[_locationM requestWhenInUseAuthorization]; // Period Authorization
        }
        
        //Method 2:
        /*
         if ([locationManager respondsToSelector:@selector(requestWhenInUseAuthorization)]) {
         
         [_locationM requestAlwaysAuthorization];//Continuous authorization
         [_locationM requestWhenInUseAuthorization];//Authorization during use
         }
         */
        
        // 4. Set the filter distance of location (unit: meter) to indicate that the corresponding proxy method is called when the user's location moves x meters.
        // When the physical distance between this location and the last location > the value set below, the current location will be told to the outside world through the agent.
        _locationM.distanceFilter = 500; //Call a proxy method when the user's location changes 500 meters
        
        // 5. Setting the accuracy of positioning (in meters), (the higher the accuracy of positioning, the more power consumption, the slower the speed of positioning)
        // _ locationM.desiredAccuracy = 100; // / When the user is within 100 meters, the system will default to 100 meters as a location.
        _locationM.desiredAccuracy = kCLLocationAccuracyBest;
    }
    return _locationM;
}

- (void)viewDidLoad {
    [super viewDidLoad];
}

#pragma mark - Click on the screen to start updating the user's location
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    
    [self compareDistance]; //Compare the distance between two points
    
    // Determine whether the location service is open or not
    if ([CLLocationManager locationServicesEnabled]) {
        NSLog(@"Location services have been launched and will soon start positioning...");

#pragma mark - start positioning
        // Method 1: Standard Location Service (Location Manager)
        // Start updating location information (once this method is invoked, the user's location is constantly refreshed, and then told the outside world)
        // By default, the following code can only get the user's location information in the foreground. If you want to get the user's location information in the background, you need to check the background mode location updates.
        // Lesson learned: If you use the location manager object to implement a service in the future, you can start a service with startXX and stop a service with stopXX.
        // [self.locationM startUpdatingLocation];
        
        // Method 2: Service for monitoring significant location change (location based on base station) (location based service for significant location change)
        //  [self.locationM startMonitoringSignificantLocationChanges];
        
        // Single Location Request
        // Agent Location Failure Method Must be Implemented
        // Cannot be used in conjunction with the startUpdatingLocation method
        [self.locationM requestLocation];
    } else {
        NSLog(@"No Location Service Opened");
    }
}

#pragma mark - Compare the distance between two points (straight line distance)
- (void)compareDistance {
    // Beijing location
    CLLocation *location1 = [[CLLocation alloc] initWithLatitude:39.26 longitude:115.25];
    // Shanghai location
    CLLocation *location2 =[[CLLocation alloc] initWithLatitude:30.4 longitude:120.51];
    
    // Distance between two places (in meters)
    CGFloat distance = [location2 distanceFromLocation:location1];
    
    NSLog(@"Compare the distance between two points:%f", distance / 1000);
}

#pragma mark-proxy method: This method is called when the location manager gets the user's location
// Parameters: (manager: location manager) (locations: array of location objects)
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations{
    
    NSLog(@"position information:%@", locations);
    
    // Stop locating (proxy methods are always invoked and can be very power-intensive unless special requirements, such as navigation)
    // If you want to get the user's location information only once, then stop updating the user's location information after getting the location information.
    // Application Scenario: Get the user's City
    [manager stopUpdatingLocation];
}

-(void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error{
    NSLog(@"seek failed");
}

#pragma mark-proxy method: Called when the user's authorization status changes
-(void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status{
    
    switch (status) {
            
        case kCLAuthorizationStatusNotDetermined:{
            NSLog(@"1.Users haven't decided yet.");
            break;
        }
        case kCLAuthorizationStatusRestricted:{
            NSLog(@"2.Access restricted(Apple Reservation Options,Temporarily useless)");
            break;
        }
            // Called when location is closed and this APP is authorized as never
        case kCLAuthorizationStatusDenied:{
            // Whether positioning is available (whether positioning is supported or whether positioning is enabled)
            if([CLLocationManager locationServicesEnabled]){
                NSLog(@"3.Location service is open and needs manual authorization. It will jump to set up the interface.");
                // Here, the user should be reminded to authorize the application and jump to the "Settings" interface for authorization. After iOS 8.0, the user should jump to the "Settings" interface code.
                NSURL *settingURL = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
                
                if([[UIApplication sharedApplication] canOpenURL:settingURL]){
                    
                    //[[UI Application Shared Application] Open URL: settingURL]; //Method expiration
                    
                    [[UIApplication sharedApplication]openURL:settingURL options:nil completionHandler:^(BOOL success) {
                        NSLog(@"Has successfully jumped to the settings interface");
                    }];
                }
                else{
                    NSLog(@"Location closed, unavailable");
                }
                break;
            }
        case kCLAuthorizationStatusAuthorizedAlways:{
            NSLog(@"4.Getting Front and Background Location Authorization");
            break;
        }
        case kCLAuthorizationStatusAuthorizedWhenInUse:{
            NSLog(@"5.Obtain Front Office Location Authorization");
            break;
        }
        default:
            break;
        }
    }
}

-(void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

@end

Print results:

OC-single positioning [11287:835597] compares the distance between two points: 1093.824596
 OC - Single positioning [11287:835597] has started positioning service and will soon start positioning.
OC-Single Location [11287:835597] 3. Location service is open and requires manual authorization, i.e. jump to set the interface
 OC - Single Location [11287:835597] has successfully jumped to the Setup Interface
 OC - Single Location [11287:835597] 5. Obtain Front Office Location Authorization
 OC - Single Location [11287:835597] 4. Obtain Front and Background Location Authorization
 OC-Single Location [11287:835597] Location Information: ("<+39.783000,+116.401700>+/-5.00m (speed-1.00 mps/course-1.00)@ 2016/9/21\ U4e2d\ Ufd\ U07\ Uc6\ Uf6\\ Uf4\\ Ue0;b\ U5:19):01):
[Swift Language]
import UIKit
import CoreLocation

class ViewController: UIViewController {
    
    // MARK: - Lazy Loading
    lazy var locationM : CLLocationManager = {
        
        // 1. After creating a location manager (strong reference is required, otherwise it will disappear as soon as it appears), the UI control is added to the subviews array when it is created, and the scope is not released at the end of the scope.
        let locationM : CLLocationManager = CLLocationManager()
        
        // 2. Setting up proxy to receive location data (other ways: block, notification)
        locationM.delegate = self
        
        // 3. Request user authorization - - ios8 before (configure info.plist file)
        // Judging System Version
        if (Float(UIDevice.current.systemVersion)! >= 8.0){
            locationM.requestAlwaysAuthorization()// Front and Background Location Authorization
            // Location M. requestWhenInUseAuthorization ()// Front-end Location Authorization
        }
        
        // 4. Setting filtering distance
        // If the physical distance between the current position and the previous position is greater than the following value, the current position will be told to the outside world through the proxy.
        locationM.distanceFilter = 100   // Locate every 100 meters
        
        // 5. Setting the accuracy of positioning (the higher the positioning accuracy, the more power consumption, the slower the positioning speed)
        locationM.desiredAccuracy = kCLLocationAccuracyBest
        
        return locationM
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }
    
    // MARK: - Click on the screen to start updating user locations
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        
        // Method 1: Standard Location Service (Location Manager)
        // Start updating location information (once this method is invoked, the user's location is constantly refreshed, and then told the outside world)
        // By default, the following code can only get the user's location information in the foreground. If you want to get the user's location information in the background, you need to check the background mode location updates.
        // Lesson learned: If you use the location manager object to implement a service in the future, you can start a service with startXX and stop a service with stopXX.
        // locationM.startUpdatingLocation()
        
        // Method 2: Service for monitoring significant location change (location based on base station) (location based service for significant location change)
        // locationManager.startMonitoringSignificantLocationChanges()
        
        // Single Location Request
        // Agent Location Failure Method Must be Implemented
        // Cannot be used in conjunction with the startUpdatingLocation method
        locationM.requestLocation()
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}

// Class Extension (CLLocation Manager's proxy method)
extension ViewController: CLLocationManagerDelegate {
    
    // Proxy method: This method is called when the location manager obtains the user's location
    // Parameters: (manager: location manager) (locations: array of location objects)
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        
        print("position information:%@", locations)
        
        // Stop locating (proxy methods are always invoked and can be very power-intensive unless special requirements, such as navigation)
        // If you want to get the user's location information only once, then stop updating the user's location information after getting the location information.
        // Application Scenario: Get the user's City
        manager.stopUpdatingLocation()
    }

    func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
        print("seek failed--\(error.localizedDescription)")
    }
    
    // Proxy method: Called when the user's location authorization status changes
    func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
        
        switch status {
            
        case CLAuthorizationStatus.notDetermined:
            print("1.Users haven't decided yet.")
        case CLAuthorizationStatus.restricted:
            print("2.Access restricted(Apple Reservation Options,Temporarily useless)")
        // Called when location is closed and this APP is authorized as never
        case CLAuthorizationStatus.denied:
            // Whether positioning is available (whether positioning is supported or whether positioning is enabled)
            if (CLLocationManager.locationServicesEnabled()){
                print("3.Location service is open and needs manual authorization. It will jump to set up the interface.")
                
                // Here, the user should be reminded to authorize the application and jump to the "Settings" interface for authorization. After iOS 8.0, the user should jump to the "Settings" interface code.
                var settingURL:URL?
                
                if (Float(UIDevice.current.systemVersion)! >= 8.0){
                    settingURL = URL(string: UIApplicationOpenSettingsURLString)
                }else{
                    // Setting up app scheme
                    settingURL = URL(string: "prefs:root=LOCATION_SERVICES")
                }
                
                if (UIApplication.shared.canOpenURL(settingURL!)){
                    UIApplication.shared.openURL(settingURL!)
                    print("Has successfully jumped to the settings interface")
                }
            }else{
                print("Location closed, unavailable")
            }
        case CLAuthorizationStatus.authorizedAlways:
            print("4.Getting Front and Background Location Authorization")
        case CLAuthorizationStatus.authorizedWhenInUse:
            print("5.Obtain Front Office Location Authorization")
        }
    }
}

Print results:

3. Location service is open and requires manual authorization. It is about to jump to set up the interface.
Has successfully jumped to the settings interface
 5. Obtain Front Office Location Authorization
 4. Acquiring Front and Background Location Authorization
 Location information:%@[<+39.78583000,+116.40641700>+/-5.00m (speed-1.00 mps/course-1.00)@ 2016/9/21 China Standard Time 5:59:01]


See Github for details on this article's source code Demo
https://github.com/shorfng/iOS_7.0_Device-Tools

Author: Loto
[Platform for Publishing Works]

Brief book
Blog Garden
Gitbook (If you think the article is too long, please read the article published by this platform.)

[Code Hosting Platform]

Github

[If you have any questions, please communicate through the following ways]

(1) Response from comment area
Send mail to shorfng@126.com


Copyright of this article belongs to the author and this website. You are welcome to reproduce it, but you must keep this statement without the author's consent, and give the original link in the obvious position of the article page. Thank you for your cooperation.

If you think my article is useful to you, please feel free to reward it. Your support will encourage me to continue to create!
  • Alipay swept to reward me.

  • You can also give me a reward by wechat.

Posted by clip on Wed, 12 Dec 2018 13:57:06 -0800