iOS Core note-corelocation Framework-Basics

Source: Internet
Author: User

1, corelocation Framework Introduction:

?了解: In iOS development, you must develop based on 2 frameworks to use the map and location features. CoreLocation框架: Mainly used for geographical positioning; MapKit框架 : Mainly used for map display.

1-1. corelocation Frame function:
function function
Geo-positioning Locate the user's location, get the corresponding latitude and longitude, altitude and other location information
Area monitoring Specify an area in the app by code in advance, and when the user enters or leaves the area, it can listen to the user's location through the corresponding proxy method.
Geo-coding The detailed 位置信息 conversion to the corresponding 经纬度 , namely:位置信息 ——> 经纬度
Anti-geo-coding Convert the latitude and longitude to a detailed location, i.e.:经纬度 ——> 位置信息

?重要: Corelocation framework focuses on the implementation of the function, only the developer can obtain the corresponding data, the user is invisible, not touch; the prefix for all data types in the Corelocation framework is the start of CL.

1-2. Two hot terms:
name meaning
LBS Location Based Service, locations-based services
SoLoMo Social Local Mobile (Solomon), social, native, mobile
Social In the app, if some social elements
Localization Around lbs-based search, peripheral registration and other services
Mobile Mobile network: 3G/4G Network, relative to the wired/wireless computer network; mobile app: relative to PC-side applications
1-3. The corelocation framework uses the main steps:
Steps Specific Information
The first step Import the Corelocation framework, Xcode5.0 after this step can omit
Step Two Import the primary header file,#import <CoreLocation/CoreLocation.h>
Step Three Use the Cllocationmanager object to invoke the relevant method ( startUpdatingLocation open positioning, stopUpdatingLocation stop positioning), turn on the positioning function, to achieve the relevant location services
Fourth Step To set the Cllocationmanager objectdelegate
Fifth Step Implement the corresponding Agent method, monitor the relevant location information changes

?注意: The framework is implicitly imported into the project only if an object has been created using a class in the framework.

2. before iOS8.0---Positioning function:

1、?重要:iOS8.0 does not require authorization from the user until the location is implemented.

2、?了解:before the iOS8.0 , the version is about to be eliminated, no longer suitable, and the code that iOS8.0 after the positioning function can run directly on the device before iOS8.0 , no need to make any changes , because of the system version and the Xcode version, there is no longer a detailed description of the positioning function prior to iOS8.0 , just the approximate implementation step, detailed steps can be see after iOS8.0 for the implementation.

3、?了解:before iOS8.0 , when the application uses the background locator feature 屏幕上方是否会出现蓝色横幅未做验证 .

2-1. before iOS8.0---Front desk location: 2-1-1, Detailed Steps
Steps Details
The first step Configure in a info.plist file Privacy - Location Usage Description to illustrate the purpose of targeting
Step Two Import the Corelocation framework and the corresponding main header file
Step Three Create a Cllocationmanager object and set the proxy ( delegate )
Fourth Step Call the startUpdatingLocation method to begin updating the user's location information
Fifth Step Obtain location information in the corresponding proxy method, locationManager:didUpdateLocations: Once the proxy method starts to locate, it will be automatically called every second, the call is very frequent, very power consumption
2-1-2, Detail Supplement: 1, import corelocation frame and corresponding main header file.
1.  #import <CoreLocation/CoreLocation.h>
2, Agent method cannot locate the reason:

?重要: ①, Cllocationmanager objects are local variables, ②, do not call the corresponding method to open the positioning function, ③, simulator problems, ④, other unknown causes.

2-2. before iOS8.0---Background location: 2-1, detailed steps:
Steps Details
The first step Configure in a info.plist file Privacy - Location Usage Description to illustrate the purpose of targeting
Step Two Turn on background mode: ①,------- 选中工程 前往target capabilities Background Modes 勾选location updates ②, the info.plist key that is added directly to the file Required background modes , the key is an array, the value added in the array App registers for location updates
Step Three Import the Corelocation framework and the corresponding main header file
Fourth Step Create a Cllocationmanager object and set the proxy ( delegate )
Fifth Step Call the startUpdatingLocation method to begin updating the user's location information
Sixth step Obtain location information in the corresponding proxy method, locationManager:didUpdateLocations: Once the proxy method starts to locate, it will be automatically called every second, the call is very frequent, very power consumption
2-2, open the background mode two ways:

?重要: In fact, two ways to open the background mode, the essence is the operation of info.plist files.

  • ①, 选中工程 前往target capabilities Background Modes 勾选location updates .
  • ②, config info.plist file:
    ?了解: In fact, two ways to open the background mode, the essence is the operation of info.plist files.
2-3, the details add:

?了解: ①, need to use the previous version of Xcode7.0, the simulator should select the previous version of iOS8.0 , ②,iOS8.0 before background positioning, when the app exits to the background, the screen should appear on the blue banner (not verified, However, a large amount of food is not indicated to have a blue banner).

2-4. Frequently Asked Questions:

?注意: If not located, the corresponding proxy method does not execute; 4 solution: ①, check whether the simulator is iOS8.0 before the system version, be sure to use the iOS8.0 before the emulator, ②, check the simulator has set data; ③, Check the code for logic errors, whether there are proxy settings, whether the location management objects are local variables, ④, emulator issues, first set the emulator location to None , and then setup the data again, or reset the emulator.

2-5. Sample code:
1. #import "ViewController.h"
2. #import <CoreLocation/CoreLocation.h>
3.
[Email protected] Viewcontroller () <CLLocationManagerDelegate>
5.
6./** Location Manager */
[Email protected] (Nonatomic, Strong) Cllocationmanager *LM;
8.
[Email protected]
10.
[Email protected] Viewcontroller
12.
#pragma mark-Lazy loading
14.-(Cllocationmanager *) LM
15.{
if (!_LM) {
17.//1. Create a location Manager
_LM = [[Cllocationmanager alloc] init];
19.//1.1 agent, notification, block
_lm.delegate = self;
21st.
22.//Distance filter: Locate once per multi-metre
_lm.distancefilter = 100;
24.
25.//The higher the accuracy, the more power consumption, the longer the positioning time
_lm.desiredaccuracy = Kcllocationaccuracybest;
27.}
. return _LM;
29.}
30.
31.-(void) Touchesbegan: (Nsset *) touches withevent: (Uievent *) event
32.{
33.//2. Use Location Manager to start updating user locations
34.//The user location can only be obtained from the foreground by default.
35.//Check background mode location updates
[Self.lm startupdatinglocation];
37.}
38.
#pragma mark-cllocationmanagerdelegate
40./**
41. * Call after update to location
42. *
* @param Manager Location Manager
* @param locations Position Array
45. */
46.-(void) Locationmanager: (Cllocationmanager *) Manager didupdatelocations: (Nsarray *) Locations
47.{
NSLog (@ "positioned");
49.
50.//Get position, do some business logic operation
51.
52.//Stop updating
[Manager Stopupdatinglocation];
54.}
[Email protected]
3. iOS8.0 ~ iOS9.0---positioning function: 3-1, iOS8.0 ~ iOS9.0---Front desk location: 1, Detailed Steps
Steps Details
The first step info.plistConfigure key-value pairs in a file NSLocationWhenInUseUsageDescription and invoke the Cllocationmanager object's method to requestWhenInUseAuthorization request user authorization
Step Two Import the Corelocation framework and the corresponding main header file
Step Three Create a Cllocationmanager object and set the proxy ( delegate )
Fourth Step Call the startUpdatingLocation method to begin updating the user's location information
Fifth Step Obtain location information in the corresponding proxy method, locationManager:didUpdateLocations: Once the proxy method starts to locate, it will be automatically called every second, the call is very frequent, very power consumption, in the proxy method to perform the corresponding logical operation
2, the details add:

?重要: ①, starting from the iOS8.0 , the application of the open location function needs to proactively request the foreground location authorization, in addition to using the Cllocationmanager object to invoke the requestWhenInUseAuthorization method, you also need to info.plist configure NSLocationWhenInUseUsageDescription in the file Key (note: Do not appear in spaces), whose value is used to explain to the user the main purpose of the application using the location function (Note: value can be null), and if the key-value pair is not configured, the box will not get user authorization. ②, need to pay attention to version adaptation issues, simulator operating environment should be iOS8.0 , including iOS8.0.

3. Sample code:
1. #import "ViewController.h"
2. #import <CoreLocation/CoreLocation.h>
3.
[Email protected] Viewcontroller () <CLLocationManagerDelegate>
5./** Location Manager * *
[Email protected] (Strong, Nonatomic) Cllocationmanager *mgr;
7.
[Email protected]
9.
[Email protected] Viewcontroller
11.
12.-(void) Viewdidload {
[Super Viewdidload];
14.
15.//1. Create a Location Manager object, create an object call init method initialization, if no special operation; You can use the new method instead
Self.mgr = [Cllocationmanager new];
17.
18.//2. To request user authorization, the key value pair must be configured in the Info.plist file
//nslocationwheninuseusagedescription: Front-Office location authorization
//requestwheninuseauthorization: Front desk Authorization to obtain location information when using the app
//Nslocationalwaysusagedescription: Pre-background authorization
//Requestalwaysauthorization: Pre-background authorization, always authorized to obtain location information
if ([Self.mgr respondstoselector: @selector (requestwheninuseauthorization)]) {
[Self.mgr requestwheninuseauthorization];
25.}
26.
27.//3. Set proxy Object
Self.mgr.delegate = self;
29.
30.//4. Turn on the positioning function
[Self.mgr startupdatinglocation];
32.}
33.
#pragma mark-<CLLocationManagerDelegate>
35./**
36. The first successful acquisition of the user location will come to this proxy method, and then every second call; Very frequent calls
37.
@param manager Positioning Manager objects
@param locations User All location objects (each element in an array represents one location)
40. */
41.-(void) Locationmanager: (Cllocationmanager *) Manager didupdatelocations: (nsarray<cllocation *> *) Locations
42.{
NSLog (@ "%@", locations);
44.
45.//1. Stop positioning
[Self.mgr stopupdatinglocation];
47.}
[Email protected]
3-2. iOS8.0 ~ iOS9.0---Background location: 3-2-1, front desk authorization + open background mode:

?重要: ①, must remember to turn on the background mode, otherwise, when the application back to the background mode will not be able to locate operations, ②, when the app back to the background, 在屏幕上方会出现蓝色横幅 has alerted the user application is using the location feature.

1. Detailed Steps
Steps Details
The first step info.plistConfigure key-value pairs in a file NSLocationWhenInUseUsageDescription and invoke the Cllocationmanager object's method to requestWhenInUseAuthorization request user authorization
Step Two Turn on background mode: ①,------- 选中工程 前往target capabilities Background Modes 勾选location updates ②, the info.plist key that is added directly to the file Required background modes , the key is an array, the value added in the array App registers for location updates
Step Three Import the Corelocation framework and the corresponding main header file
Fourth Step Create a Cllocationmanager object and set the proxy ( delegate )
Fifth Step Call the startUpdatingLocation method to begin updating the user's location information
Sixth step Obtain location information in the corresponding proxy method, locationManager:didUpdateLocations: Once the proxy method starts to locate, it will be automatically called every second, the call is very frequent, very power consumption, in the proxy method to perform the corresponding logical operation
2, open the background mode two ways:

?重要: In fact, two ways to open the background mode, the essence is the operation of info.plist files.

    • ①, 选中工程 前往target capabilities Background Modes 勾选location updates .
  • ②, config info.plist file:
3. Sample code:

?重要: Consistent with the sample code of the foreground location, except that the application turns on background mode, can get the user's location information in the background, and performs the corresponding logical operation in the proxy method.

3-2-2, front and rear authorization:

?重要: ①,iOS8.0 after the application uses the background location function, the front and rear authorization level is higher than the foreground authorization level, when two kinds of authorization methods are used, there will be two time frame reminders. ②, the use of pre-and post-authorization, regardless of whether the application turned on background mode, the application back to the background can get location information. ③, use before and after the license, when the application back to the background, 在屏幕上方不会出现蓝色横幅 .

1. Detailed Steps
Steps Details
The first step info.plistConfigure key-value pairs in a file NSLocationAlwaysUsageDescription and invoke the Cllocationmanager object's method to requestAlwaysAuthorization request user authorization
Step Two Import the Corelocation framework and the corresponding main header file
Step Three Create a Cllocationmanager object and set the proxy ( delegate )
Fourth Step Call the startUpdatingLocation method to begin updating the user's location information
Fifth Step Obtain location information in the corresponding proxy method, locationManager:didUpdateLocations: Once the proxy method starts to locate, it will be automatically called every second, the call is very frequent, very power consumption, in the proxy method to perform the corresponding logical operation
2, the details add:

?重要: ①, note that in the actual application development may need version adaptation; ②, do not forget the configuration info.plist file, otherwise, the box will not appear to obtain user authorization.

4. after iOS9.0---Positioning function:

?了解:iOS9.0 uses 前台授权 + to 开启后台模式 achieve the background positioning function has changed, added new steps; You need to set the CLLocationManager properties of the object allowsBackgroundLocationUpdates , the proxy object must also implement the locationManager:didFailWithError: proxy method to achieve the error message that the listener failed to locate.

4-1. after iOS9.0---Front desk location:

?了解: With iOS8.0 ~ iOS9.0 The front-office location to achieve the same steps, no new changes; Be aware that the use of the foreground location feature requires user authorization, note: The configuration file is required, info.plist otherwise, the box will not appear to remind the user, to obtain user authorization.

4-2. after iOS9.0---Background location: 4-2-1, 前台授权+ 开启后台模式: 1, 前台授权+ 开启后台模式

?重要: On the basis of the foreground location authorization, if the background mode is checked location updates , additional properties are required, and the proxy allowsBackgroundLocationUpdates = YES object must implement the locationManager:didFailWithError: proxy method to achieve the error message of the listener location failure. Use allowsBackgroundLocationUpdates the attribute to note that a version adaptation is required, which is a iOS9.0 ~ .

2. Sample code:
1.// 5. 获取后台临时定位授权, 记得开启后台定位模式, 否则, 程序将会崩溃
2.if ([UIDevice currentDevice].systemVersion.doubleValue >= 9.0) {
3. self.mgr.allowsBackgroundLocationUpdates = YES;
4.}
3, must implement the Proxy method:
1./**
2. 定位失败调用该代理方法
3.
4. @param manager 定位管理者对象
5. @param error 错误对象
6. */
7.- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error{
8. if (error != nil) {
9. NSLog(@"%@", error);
10. }
11.}

?重要: The program will crash without implementing the Proxy method.

4-2-2, 前后台授权

?重要: Direct request front and rear positioning authorization, and iOS8.0 ~ iOS9.0 after the same; no change. Note: Only run on devices after iOS9.0 , be sure to note the version adaptation.

iOS Core note-corelocation Framework-Basics

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.