iOS个人修养iOS开发工具

iOS后台持续定位

2015-12-11  本文已影响863人  CGPointZero

继之前的后台播放音频,后台下载,再来一发后台持续定位的实现。流程差不多:
1.开去后台模式:

后台模式勾选

2.在plist中加入NSLocationAlwaysUsageDescription这个键,对应的值为Boolean型,YES (总是使用定位)。
并在程序中加入如下代码,获取持续定位的许可。
<pre>if([_manager respondsToSelector:@selector(requestAlwaysAuthorization)])
{
[_manager requestAlwaysAuthorization];
}</pre>
其中的manager是CLLocationManager对象。

3.在applicationDidEnterBackground:方法中,加入如下代码:
<pre>- (void)applicationDidEnterBackground:(UIApplication )application {
if([CLLocationManager significantLocationChangeMonitoringAvailable])
{
ViewController
vc=(ViewController *)self.window.rootViewController;
[vc.manager stopUpdatingLocation];
[vc.manager startMonitoringSignificantLocationChanges];
}
else
{
NSLog(@"significant Location Change not Available");
}
}</pre>
4.在applicationDidBecomeActive:方法中,加入如下代码:
<pre>

5.至此,后台持续定位功能成功实现。最后附上部分代码,供参考:
AppDelegate.m
<pre>

import "AppDelegate.h"

import <CoreLocation/CoreLocation.h>

import "ViewController.h"

@interface AppDelegate ()

@end

@implementation AppDelegate

@end
</pre>
ViewController.h
<pre>

import <UIKit/UIKit.h>

import <CoreLocation/CoreLocation.h>

@interface ViewController : UIViewController<CLLocationManagerDelegate>

//定位管理对象
@property(nonatomic,strong)CLLocationManager *manager;

@end
</pre>
ViewController.m
<pre>

import "ViewController.h"

import <Photos/Photos.h>

import <CoreLocation/CoreLocation.h>

@interface ViewController ()<CLLocationManagerDelegate>
{
// 定位管理对象
CLLocationManager *_manager;
CLGeocoder *_coder;
// 存储上一次的位置
}
@end

@implementation ViewController

}

pragma mark-CLLocationManager代理方法

//定位失败时调用的方法
-(void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
NSLog(@"%@",error);
}
//定位成功调用的的方法
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
if(locations.count>0)
{
//获取位置信息
CLLocation *loc=[locations lastObject];
//海拔
CGFloat altitute=loc.altitude;
CGFloat altituteAcuracy=loc.verticalAccuracy;

    NSLog(@"海拔高度:%.0fm 精度:%.0fm",altitute,altituteAcuracy);
    //获取经纬度的结构体
    CLLocationCoordinate2D coor=loc.coordinate;
    
    CLLocation *location=[[CLLocation alloc]initWithLatitude:coor.latitude longitude:coor.longitude];
    
    [_coder reverseGeocodeLocation:location completionHandler:^(NSArray *placemarks, NSError *error) {
        CLPlacemark *pmark=[placemarks firstObject];
        NSLog(@"%@",pmark.addressDictionary);
        NSString *city=pmark.addressDictionary[@"City"];
        if([city hasSuffix:@"市辖区"])
            city=[city substringToIndex:city.length-3];
        if([city hasSuffix:@"市"])
            city=[city substringToIndex:city.length-1];
        NSLog(@"%@",city);
    }];
}

}
//返回定位的朝向
-(void)locationManager:(CLLocationManager *)manager didUpdateHeading:(CLHeading *)newHeading
{
// 相对地理北极的方向
// newHeading.trueHeading;
// 相对地磁北极的方向
// newHeading.magneticHeading;
}

@end
</pre>

上一篇 下一篇

猜你喜欢

热点阅读