分享

iOS开发 实时定位 CLLocationManager

 玄冰优 2017-05-08

用系统原生的API来做一个实时定位。
https://github.com/Lian1990/TestLocation


本来是一个探索项目给客户展示用的demo,现在只简单记录一下其中的 实时定位,真实环境肯定是要考虑对于手机的耗电量等实际问题的,而且发布还要看苹果审核团队的脸色了 ????(  ̄ー ̄)。

首先是设置 info.plist 中的权限
 
 

开启后台运行的权限

 
 


代码code
只是将定位反编译直接展示在tableview中,以便测试。
顺便把本地提醒加上。


----------------------------------
.h文件中

#import <UIKit/UIKit.h>
#import <CoreLocation/CoreLocation.h>

@interface ViewController : UIViewController<UITableViewDataSource,UITableViewDelegate,CLLocationManagerDelegate>

@property (strong,nonatomic) UITableView *myTable;
@property (strong,nonatomic) CLLocationManager *locationManager;
@property (strong,nonatomic) NSMutableArray *dataArr;
@property (strong,nonatomic) NSTimer *myTimer;

@end

=====
.m文件中

#pragma mark === location ===
-(void)startLoaction{
    if ([CLLocationManager locationServicesEnabled]) {
        self.locationManager = [[CLLocationManager alloc]init];
        self.locationManager.delegate = self;
        self.locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters;
        [self.locationManager requestAlwaysAuthorization];
        [self.locationManager setAllowsBackgroundLocationUpdates:YES];
        self.locationManager.pausesLocationUpdatesAutomatically = NO;//不自动停止定位
        self.locationManager.distanceFilter = kCLDistanceFilterNone;//不移动也能更新定位
        [self.locationManager startUpdatingLocation];
    }
}
-(void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error{
    if ([error code] == kCLErrorDenied) {
        NSLog(@"deny 拒绝访问");
    }else if ([error code] == kCLErrorLocationUnknown){
        NSLog(@"unkonwn location 定位未知");
    }else{
        return;
    }
}
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations{
    CLLocation *newloaction = [locations objectAtIndex:0];
    CLGeocoder *geocoder = [[CLGeocoder alloc]init];
    [geocoder reverseGeocodeLocation:newloaction completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
        if (placemarks.count>0) {
            CLPlacemark *place = [placemarks objectAtIndex:0];
            NSString *locationStr = place.subLocality;
            if (locationStr) {
                _locationNewStr = locationStr;
                if (self.myTimer == nil) {
                    self.myTimer = [NSTimer scheduledTimerWithTimeInterval:60 target:self selector:@selector(updateLocationStr) userInfo:nil repeats:YES];
                }
               
            }
        }else if (error == nil && [placemarks count]==0){
            NSLog(@"无结果无结果 反编译没结果");
        }else if (error != nil){
            NSLog(@"the error is %@",error);
        }
    }];
    [manager stopUpdatingHeading];
}
-(void)updateLocationStr{
   
    NSString *str = [NSString stringWithFormat:@"%@+++%@",_locationNewStr,[NSDate date]];
    [self.dataArr insertObject:str atIndex:0];
    [self.myTable reloadData];
}


在appdelegate中
- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
   
    application.applicationIconBadgeNumber = 0; //小红点
}

//接收本地通知
-(void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification{
    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"打卡提示??????" message:notification.alertBody delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
    [alert show];
   
     [[UIApplication sharedApplication] cancelAllLocalNotifications];
}


.m文件中
 
 

***********************************************
关于相关的知识点

关于定位的一些属性和方法

1.CLLocationManager

CLLocationManager的常用操作和属性

开始用户定位- (void)startUpdatingLocation;

停止用户定位- (void) stopUpdatingLocation;

说明:当调用了startUpdatingLocation方法后,就开始不断地定位用户的位置,中途会频繁地调用代理的下面方法

  - (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations;

每隔多少米定位一次

  @property(assign, nonatomic) CLLocationDistance distanceFilter;

定位精确度(越精确就越耗电)

  @property(assign, nonatomic) CLLocationAccuracy desiredAccuracy;

 

2.CLLocation

CLLocation用来表示某个位置的地理信息,比如经纬度、海拔等等

(1)经纬度 

  @property(readonly, nonatomic) CLLocationCoordinate2D coordinate;

(2)海拔 

  @property(readonly, nonatomic) CLLocationDistance altitude;

(3)路线,航向(取值范围是0.0° ~ 359.9°,0.0°代表真北方向)

  @property(readonly, nonatomic) CLLocationDirection course;

(4)行走速度(单位是m/s)

   @property(readonly, nonatomic) CLLocationSpeed speed;

(5)计算2个位置之间的距离

  - (CLLocationDistance)distanceFromLocation:(const CLLocation *)location方法

 

3.CLLocationCoordinate2D

CLLocationCoordinate2D是一个用来表示经纬度的结构体,定义如下

typedef struct {

        CLLocationDegrees latitude; // 纬度

        CLLocationDegrees longitude; // 经度

} CLLocationCoordinate2D;

一般用CLLocationCoordinate2DMake函数来创建CLLocationCoordinate2D


————————————————

本地通知属性

// 枚举值-发出通知的时间(有局限性)
@property(nonatomic) NSCalendarUnit repeatInterval;
// 自定义-发出通知的时间(可以自由设定时间)
@property(nonatomic,copy) NSCalendar *repeatCalendar;
// 区域-创建只需要创建一个中心点与半径就可以了
@property(nonatomic,copy) CLRegion *region
// 进入区域发出一个通知,设置yes,只会发出一个通知,设置NO就会每次进入这个区域都发送
@property(nonatomic,assign) BOOL regionTriggersOnce NO
// 设置通知的内容
@property(nonatomic,copy) NSString *alertBody;      
 // 决定alertAction是否生效
@property(nonatomic) BOOL hasAction;
// 设置滑块的文字
@property(nonatomic,copy) NSString *alertAction;    

// 设置点击通知的启动图片(一般设置App启动图片后,这里可以随便写)
@property(nonatomic,copy) NSString *alertLaunchImage;
// 设置alertTitle,就是通知内容上面的文字
@property(nonatomic,copy) NSString *alertTitle
 // 设置弹出的声音
@property(nonatomic,copy) NSString *soundName;
 // 设置App的消息条数
@property(nonatomic) NSInteger applicationIconBadgeNumber;
 // 设置通知一些额外数据
 @property(nonatomic,copy) NSDictionary *userInfo;









    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多