iOS Development Corelocaiton Framework use (location services)

Source: Internet
Author: User

Objective

In iOS development, the positioning and mapping feature is one of the more common features that you must develop based on 2 frameworks to join these 2 features.

(1) Corelocation: Used for geo-location, geo-coding, area monitoring, etc. (focus on function implementation).

(2) Mapkit: Used for map display, such as pin, route, overlay display, etc. (Focus on the interface display).

This article we will focus on the introduction of the next Corelocation framework

Brief introduction

Corelocaiton Framework is the positioning of Baidu map is also in the Apple API based on the package.

Corelocation Framework Usage Prerequisites

Import frame (can be omitted after Xcode5.0)


One. iOS8.0 Pre-positioning configuration 1. Foreground location

Direct introduction of the header File Settings agent can be

2. Background positioning

Need to check the background mode location on the basis of the foreground positioning updates

Two. Positioning configuration after iOS8.0 1. Foreground location

Request foreground location Authorization and configure key (Nslocationwheninuseusagedescription) in the Info.plist file

The parameter type is a string if the input is the content that prompts the user

2. Background positioning

The first of these solutions

Request pre-and post-location authorization and configure key (Nslocationalwaysusagedescription) in the Info.plist file

Second Solution

Need to check the background mode location on the basis of the foreground positioning updates

Import Primary header file

#import <CoreLocation/CoreLocation.h>

Corelocation Framework Pre-use notice

The prefix for all data types in the Corelocation framework is CL

Using Cllocationmanager objects in corelocation to do user positioning

Location Services

<CLLocationManagerDelegate> need to comply with this agent

Start updating user locations

-(void) startupdatinglocation;

Stop Updating user locations

-(void) stopupdatinglocation;

When the Startupdatinglocation method is called, the user's location is constantly requested and refreshed, and the following method of the proxy is invoked once the request is made to the user's location

-(void) Locationmanager: (cllocationmanager*) Managerdidupdatelocations: (nsarray*) locations;

The locations parameter contains the Cllocation object (I'll describe the Cllocation object in detail below)

For the sake of rigor, it's a good idea to determine if the current app's positioning function is available before using the location feature

Cllocationmanager has a class method to determine if the current app's positioning function is available

+ (BOOL) locationservicesenabled;

@property (assign,nonatomic) Cllocationdistancedistancefilter;

How many meters to locate each time

@property (assign,nonatomic) cllocationaccuracydesiredaccuracy;

Positioning accuracy (the more accurate it consumes)

Cllocation Object

Cllocation the geographic information used to represent a location, such as latitude and longitude, altitude, etc.

@property (readonly,nonatomic) cllocationcoordinate2dcoordinate; Warp latitude

Note:

typedef struct

{

cllocationdegreeslatitude;//Latitude

cllocationdegreeslongitude;//Longitude

} cllocationcoordinate2d

@property (readonly,nonatomic) cllocationdistancealtitude; Elevation

@property (readonly,nonatomic) cllocationdirectioncourse; Course, course (value range is 0.0°~359.9°,0.0° for true North direction)

@property (readonly,nonatomic) cllocationspeedspeed; Movement speed (unit m/s)

Call-(Cllocationdistance) Distancefromlocation: (constcllocation*) The location method can calculate the distance between 2 locations

Instance Code

#import "ViewController.h" #[email Protected] Viewcontroller ()//Position Manager

@property (Nonatomic,strong) Cllocationmanager *locmanager;

@end

@implementation Viewcontroller

Lazy Loading

-(Cllocationmanager *) locmanager{

if (!_locmanager) {

Create a location Manager

_locmanager = [[Cllocationmanager alloc] init];

Agent

_locmanager.delegate = self;

How many meters are positioned to move every

_locmanager.distancefilter = 3000;

Higher accuracy, more power consumption, longer positioning time

_locmanager.desiredaccuracy = kcllocationaccuracythreekilometers;

ios8.0+ positioning adaptation

if ([[Uidevice currentdevice].systemversion Floatvalue] >= 8.0) {

Front-end location authorization (by default, the location can not be obtained in the background, check the background mode of the site update, but there will be a blue bar)

[_locmanager requestwheninuseauthorization];

This method also works when the current authorization status is the foreground authorization

[_locmanager requestalwaysauthorization];

}

Allow background access to user location (iOS9.0)

if ([[Uidevice currentdevice].systemversion Floatvalue] >= 9.0)

{

Be sure to check the background mode location updates

_locmanager.allowsbackgroundlocationupdates = YES;

}

}

return _locmanager;

}

-(void) Viewdidload {

[Super Viewdidload];

Start updating user locations

[Self.locmanager startupdatinglocation];

}

#pragma mark-cllocationmanagerdelegate

/*

Called after update to location

@param Manager Location Manager

@param locations Position Array

*/

-(void) Locationmanager: (Cllocationmanager *) Manager didupdatelocations: (Nsarray *) Locations

{

NSLog (@ "Positioning to%@", locations);

Here locations stores the constant updated location coordinate values, takes the last value to the latest position, and if you do not want it to update the location continuously,

Cllocation *currentlocation = [locations Lastobject];

Get all current city names

Clgeocoder *geocoder = [[Clgeocoder alloc] init];

Reverse geo-compilation of address information based on latitude and longitude

[Geocoder reversegeocodelocation:currentlocation completionhandler:^ (Nsarray *array, Nserror *error)

{

if (Array.count > 0)

{

Clplacemark *placemark = [array objectatindex:0];

NSLog (@%@,placemark.name);//Specific location

Get the city

NSString *city = placemark.locality;

if (!city) {

The city information of the four municipalities can not be obtained by locality, but only by obtaining the province's method (if it is empty, it is known as the municipality)

City = Placemark.administrativearea;

}

Clplacemark *firstplacemark=[array Firstobject];

Warp latitude

Cllocationdegrees Latitude=firstplacemark.location.coordinate.latitude;

Cllocationdegrees Longitude=firstplacemark.location.coordinate.longitude;

Print Location City

NSLog (@ "Positioning complete:%@", city);

Print current latitude and longitude

NSLog (@ "%f,%f", latitude,longitude);

The system will keep updating the data until you choose to stop the update, because we just need to get the latitude and longitude, so get it and stop the update.

[Manager Stopupdatinglocation];

}else if (Error = = Nil && [array count] = = 0)

{

NSLog (@ "No results were returned.");

}else if (Error! = nil)

{

NSLog (@ "An error occurred =%@", error);

}

}];

Stop updating when you get a city location

[Manager Stopupdatinglocation];

}

/*

Called when the authorization state has changed

@param Manager Location Manager

@param status

*/

-(void) Locationmanager: (Cllocationmanager *) Manager didchangeauthorizationstatus: (clauthorizationstatus) status

{

Switch (status) {

The user has not yet decided

Case kclauthorizationstatusnotdetermined:

{

NSLog (@ "User has not decided");

Break

}

Ask restricted

Case kclauthorizationstatusrestricted:

{

NSLog (@ "Access restricted");

Break

}

When the location is closed and when the app is authorized as never, the call

Case Kclauthorizationstatusdenied:

{

Whether the positioning is available (whether to support positioning or whether the location is enabled)

if ([Cllocationmanager locationservicesenabled])

{

NSLog (@ "position is turned on, but rejected");

}else

{

NSLog (@ "location off, not available");

}

NSLog (@ "rejected");

Break

}

Get front and rear location authorization

Case Kclauthorizationstatusauthorizedalways:

Case kclauthorizationstatusauthorized://invalid, not recommended

{

NSLog (@ "Get front and rear location authorization");

Break

}

Get a front-office location authorization

Case Kclauthorizationstatusauthorizedwheninuse:

{

NSLog (@ "Get front desk location authorization");

Break

}

Default

Break

}

}

Failed to locate

-(void) Locationmanager: (Cllocationmanager *) Manager didfailwitherror: (nserror *) error

{

NSLog (@ "Location failed%@", error);

}

@end

iOS Development Corelocaiton Framework use (location services)

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.