iOS Location Services Programming

Source: Internet
Author: User
Tags uikit

Many mobile devices now offer location services, iphone, IPod Touch and ipad with iOS, and iOS devices can be located in 3 different ways: Wifi, cellular mobile phone base station, GPS satellite

IOS does not like the Android system when it is programmed in location services, you can specify which route to use for positioning. The iOS API masks the underlying details, and developers and users do not know which way the device is positioned, and the iOS system uses the best solution based on the device and the environment around it. This is the case, if you can receive GPS information, then the device priority to use GPS positioning, or use WiFi or cellular base station positioning, WiFi and cellular base station priority to use WiFi, if you can not connect to the Wi-Fi use cellular base station location.

In general, the advantages of GPS positioning is accurate, broad coverage, the disadvantage is not to be obscured (for example: in the building can not receive GPS satellite signal), GPS opened after the comparison of electricity. The cellular base station not only has the big error, but also consumes the user traffic expense. WiFi location is the most cost-effective.

Location Services Programming

Location Services after iOS 6 The API did not change much, mainly using the corelocation framework, when targeting the main use of Cllocationmanager, Cllocationmanagerdelegate and Cllocation. Cllocationmanager is a location service management class that provides us with access to device locations and high-level information, as well as monitoring devices to enter or leave an area, and it can also help to obtain the direction of the device's operation. Cllocationmanagerdelegate is a Cllocationmanager class delegation protocol. The Cllocation class is packed with location and height information.

In the application of location services, when the first request obtains location information, the system prompts the user whether to allow the location service to be enabled. The user's location is more private information, the application to obtain these information users have the right to know and negative. This is illegal in some countries if the app obtains the user's location information without the user's knowledge.

If you choose "Do not allow", the location service will not be able to get position information, if you want to change these settings can be turned on or off in the system settings app.

We can close all the location services, just close the top "location Services" switch control. The following specific applications can also be turned off and turned on.

Below we introduce a case to use Location service programming, start when the application starts, access to the screen when the location information, and displayed in the corresponding text box, if the device location to send changes, will also re-location information, and update the corresponding text box.

First of all to achieve the location service case, need to introduce corelocation framework for the project, add concrete steps is to select the project Targets→whereami→build phases→link Binary with Libraries, select the lower right corner of the "+" button to open the Frame and Library selection dialog box

In the Add dialog box, select Corelocation.framework, click the Add button and add complete. UI Design section We are no longer introduced. We look directly at the implementation code, where the main code is written in the View controller Viewcontroller, where the ViewController.h code is as follows:

CPP Code
  1. #import <UIKit/UIKit.h>
  2. #import <CoreLocation/CoreLocation.h>
  3. #import <CoreLocation/CLLocationManagerDelegate.h>
  4. @interface Viewcontroller:uiviewcontroller <CLLocationManagerDelegate>
  5. Longitude
  6. @property (Weak, nonatomic) Iboutlet Uitextfield *txtlng;
  7. Latitude
  8. @property (Weak, nonatomic) Iboutlet Uitextfield *txtlat;
  9. Height
  10. @property (Weak, nonatomic) Iboutlet Uitextfield *txtalt;
  11. @property (nonatomic, strong) Cllocationmanager *locationmanager;
  12. @end

In the H file, you first need to introduce <CoreLocation/CoreLocation.h> and <CoreLocation/CLLocationManagerDelegate.h> header files. You then need to declare the implementation of the Cllocationmanagerdelegate protocol when defining Viewcontroller. We also defined the Cllocationmanager *locationmanager property.

The Viewdidload code for VIEWCONTROLLER.M is as follows:

CPP Code
    1. -(void) Viewdidload
    2. {
    3. [Super Viewdidload];
    4. Location Services Management Object initialization
    5. _locationmanager = [[Cllocationmanager alloc] init];
    6. _locationmanager.delegate = self;
    7. _locationmanager.desiredaccuracy = Kcllocationaccuracybest; ①
    8. _locationmanager.distancefilter = 1000.0f; Ii
    9. }

In the Viewdidload method, the Cllocationmanager member variable _locationmanager is primarily initialized. The Cllocationmanager object is instantiated first using the [[Cllocationmanager alloc] init] statement. Then the _locationmanager.delegate = Self statement sets the location service delegate to self. The ① Line code sets the Desiredaccuracy property, which is a very important property, with a value of 6 constants: Kcllocationaccuracynearesttenmeters. Accuracy 10 m; kcllocationaccuracyhundredmeters. Accuracy 100 m; kcllocationaccuracykilometer. Accuracy 1000 m; kcllocationaccuracythreekilometers. Accuracy 3000 m; kcllocationaccuracybest. When the device is battery powered, the highest precision; kcllocationaccuracybestfornavigation. The highest accuracy in the case of navigation, generally need to have external power supply to use;

The higher the precision, the less time it takes to obtain location information, which means the device consumes more power. So an application should choose the right precision, if your application is a car navigation application, Kcllocationaccuracybestfornavigation is a good choice, you can use the battery on the car to power the equipment. If your app is a navigation app for hikers, Kcllocationaccuracyhundredmeters is a good choice.

The ② Line code sets the Distancefilter property, which is the distance filter, which defines the minimum distance that the device moves update location information, in meters, which is set at 1000 meters.

After the initialization cllocationmanager is complete, you need to use the Startupdatinglocation method to start the location service. It is in the VIEWCONTROLLER.M Viewwillappear: method, the code is as follows:

CPP Code  
    1. -(void) Viewwillappear: (BOOL) animated
    2. {
    3. [Super viewwillappear:animated];
    4. Start positioning
    5. [_locationmanager startupdatinglocation];
    6. }

The call to the Startupdatinglocation method locates the service, which, based on the conditions set, constantly requests a callback for new location information. It is therefore prudent to turn this method on, to open it at the most appropriate time, and to viewwillappear in the declaration cycle method of the View controller: it is the most appropriate. The method that corresponds to the open service is the Stopupdatinglocation method, which is called in the View controller's Viewwilldisappear: method, with the following code:

CPP Code   
    1. -(void) Viewwilldisappear: (BOOL) animated
    2. {
    3. [Super viewwilldisappear:animated];
    4. Stop positioning
    5. [_locationmanager stopupdatinglocation];
    6. }

Viewwilldisappear: Called when the View disappears (application fallback to the background), it is a responsible practice to ensure that location services are closed in the most timely manner. Requests change after iOS 6, the location service app is back in the console and can defer updates to position information, where the Allowdeferredlocationupdatesuntiltraveled:timeout: method can set up deferred updates so that the app is no longer in the background Update location information. The shutdown deferred update is implemented using the Disallowdeferredlocationupdates method. In addition, after iOS 6, add the pauseslocationupdatesautomatically attribute, it can set the automatic pause location update, location services to open and suspend management to the system, it is more reasonable and simple.

Once the location service is turned on and the Cllocationmanager Delegate property delegate is set, when the user device moves to the filtering distance, the delegate method is recalled, and there are two methods related to location services:

Locationmanager:didupdatelocations: Positioning success, is the new iOS 6 method, replacing the previous locationManager:didUpdateToLocation:fromLocation: method;

Locationmanager:didfailwitherror: Failed to locate;

Implement the Cllocationmanager delegate code as follows:

CPP Code
  1. #pragma the Mark Core location delegate method for updating locations
  2. -(void) Locationmanager: (Cllocationmanager *) Manager didupdatelocations: (Nsarray *) Locations
  3. {
  4. Cllocation * currlocation = [locations Lastobject]; ①
  5. _txtlat.text = [NSString stringwithformat:@"%3.5f",
  6. CurrLocation.coordinate.latitude]; Ii
  7. _txtlng.text = [NSString stringwithformat:@"%3.5f",
  8. CurrLocation.coordinate.longitude]; ③
  9. _txtalt.text = [NSString stringwithformat:@"%3.5f",
  10. Currlocation.altitude]; ④
  11. }
  12. -(void) Locationmanager: (Cllocationmanager *) Manager didfailwitherror: (nserror *) Error
  13. {
  14. NSLog (@ "error:%@", error);
  15. }

In Locationmanager:didupdatelocations: The parameter locations in the method is a set of positional changes, which are stored in the order of time changes. If you want to get the location of the current device, you can use the [locations Lastobject] Statement of line ① to get the last element in the collection, which is the device's current position. The type of object returned from the collection is cllocation,cllocation encapsulates information such as location, height, and so on. In the above code we used its two properties: the altitude and Coordinate,altitude properties are height values, coordinate is the structure body cllocationcoordinate2d that encapsulates the longitude and latitude, CLLOCATIONCOORDINATE2D is defined as follows:

CPP Code   
    1. typedef struct {
    2. Cllocationdegrees latitude; //Latitude
    3. Cllocationdegrees longitude; //Longitude
    4. } cllocationcoordinate2d;

Where latitude are longitude information, longitude are latitude information, they are cllocationdegrees types, and cllocationdegrees are double types defined with typedef.

The newLocation.coordinate.latitude expression in line ② code is the current latitude of the device, the ③ line of code in the The newLocation.coordinate.longitude expression is the current latitude of the device, and the obtained height can be obtained directly using the ④ line newlocation.altitude expression.

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.