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

Home > Articles > Apple > Operating Systems

iOS 5 Core Frameworks: Core Location and Map Kit

  • Print
  • + Share This
By pulling a user’s location, you make the data in your app more relevant to your users. Shawn Welch discusses iOS 5 enhancements to location services including forward and reverse geocoding, placemarks, and regions.
This chapter is from the book

One of the obvious benefits of iOS is that it’s a mobile platform. iOS devices move throughout the world; calling upon a device’s location while utilizing Core Location and Map Kit helps you provide a better context for the data in your app. For example, if a user is in San Francisco and does a search for “Bart,” they’re probably looking for information on the Bay Area Rapid Transit system (aka the BART), whereas in other parts of the world that same search may be looking for a pop culture reference. By pulling a user’s location, you make the data in your app more relevant to your users. New to iOS 5 are enhancements to location services including forward and reverse geocoding, placemarks, and regions.

Getting Started with Core Location and Map Kit

Core Location is a set of Objective-C classes built into the Core Services layer of iOS. Core Location was designed to simplify the process of working with location by providing a set of APIs that facilitate location monitoring and various location-data conversions (such as latitude/longitude coordinates to human readable addresses and vice versa). The Core Location framework is data oriented and can be used to obtain relevant location information as needed for check-in services, user tracking, nearby searches, and more.

The Core Location Manager (CLLocationManager) manages this flow of data, and controls your app’s interaction with the physical hardware used to determine location. The location manager passes new location data that is retrieved from hardware to its delegate and then encapsulates it in a CLLocation object. This object contains a determination of the latitude and longitude coordinates of the device as well as information about the accuracy of the determination. The location manager also calculates speed and heading (based on the observed change in location), and likewise encapsulates it in the CLLocation object.

Unlike the Core Location framework, the Map Kit framework is visually oriented—it communicates location data back to a user through maps. Using Map Kit, you can seamlessly embed various map views into your app using Google Maps data as a service provider. Map Kit also has some very handy (and entirely automated) APIs designed for visually based real-time user tracking on a map.

When used in combination, Core Location and Map Kit allow you to create feature-rich, location-aware apps for all iOS devices.

How Location Is Determined

When an iOS device attempts to pinpoint its location, it relies on three data sources to make the determination. Each of these data sources provides a different level of speed (the time it takes to make the determination), performance (the amount of power used to make the determination), and accuracy (the +/− distance in meters). Table 4.1 (on the next page) highlights the three technologies used and ranks them based on their relative properties.

Table 4.1 Location Determination Sources on iOS Devices

Source

Speed

Intended Accuracy

Power

Cell tower *

Fastest

City or region

Fairly low, since 3G devices stay connected to towers.

Wi-Fi

Medium

City block or better

More than cell, but still low. Requires Wi-Fi to perform a scan of nearby networks.

GPS *

Slowest

+/- 5m or better

Fairly high compared to other methods, especially during continuous tracking.

As you can see, there are varying levels of performance, speed, and accuracy between each location source. Determining location through cell phone towers is very fast and very efficient but it’s not the most accurate determination. This is not always an issue. For example, if you’re making a taxi app and you want to list the phone numbers for all of the taxi services in the area, you probably only need to know what city someone is in. Since taxi services will drive a ways to pick you up, it’s not necessarily relevant that a person is standing on the corner of Arlington and Boylston.

At the other end of the spectrum, a fitness app that tracks your running progress or a turn-by-turn GPS app would require more accurate location data. Your users would be annoyed if their turn-by-turn app missed a turn by about 100 meters. In between these extremes, where accuracy is important but not as much as turn-by-turn, would be a location check-in service. In this case it’s not critical to your app’s function that a person be in the exact location their device claims to be, so you can trade off the accuracy for better battery performance.

Another important take-away from Table 4.1 is that not every location data source is available on every iOS device. Only devices configured with a cellular radio (iPhones and 3G-enabled iPads) are able to determine location through cell towers. Additionally, GPS is only available on the iPhone models 3G and later and all 3G-enabled iPads. If accurate location data is critical to the operation of your app (such as for turn-by-turn navigation or Find My Friends), then you should configure your app’s info property list to require the appropriate hardware.

You can add two levels of restrictions for location-based hardware capabilities. When added to the UIRequiredDeviceCapabilities array in your info property list, these keys provide the following restrictions (Figure 4.2):

4_2_require_capabilitie.jpg

Figure 4.2. Location-based hardware requirements added to an app’s info property list.

  • location-services: Requires that device has some form of location service available. Used as a general restriction.
  • gps: Requires device with GPS hardware.

Remember, add these keys to your app only if your app is unable to operate without them. If location is simply a nice feature that improves user experience, then your app should not require specific hardware. For example, a movie theatre app might work best when the app can automatically determine your location using hardware. But this app would also work if a user simply types in their ZIP code for nearby theaters. In this case, the app should not include location-services as required hardware.

Fortunately, while it is important for you to be aware of the various source hardware capabilities, it is not necessary for you to specify which piece of hardware your application should use—iOS chooses the hardware automatically. When working with the Core Location Manager to manage updates from hardware, you simply specify your desired accuracy. The desired accuracy of the location manager is measured in meters and can be set using a CLLocationAccuracy constant. These constants are defined by the iOS SDK and indicate by name their intended use (Table 4.2).

Table 4.2. Core Location Accuracy Constants

Constant

Intended Use

kCLLocationAccuracyBest

The default value for the location manager desired accuracy. In this condition, iOS does its best to provide the best location possible with locationbased hardware.

kCLLocationAccuracyBestForNavigation

This condition is the most accurate of all the available configurations and should only be used in apps where absolute precision is necessary (turn-by-turn). ioS actually achieves better than "best" in this condition by using additional sensors beyond location-based hardware to provide highlyaccurate data at all times. this condition is fairly power intensive and is designed to operate while the device is plugged in to a power source.

kCLLocationAccuracyNearesttenMeters

Set the desired accuracy to 10 meters. This condition works well for checkin type applications.

kCLLocationAccuracyHundredMeters

Set the desired accuracy to 100 meters. this condition works well for nearby services that operate under the assumption your user is walking (such as nearby restaurants or friends close by).

kCLLocationAccuracyKilometer

Set the desired accuracy for 1 kilometer. This condition works well for city-based searches such as the nearest movie theater.

kCLLocationAccuracythreeKilometers

Set the desired accuracy for 3 kilometers. This condition works well for city-based searches where you're looking for services available in that city and are not necessarily sorting by the closest service.

Location Permissions

I don’t know about you, but I can’t count how many times I’ve launched an app and was surprised to be asked for access to my location. Nine times out of ten, if I wasn’t expecting to provide an app with my location, I won’t allow it.

The moral of this story is when you use location in apps, you have to ask for permission first—there’s no way around it. The harsh truth about location-aware apps is that many users don’t like providing apps with their location data. Not everyone will enable location for your app, even if it makes your app super awesome. So you need to be prepared to handle conditions where your app does not have permission to use the services you planned on using.

Controlling Location Permissions

The first time your app attempts to determine a device’s location, iOS will prompt a permission dialog to the user that indicates your action. This action occurs whether you’re using a CLLocationManager (Core Location) or an MKMapView (Map Kit) configured to show the device’s location. By default, this dialog will simply say, “Your App Would Like to Use Your Current Location,” with the choices of Don’t Allow and OK. When you’re determining location using the CLLocationManager, you have the option of setting a purpose string, which is your opportunity to explain in the permission dialog why your app needs access to a user’s location. (Figure 4.3).

4_3_permission.jpg

Figure 4.3. A location services permission dialog.

We’ll get into the specifics of the CLLocationManager in the next section; however, while we’re on the subject of permissions you can configure the custom purpose message of a CLLocationManager by setting its managed property purpose (Figure 4.3).

1   [locationManager setPurpose:@"My Custom Purpose Message..."];

Determining Location Service Availability

Before you attempt to use location services in your app, you should first check to see if they’re available. There are many reasons why location services might be unavailable. First and foremost, the necessary hardware might be disabled because a device is in airplane mode or because the user has turned off location services globally for all apps. Second, a user might have disallowed access to your app specifically either in the location services permission dialog mentioned in the previous section or in the Settings app. Finally, the Parental Controls section of the Settings app on every iOS device allows parents the choice to prevent apps from using location data. This condition should be handled separately from the permission dialog because in this case your users will never be presented with a dialog asking for permission.

With these conditions in mind, the CLLocationManager offers two class methods that allow you to determine first, whether or not location services are enabled, and second, the authorization status of your specific app. These class methods are [CLLocationManager locationServicesEnabled] and [CLLocationManager authorizationStatus], with the conditions and possible values demonstrated in the following code block:

 1   // Check to see if location services are enabled
 2   if([CLLocationManager locationServicesEnabled]){
 3
 4       NSLog(@"Location Services Enabled");
 5
 6       // Switch through the possible location
 7       // authorization states
 8       switch([CLLocationManager authorizationStatus]){
 9         case kCLAuthorizationStatusAuthorized:
10           NSLog(@"We have access to location services");
11           break;
12         case kCLAuthorizationStatusDenied:
13           NSLog(@"Location services denied by user");
14           break;
15         case kCLAuthorizationStatusRestricted:
16           NSLog(@"Parental controls restrict location services");
17           break;
18         case kCLAuthorizationStatusNotDetermined:
19           NSLog(@"Unable to determine, possibly not available");
20       }
21   }
22   else{
23       // locationServicesEnabled was set to NO
24       NSLog(@"Location Services Are Disabled");
25   }

This code block is fairly straightforward. Functionally, we’re not doing much more than printing log messages based on the possible location services enabled and location authorization states. In line 2 we first check to see if location services are enabled. If this condition results to NO, we jump down to line 22 and handle our disabled condition. This condition would result as NO if the device were in airplane mode or if location services were disabled globally in the Settings app. In lines 8 through 20 we handle the condition that location services are enabled by evaluating a switch statement based on the possible authorization status values. The possible values for the location authorization status are

  • kCLAuthorizationStatusAuthorized: Your app is able to use location services.
  • kCLAuthorizationStatusDenied: The user has chosen to deny your app access to location services.
  • kCLAuthorizationStatusRestricted: You do not have access to location services because availability is restricted by parental controls. This means the user will never be presented a permission dialog.
  • kCLAuthorizationStatusNotDetermined: Your app was unable to determine if location services are authorized. This authorization state is most likely caused by location services being disabled or some other fringe case caused by errors. In our code block, we would probably never reach this condition because we first check to see if location services are enabled. But, if you were to check this value outside of our code block while services are disabled, the status would be unknown.
  • + Share This
  • 🔖 Save To Your Account

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