Publishers of technology books, eBooks, and videos for creative people

Home > Articles > Apple > Operating Systems

This chapter is from the book

The Core Location Manager

As the first step in working with location data, we’ll focus on Core Location. Remember, Core Location is primarily a data-oriented framework. This means we’ll be dealing with coordinates, text strings, and number values instead of visual location information like maps. Later in the Map Kit section, we’ll discuss how to use some of the data sources we learn about with Core Location in combination with Map Kit, and how to visually represent location information on a map.

I’ve mentioned the Core Location Manager (CLLocationManager) a few times. The CLLocationManager is responsible for controlling the flow and frequency of location updates provided by location hardware. Simply put, the location manager generates location objects (CLLocation objects) and passes them to its delegate whenever a certain set of criteria is met. These criteria are determined by how you configure and start your location manager.

The CLLocationManager is typically used to generate location data while working with one of the following services.

  • Standard Location Service
  • Significant Location Change Monitoring
  • Heading Monitoring
  • Region Monitoring

Standard Location Service

The standard location service is one of the most common uses of the location manager. Used to determine a user’s current location as needed for nearby searches or check-in locations, the standard location service can be configured with a desired accuracy and distance filter (which is the threshold used to determine when a new location should be generated). When a device moves beyond the configured distance filter, the standard location service triggers a new location and calls the necessary delegate methods. After creating the location manager and configuring the desired properties, call startUpdatingLocation to begin location services. The following code block demonstrates how to set up a new location manager using the standard location service:

 1   //Create a new location manager
 2   locationManager = [[CLLocationManager alloc] init];
 3
 4   // Set Location Manager delegate
 5   [locationManager setDelegate:self];
 6
 7   // Set location accuracy levels
 8   [locationManager setDesiredAccuracy:kCLLocationAccuracyKilometer];
 9
10   // Update again when a user moves distance in meters
11   [locationManager setDistanceFilter:500];
12
13   // Configure permission dialog
14   [locationManager setPurpose:@"My Custom Purpose Message..."];
15
16   // Start updating location
17   [locationManager startUpdatingLocation];

In this code block, line 2 allocates a new CLLocationManager and saves it as an instance variable named locationManager. In line 5 we set the location manager delegate as self, which means this class must observe the CLLocationManager-Delegate protocol (covered in the section below, Responding to New Information from the Core Location Manager). Next, in line 8 we set the desired accuracy of our location manager to 1 kilometer, and in line 11 we set the distance filter of our location manager to 500 meters.

While the distance filter can be almost any value, I personally have found that setting your distance filter to half the distance of your desired accuracy typically generates a fairly accurate sample of locations as needed by the location accuracy.

In line 14 we set the custom purpose message. Remember, this message will be shown in the location permission dialog as seen in Figure 4.3 and should be used to describe why your app needs access to a user’s location—especially when it’s not readily apparent. Finally, in line 17 we start updates on the location manager by calling startUpdatingLocation.

Significant Location Change Monitoring

The location manager of a significant location change service sends new locations to the delegate whenever it detects the device has significantly changed position. The location manager provides a starting location as soon as this service is started and future locations are only calculated and sent to the delegate when the device detects new Wi-Fi hotspots or cellular towers. While slightly similar to the standard location service in functionality, this method is much more aggressive in power management and is highly efficient. While the standard service continuously monitors a user’s location to determine when the distance filter threshold is crossed, the significant location change disables location services between new location events (because location events are determined when new connections are located by the cellular and Wi-Fi antennae). As an added bonus, unlike the standard location service, the significant change monitoring service will wake up an app that’s suspended or terminated and allow the app to execute any necessary background processes.

The code needed to set up a significant location change monitoring is much simpler, essentially because the significant location change service is largely handled by the core operating system. Remember, the significant location change monitoring service automatically generates new locations when the radio antennae detect new connection sources (cellular or Wi-Fi). That means the significant location change service will ignore the accuracy and distance filter properties of the location manager (the accuracy will always be the best available by the sources used). The following code block demonstrates how to set up a location manager that monitors significant location changes:

 1   //Create a new location manager
 2   locationManager = [[CLLocationManager alloc] init];
 3
 4   // Set Location Manager delegate
 5   [locationManager setDelegate:self];
 6
 7   // Configure permission dialog
 8   [locationManager setPurpose:@"My Custom Purpose Message..."];
 9
10   // Start updating location
11   [locationManager startMonitoringSignificantLocationChanges];

Very similar to the previous code block, starting the significant location change service simply involves creating a new location manager (line 2), setting the delegate (line 5), configuring an optional custom purpose message (line 8), and then calling the method, startMonitoringSignificantLocationChanges in line 11 (instead of startUpdatingLocation). Just like the standard location service, the significant location change service interacts with its delegate using the same methods, which is covered in the section that follows, Responding to New Information from the Core Location Manager.

Heading Monitoring

Heading information is a little different than the other location-based data types generated by the location manager. Unlike the previous services, the heading monitoring service only generates new heading information (direction information relative to magnetic north or true north). The heading object (CLHeading) is created using the device’s magnetometer (compass) and does not contain a reference to the latitude and longitude coordinates of the device.

Just like with other location services, not all devices are equipped with a magnetometer, especially older generation models. You should first check to see if heading services are available by calling [CLLocationManager headingAvailable], and if heading services are required for your app’s function (such as a compass app) you should add the value magnetometer to your app’s info property list.

One of the reasons heading monitoring exists as a separate service—besides separate hardware—is because doing so allows additional performance optimization. In most location-aware apps, you don’t need to know the device heading with incredible accuracy. The majority of apps are able to get by on the generic speed and heading information generated in the standard and significant location change services. In these cases, the course and speed values managed by the CLLocation object are simply extrapolated based on the previous location coordinate (distance moved, direction moved). This means if your user is standing still, the CLLocation object is likely to hold invalid heading information.

Because heading monitoring is a separate service, however, you can give your users the option of turning on additional heading information as needed. This practice is observed in the native Google Maps app on the iPhone and iPad. When a user taps the location button once, the map zeros in on their current location. If they tap the location button again, the Google Maps app enables heading monitoring to indicate the direction the device is facing.

Starting a heading monitoring service is just like starting updates on a standard location service. The process involves creating a new location manager, assigning the delegate, setting your desired accuracy and threshold filter (in degrees changed), and calling startUpdatingHeading. Because the heading is dependent on the orientation of your device (landscape versus portrait), the location manager also allows you to set the desired heading orientation. The following code block demonstrates how to set up a new heading monitoring service:

 1   if([CLLocationManager headingAvailable]){
 2
 3       // Create a new Location Manager and assign delegate
 4       headingManager = [[CLLocationManager alloc] init];
 5       [headingManager setDelegate:self];
 6
 7       //Send all updates, even minor ones
 8       [headingManager setHeadingFilter:kCLHeadingFilterNone];
 9
10       // Set heading accuracy
11       [headingManager setDesiredAccuracy:kCLLocationAccuracyBest];
12
13       // Set expected device orientation
14       [headingManager setHeadingOrientation:
                                   CLDeviceOrientationLandscapeLeft];
15
16       // Start updating headings
17       [headingManager startUpdatingHeading];
18   }
19   else
20       NSLog(@"Heading not available");

You’ll notice this code block is similar to the standard location service. The first thing we do is check to see if heading services are available by calling the CLLocationManager class method headingAvailable in line 1. Next, in lines 4 and 5 we create a new CLLocationManager object and assign the delegate to self. In line 8 we set up our desired heading filter. This value specifies the minimum heading change in degrees needed to trigger a new heading event. In line 8 we set this option to the constant, kCLHeadingFilterNone. This simply sets the filter to nothing allowing us to obtain every change detected (no matter how minor) from the magnetometer. By default, this filter value is set to 1 degree.

In line 14 we set the expected orientation of our device to landscape left. The orientation will default to portrait, and if your device allows for rotation you should detect device rotations and reassign the heading orientation when appropriate. Finally, in line 17 we start updating our heading information. This begins calling the delegate method, locationManager:didUpdateHeading: when the filter threshold condition is met.

Region Monitoring

One of the newest features available in iOS 5 is the ability to add region-based monitoring services to a location manager. Region monitoring allows you to monitor a device’s interaction with the bounds of defined areas or regions; specifically, the location manager will call didEnterRegion and didExitRegion on its assigned delegate when the bounds of monitored regions are crossed.

This new functionality allows for all sorts of app opportunities from auto-check-in services to real-time recommendations (for example, you’re walking past a good coffee shop and an app on your phone knows that you like coffee). In fact, the new Reminders app for iOS 5 uses this functionality in combination with Siri (the iPhone 4S digital assistant) to carry out requests such as “Remind me when I get home that I need to take out the trash,” or “Remind me when I leave the office that I need to call my wife and tell her I’m on my way.” In these examples, Siri simply defines a region in a core location manager for the locations home and the office and sets up a reminder to trigger when those regions detect the appropriate didExitRegion or didEnterRegion events.

The process for monitoring regions is very similar to the other services we monitored. Instead of setting up distance filters or depending on cell towers to trigger new location events, however, we define a specific circular region (or regions) based on a set of latitude and longitude coordinates and a radius in meters.

The following code block demonstrates how to monitor for a region. This example assumes that you already know the latitude and longitude coordinates of your target region. Later, we’ll cover how to generate these values using human-readable address strings, but for now, let’s just assume you’ve memorized that Apple’s main campus is located at the latitude and longitude coordinates of (37.331691, −122.030751).

 1   // Create a new location manager
 2   locationManager = [[CLLocationManager alloc] init];
 3
 4   // Set the location manager delegate
 5   [locationManager setDelegate:self];
 6
 7   // Create a new CLRegion based on the lat/long
 8   // position of Apple's main campus
 9   CLLocationCoordinate2D appleLatLong =
         CLLocationCoordinate2DMake(37.331691, -122.030751);
10   CLRegion *appleCampus = [[CLRegion alloc]
                              initCircularRegionWithCenter:appleLatLong
                                                    radius:100
                                                identifier:@"Apple"];
11
12   // Start monitoring for our CLRegion using best accuracy
13   [locationManager startMonitoringForRegion:appleCampus
                               desiredAccuracy:kCLLocationAccuracyBest];

In this example, we set up the location manager and delegate in lines 2 through 5. In line 9 we create a new CLLocationCoordinate2D using the latitude and longitude coordinates for Apple’s main campus. Next, in line 10 we allocate a new CLRegion. Notice we initialize this region as a circular region with the radius of 100 meters. This method also allows us to assign an identifier we can use to refer to the region at a later time (in the event you’re monitoring more than one region in your location manager). Finally, in line 13 we simply start the monitoring service for our CLRegion by calling startMonitoringForRegion:desiredAccuracy.

Responding to New Information from the Core Location Manager

As you’ve learned, the location manager is delegate based. This means the location manager calls methods on its assigned delegate whenever new location, heading, or region information is available. These delegates are defined in the protocol CLLocationManagerDelegate.

Table 4.3 outlines the delegate methods used in the standard location service, significant location change monitoring service, heading monitoring service, and the region monitoring service described in this chapter. By implementing these methods in the class used as the assigned delegate, you can update your UI or save relevant course information as needed by your app.

Table 4.3. Core Location Manager Delegate Protocol Methods

Method

Description

locationManager:didUpdatetoLocation:fromLocation:

Called by both the standard location service and significant location change service when new CLLocation objects are generated. Both of these services pass in the new CLLocation object (toLocation) as well as the previous location object (fromLocation)

locationManager:didFailWithError:

Called by the standard location service and the significant location change service when an error occurs. An error could be the result of conditions such as bad hardware or an interruption in service during a location call.

locationManager:didUpdateHeading:

Called by the heading monitoring service whenever a new heading is generated based on the heading filter threshold. The heading object passed to this delegate (CLHeading) contains relative directions to both true and magnetic north along with the x, y, and z components of that heading.

locationManager:didEnterRegion:

Called by the location manager when a device crosses into a monitored region.

locationManager:didExitRegion:

Called by the location manager when a device exits a monitored region.

locationManager:monitoringDidFailForRegion:withError:

Called when region monitoring fails due to an error.

locationManager:didChangeAuthorizationStatus:

Called when the location permissions for this app are changed.

Peachpit Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from Peachpit and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about Peachpit products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites; develop new products and services; conduct educational research; and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email ask@peachpit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by Adobe Press. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.peachpit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020