Explain the basic positioning function implementation in IOS development _ios

Source: Internet
Author: User
Tags reserved

One, simple explanation

1.CLLocationManager

Common operations and properties for Cllocationmanager

Start user positioning-(void) startupdatinglocation;

Stop user positioning-(void) stopupdatinglocation;

Note: When the Startupdatinglocation method is invoked, the user's position is constantly positioned, and the following method of the proxy is frequently invoked

Copy Code code as follows:

-(void) Locationmanager: (Cllocationmanager *) Manager didupdatelocations: (Nsarray *) locations;

Every number of meters to locate once
Copy Code code as follows:

@property (Assign, nonatomic) cllocationdistance distancefilter;

Positioning accuracy (the more accurate the more power consumption)
Copy Code code as follows:

@property (Assign, nonatomic) cllocationaccuracy desiredaccuracy;



2.CLLocation

Cllocation is used to indicate geographic information about a location, such as latitude and longitude, elevation, etc.

(1) by latitude
Copy Code code as follows:

@property (readonly, nonatomic) Cllocationcoordinate2d coordinate;

(2) Elevation
Copy Code code as follows:

@property (readonly, nonatomic) cllocationdistance altitude;

(3) Course, course (value range is 0.0°~ 359.9°,0.0° representing True north)
Copy Code code as follows:

@property (readonly, nonatomic) Cllocationdirection course;

(4) Walking speed (unit is m/s)
Copy Code code as follows:

@property (readonly, nonatomic) cllocationspeed speed;

(5) Calculate the distance between 2 positions
Copy Code code as follows:

-(Cllocationdistance) Distancefromlocation: (const cllocation *) Location method



3.cllocationcoordinate2d

Cllocationcoordinate2d is a structure used to denote latitude and longitude, defined as
Copy Code code as follows:

typedef struct {

Cllocationdegrees latitude; Latitude

Cllocationdegrees longitude; Longitude

} cllocationcoordinate2d;

Generally use the Cllocationcoordinate2dmake function to create a cllocationcoordinate2d



Second, the code example
Copy Code code as follows:

//
Yyviewcontroller.m
18-Positioning Service
//
Created by Apple on 14-8-9.
Copyright (c) 2014 Yangyong. All rights reserved.
//

#import "YYViewController.h"
#import <CoreLocation/CoreLocation.h>

Need to comply with Cllocationmanagerdelegate protocol
@interface Yyviewcontroller () <CLLocationManagerDelegate>
@property (Nonatomic,strong) Cllocationmanager *locmgr;
@end

@implementation Yyviewcontroller
#pragma mark-lazy Load
-(Cllocationmanager *) locmgr
{
if (_locmgr==nil) {
1. Create a Location manager (locate the user's location)
Self.locmgr=[[cllocationmanager Alloc]init];
2. Set up Agent
self.locmgr.delegate=self;
}
return _locmgr;
}
-(void) viewdidload
{
[Super Viewdidload];

Determine if the user Locator service is open
if ([Cllocationmanager locationservicesenabled]) {
Start locating the user's location
[Self.locmgr startupdatinglocation];
How many meters per meter (this is set to any move)
Self.locmgr.distancefilter=kcldistancefilternone;
Set positioning accuracy, the higher the general accuracy, the more power consumption (here set to the highest accuracy, applicable to navigation applications)
Self.locmgr.desiredaccuracy=kcllocationaccuracybestfornavigation;
}else
{//Cannot locate user's location
1. Remind users to check current network conditions
2. Remind the user to turn on the positioning switch
}

Test method to calculate the distance between two positions
[Self countdistance];
}

#pragma mark-cllocationmanagerdelegate
/**
* When positioned to the user's location, it is invoked (the frequency of calls is more frequent)
*/
-(void) Locationmanager: (Cllocationmanager *) Manager didupdatelocations: (Nsarray *) Locations
{
The locations array holds the Cllocation object, and a Cllocation object represents a position
Cllocation *loc = [locations Firstobject];

Dimension: Loc.coordinate.latitude
Longitude: Loc.coordinate.longitude
NSLog (@ "Latitude =%f, Longitude =%f", loc.coordinate.latitude,loc.coordinate.longitude);
NSLog (@ "%d", locations.count);

Stop the update location (if the location service does not need to be updated in real time, then stop the update of the location)
[Self.locmgr stopupdatinglocation];

}

Calculate the distance between two positions
-(void) countdistance
{
Create two location objects based on latitude and longitude
Cllocation *loc1=[[cllocation alloc]initwithlatitude:40 longitude:116];
Cllocation *loc2=[[cllocation alloc]initwithlatitude:41 longitude:116];
Calculate the distance between two positions
Cllocationdistance Distance=[loc1 DISTANCEFROMLOCATION:LOC2];
NSLog (@ "(%@) and (%@) distance =%fm", loc1,loc2,distance);
}

@end


Print View:

Code Description:

1. About Proxy methods

You need to set up a proxy that tells the user the current location through a proxy, with two proxy methods:

Locations parameters contain cllocation objects.

Where the latter is an outdated method, an array is used in the new method (the first) instead.
 
Description: This method is invoked when it navigates to the user's location, and the invocation is more frequent
 
Note: Do not use local variables (Create location manager), because the method of local variable ends it is destroyed. It is recommended that you use a global variable and create it only once (using lazy loading).
 
2. Positioning Precision

3. If you find that your location service is not open, you should remind the user to turn on the positioning Service feature.
 
4. Location service is more power consumption, if it is to do positioning service (no need to update in real time), then locate the user location, you should stop the update location.
 
 
 
Third, user privacy protection
 

1. Permission setting description
 
from iOS 6, Apple has done a lot to protect the privacy of users, the following operations must be approved by the user authorization
 
(1) to obtain the user's location
 
(2) Want to access the user's address book, calendar, camera, photo albums, etc.
&NBSP
When you want to access the user's privacy information, the system automatically pops up a dialog box to allow users to authorize

Note: Once the user chooses "Don" T Allow, This means that your application will not be able to use the positioning function after the first time, and will not be reminded to set up again after the user has chosen the initial selection.
 
So you should make judgments in your program, and if you find that your location service is not open, you should alert the user to turn on the positioning Service feature.
 
Cllocationmanager has a class method to determine whether the currently applied positioning function is available in + (BOOL) locationservicesenabled;
 
Common methods: Screenshots tell the user , how to turn on authorization
 

 
2. Developers can set nslocationusagedescription instructions for positioning in Info.plist (privacy-location Usage Description)

Description: The positioning service here is network-based. Usually the positioning service can be based on GPS, base station or network.


Iv. improvements since the iOS8
IOS 8 also offers a more user-friendly positioning service option. App's location-based services are no longer just turned off or turned on, and now the location service is enabled with three options, "Never," and "Always." At the same time, considering the energy consumption problem, if an app requires always to open the location service in the background, IOS 8 will not only ask you when the app is first opened, but will also remind you in the daily use of the pop-up window that the app has been using location-based services in the background and asks if you want to continue In IOS7 and previous versions, if you use the location service in your application, you will be asked whether the user is allowed to use the positioning service if the Startupdatinglocation method application is invoked in the program. At the same time, you can configure Privacy-location Usage description to tell the user what to use in the Info.plist, and this configuration is optional.
However, configuration items have changed in IOS8 and can be configured nslocationalwaysusagedescription or nslocationwheninuseusagedescription to tell users the purpose of using the location service, And note that this configuration is required, if not configured by default, the application will not be able to use the positioning service, open the application does not give a prompt to open the positioning service, unless the installation of the application itself to set the positioning service. Also, in your application, you need to request a requestalwaysauthorization or Locationservicesenabled method based on configuration. Because my machine has been updated to the latest iOS8.1 the following content is mainly for iOS8, the use of iOS7 friends need to make a little adjustment.

Copy Code code as follows:

//
Kcmainviewcontroller.m
Corelocation
//
Created by Kenshin Cui on 14-03-27.
Copyright (c) 2014 Kenshin Cui. All rights reserved.
//

#import "KCMainViewController.h"
#import <CoreLocation/CoreLocation.h>

@interface Kcmainviewcontroller () <cllocationmanagerdelegate>{

Cllocationmanager *_locationmanager;
}

@end

@implementation Kcmainviewcontroller

-(void) Viewdidload {
[Super Viewdidload];

Location Manager
_locationmanager=[[cllocationmanager Alloc]init];

if (![ Cllocationmanager locationservicesenabled]) {
NSLog (@) The location service may not be open at this moment, please set open! ");
Return
}

Request user Authorization If no authorization is granted
if ([Cllocationmanager authorizationstatus]==kclauthorizationstatusnotdetermined) {
[_locationmanager requestwheninuseauthorization];
}else if ([Cllocationmanager authorizationstatus]==kclauthorizationstatusauthorizedwheninuse) {
Set up agents
_locationmanager.delegate=self;
Set positioning precision
_locationmanager.desiredaccuracy=kcllocationaccuracybest;
Positioning frequency, every number of meters to locate once
Cllocationdistance distance=10.0;//10-meter positioning once
_locationmanager.distancefilter=distance;
Start trace positioning
[_locationmanager startupdatinglocation];
}
}

#pragma mark-corelocation Agent
#pragma mark traces the locator agent method, which is executed each time the position changes (as long as the location is positioned)
You can set a virtual location through the emulator, otherwise you cannot call this method in the emulator
-(void) Locationmanager: (Cllocationmanager *) Manager didupdatelocations: (Nsarray *) locations{
Cllocation *location=[locations firstobject];//Take out the first position
cllocationcoordinate2d coordinate=location.coordinate;//Position coordinates
NSLog (@ "Longitude:%f, Latitude:%f, Elevation:%f, heading:%f, walking speed:%f", Coordinate.longitude,coordinate.latitude,location.altitude, Location.course,location.speed);
If you do not need to locate in real time, use it even if you turn off the positioning service
[_locationmanager stopupdatinglocation];
}

@end


Attention:

1. Positioning frequency and positioning accuracy should not be the more accurate the better, depending on the actual situation, because the more accurate consumption of performance, the more the cost of electricity.

2. After the success of the positioning will be based on the settings frequently called-(void) Locationmanager: (Cllocationmanager *) Manager didupdatelocations: (Nsarray *) Locations method, This method returns an array of geographic objects, each with a cllocation representing geographic information (including longitude, latitude, posters, walking speed, and so on), and is returned because there are times when a location point may contain multiple locations.

3. After using the positioning service, if you do not need real-time monitoring should immediately turn off the positioning service to save resources.

4. In addition to providing a positioning function, Cllocationmanager can also invoke the Startmonitoringforregion: method to monitor the specified area.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.