iOS targeting--corelocation frame

Source: Internet
Author: User

Use of the Corelocation framework
// 首先导入头文件#import <CoreLocation/CoreLocation.h>
    • The prefix for all data types in the Corelocation framework is CL
    • Using Cllocationmanager objects in corelocation to do user positioning
Common operation of 1.CLLocationManager using Cllocationmanager
/** *  定位管理者,全局变量强引用,防止销毁 */@property (nonatomic ,strong) CLLocationManager *mgr;
Set up Agent
// 2.成为CoreLocation管理者的代理监听获取到的位置    self.mgr.delegate = self;
① Get user Authorization 注意:IOS7 the user is automatically asked to authorize your application as soon as the location is started. But starting with iOS8, you need to be "self" and "active" to require user authorization.
    • Add friendly hints to add fields to the Info.plist file
      • Privacy-location Usage Description
In IOS8, you should not only proactively request authorization, but you must also configure a property in the Info.plist file to eject the authorization window
    • Nslocationwheninusedescription, allowing GPS descriptions to be obtained at the front desk
    • Nslocationalwaysusagedescription, allows the description of GPs to be acquired in the background
 /* User has never selected permissions kclauthorizationstatusnotdetermined cannot use location services, the status user cannot change kclauthorizationstatusrestricted The app uses location services, or the location services total switch is turned off kclauthorizationstatusdenied authorized (deprecated) kclauthorizationstatusauthorized users to allow the process Geographic information can be used at any time kclauthorizationstatusauthorizedalways the user consent program to use geolocation when visible Kclauthorizationstatusauthorizedwheninu SE *///1. Get User authorization status Clauthorizationstatus status = [Cllocationmanager authorizationstatus]; //2. Determine if the user is authorized if (status = = kclauthorizationstatusnotdetermined) { NSLog (@ "Wait for user Authorization");} Else if (status = = Kclauthorizationstatusauthorizedalways | | status = = Kclauthorizationstatusauthorizedwheninuse) { NSLog (@ "authorized success"); //Start positioning [self. Mgr Startupdatinglocation];} else { NSLog (@ "Authorization Failed");}              
IOS8 reason for requesting authorization not to be prompted
    • 1. No request sent
      • No request code
    • 2.CLLocationManager is not a global member property
      • Be destroyed prematurely, without strong references
    • 3. No fields are added to the Info.plist file
      • Nslocationalwaysusagedescription
      • Nslocationwheninusedescription
② Start user Targeting
- (void)startUpdatingLocation;
③ Stop user positioning
- (void) stopUpdatingLocation;
③ set when the user moves how many meters, reposition
- self.mgr.distanceFilter = 50;
④ setting the accuracy of the get position
    • The more accurate the more power it consumes
    /*      kCLLocationAccuracyBestForNavigation 最佳导航      kCLLocationAccuracyBest;  最精准      kCLLocationAccuracyNearestTenMeters;  10米      kCLLocationAccuracyHundredMeters;  百米      kCLLocationAccuracyKilometer;  千米      kCLLocationAccuracyThreeKilometers;  3千米     */    self.mgr.desiredAccuracy = kCLLocationAccuracyNearestTenMeters;
    • When the Startupdatinglocation method is called, the user's location is started constantly, and the agent's method is called frequently in the middle调用频率非常高

    • If you only need to get it once, you can get to the location and stop

      • [Manager Stopupdatinglocation];
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations;//locations参数里面装着CLLocation对象
The user's coordinate information can be obtained in the Startupdatinglocation proxy method.
  //1. Get the last position cllocation *location = [Locations Lastobject]    ; /* location.coordinate; coordinates, including latitude and longitude location.altitude; equipment Altitude Unit is the meter location.course; Forward direction 0 means North 90 East 180 south 270 West Location.horizontalaccuracy; Horizontal accuracy of location.verticalaccuracy; Vertical accuracy of location.timestamp; The time location.speed The location information is returned;     Device Movement Speed Unit is m/s, suitable for driving speed and not suitable for no. *//* can set simulator simulation speed bicycle ride bike move run running    Freeway Drive Expressway */cllocation *location = [locations Lastobject]; nslog (@ "%f,%f speed =%f", location .coordinate.latitude, location .coordinate.longitude, location .speed)            
Calculate the straight distance between two places
    • (cllocationdistance) Distancefromlocation: (const cllocation *) location;
    // 北京:39.6 116.39    // 广州:23.08 113.15    CLLocation *BeiJing = [[CLLocation alloc] initWithLatitude:39.6 longitude:116.39];    CLLocation *GuangZhou = [[CLLocation alloc] initWithLatitude:23.08 longitude:113.15]; // 得到两地之间的距离 CLLocationDistance distance = [BeiJing distanceFromLocation:GuangZhou]; NSLog(@"%.2f", distance);
2, Cllocation
    • Cllocation the geographic information used to represent a location, such as latitude and longitude, altitude, etc.
// 属性    location.coordinate; 坐标, 包含经纬度     location.altitude; 设备海拔高度 单位是米     location.course; 设置前进方向 0表示北 90东 180南 270西 location.horizontalAccuracy; 水平精准度 location.verticalAccuracy; 垂直精准度 location.timestamp; 定位信息返回的时间 location.speed; 设备移动速度 单位是米/秒, 适用于行车速度而不太适用于不行// 可以计算2个位置之间的距离- (CLLocationDistance)distanceFromLocation:(const CLLocation *)location
3, Clgeocoder
    • Use Clgeocoder to complete geocoding and anti-geocoding
Geocoding: To obtain specific location information (such as latitude and longitude, full name of address, etc.) based on a given place-name, to obtain specific location information based on a given latitude and longitude
// 地理编码方法- geocodeAddressString:address completionHandler:^(NSArray *placemarks, NSError *error) {};// 反地理编码方法- reverseGeocodeLocation:location completionHandler:^(NSArray *placemarks, NSError *error) {};
Clplacemark literally means a landmark, encapsulating detailed address location information
The Addressdictionary property of 1.CLPlacemark traverses the dictionary data addressdictionary Enumeratekeysandobjectsusingblock2.block is called in the main thread, so you can refresh Uiname directly in block: Place name thoroughfare: Street Ubthoroughfare: Street facies Information, such as locality: City sublocality: City-related information, such as iconic building Administrativearea: the municipality of Subadminis                Trativearea: Other administrative Region information PostalCode: Zip code isocountrycode: Country Code country;                  : National inlandwater: Water source, Lake Ocean; : Marine Areasofinterest: associated or interest-related landmarks@property (Nonatomic,readonly) Cllocation *location; //location  @property (nonatomic, Span class= "Hljs-keyword" >readonly) clregion *region; //area  @property (nonatomic, readonly) nsdictionary *addressdictionary; Detailed address information  @property (nonatomic,  ReadOnly) nsstring *name; Address name  @property (nonatomic,  ReadOnly) nsstring *locality; City                 
Error: Using Corelocation to obtain geo-location information, error
Error Domain=kCLErrorDomain Code=0 "The operation couldn’t be completed. (kCLErrorDomain error 0.)"
Workaround:
    • 1. Make sure the simulator (mobile phone) is networked and allows the program to obtain a geographic location
    • 2. Resetting the location service or network Service

    • PS:If it's the simulator, just reset the simulator directly. IOS simulator-reset Content and Settings ...

Latitude and longitude range of China's latitude and longitude degree
    • Latitude range: N 3°51′~ n 53°33′
    • Longitude range: E 73°33′~ e 135°05′
Latitude and longitude of some cities in China

iOS targeting--corelocation frame

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.