iOS开发 程序后台上传位置CLLocationManager

2024-03-05 04:18

本文主要是介绍iOS开发 程序后台上传位置CLLocationManager,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

之前开发一款配送员用的APP时,用到了在程序在后台时,可以不断上传位置的功能,今天略微整理了一下,

主要用到系统的CoreLocation

代码:

#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>@interface XSDLocationTools : NSObject
+ (XSDLocationTools *)shareInstance;
// 开启定位
- (void)startLocationService;
@end

.m

//
//  XGLocationTool.m
//  XGPayDemo
//
//  Created by 小广 on 16/4/25.
//  Copyright © 2016年 小广. All rights reserved.
//#import "XSDLocationTools.h"
#import <CoreLocation/CoreLocation.h>
//#import "WGS84ToGCJ02.h"
#import "BaiduMapDefine.h"
#import "XSDBaiduMapTools.h"#define LAST_LONG  @"last_longitude"  // 上次上传位置的经度
#define LAST_LATI  @"last_latitude"  // 上次上传位置的纬度@interface XSDLocationTools ()<CLLocationManagerDelegate>
{//dispatch_source_t _timer;CLLocationCoordinate2D _newCoor;
}
// 1.设置位置管理者属性
@property (nonatomic, strong) CLLocationManager *lcManager;
//@property (nonatomic, assign) BOOL isRequest;
@property (nonatomic, strong) NSTimer *uploadTimer;@end@implementation XSDLocationTools+ (XSDLocationTools *)shareInstance {static XSDLocationTools *instance = nil;static dispatch_once_t onceToken;dispatch_once(&onceToken, ^{instance = [[XSDLocationTools alloc] init];[instance p_addNSNotificationObserver];});return instance;
}// 开启定位
- (void)startLocationService {if ([CLLocationManager locationServicesEnabled]) {// 创建位置管理者对象self.lcManager = [[CLLocationManager alloc] init];self.lcManager.delegate = self; // 设置代理// 设置定位距离过滤参数 (当本次定位和上次定位之间的距离大于或等于这个值时,调用代理方法)self.lcManager.distanceFilter = 50;self.lcManager.desiredAccuracy = kCLLocationAccuracyBest; // 设置定位精度(精度越高越耗电)// 2、在Info.plist文件中添加如下配置://(1)NSLocationAlwaysUsageDescription 授权使应用在前台后台都能使用定位服务//(2)NSLocationWhenInUseUsageDescription 授权使应用只能在前台使用定位服务// 两者也可以都写if ([[UIDevice currentDevice].systemVersion floatValue] >=8.0 ) {// iOS0.0:如果当前的授权状态是使用是授权,那么App退到后台后,将不能获取用户位置,即使勾选后台模式:location[self.lcManager requestAlwaysAuthorization];[self.lcManager requestWhenInUseAuthorization];}// iOS9.0+ 要想继续获取位置,需要使用以下属性进行设置(注意勾选后台模式:location)但会出现蓝条if ([self.lcManager respondsToSelector:@selector(allowsBackgroundLocationUpdates)]) {//self.lcManager.allowsBackgroundLocationUpdates = YES;}[self.lcManager startUpdatingLocation]; // 开始更新位置[self.uploadTimer setFireDate:[NSDate distantPast]]; // 开启定时器}
}/** 获取到新的位置信息时调用*/
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations {CLLocation *tempLocation = locations[0];// 将坐标转化为百度坐标 方法来源于百度sdkNSDictionary *temp = BMKConvertBaiduCoorFrom(tempLocation.coordinate, BMK_COORDTYPE_GPS);CLLocationCoordinate2D nowLocation = BMKCoorDictionaryDecode(temp);//if (self.isRequest) return;//self.isRequest = YES;//[self uploadUserLocationHandle:nowLocation];//[self uploadLocationTimer:nowLocation];_newCoor = nowLocation;
}
/** 不能获取位置信息时调用*/
-(void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {NSLog(@"获取定位失败");
}/** 定位服务状态改变时调用*/
- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status
{switch (status) {case kCLAuthorizationStatusNotDetermined:{NSLog(@"用户还未决定授权");break;}case kCLAuthorizationStatusRestricted:{NSLog(@"访问受限");break;}case kCLAuthorizationStatusDenied:{// 类方法,判断是否开启定位服务if ([CLLocationManager locationServicesEnabled]) {NSLog(@"定位服务开启,被拒绝");} else {NSLog(@"定位服务关闭,不可用");}break;}case kCLAuthorizationStatusAuthorizedAlways:{NSLog(@"获得前后台授权");break;}case kCLAuthorizationStatusAuthorizedWhenInUse:{NSLog(@"获得前台授权");break;}default:break;}
}// 直接上传用户位置
static NSInteger uploadCount = 1;
- (void)uploadUserLocationHandle:(CLLocationCoordinate2D)coor {NSDictionary *dic = @{@"longitude":@(coor.longitude),@"latitude":@(coor.latitude)};__weak typeof(self)weakSelf = self;[[UserManager shareInstance] uploadUserLocation:dic block:^(BOOL success) {if (!success) {if (uploadCount > 3) return ;uploadCount ++;[weakSelf uploadUserLocationHandle:coor];XSDLog(@"上传位置不ok");return;}// if (uploadCount != 1) uploadCount = 1;XSDLog(@"上传位置ok");}];}// 定时上传位置
- (void)uploadLocationTimer {BOOL canUpload = [self isCanUpload:_newCoor];if (canUpload) {NSDictionary *dic = @{@"longitude":@(_newCoor.longitude),@"latitude":@(_newCoor.latitude)};__weak typeof(self)weakSelf = self;// 和后台服务器进行交互 上传位置[[UserManager shareInstance] uploadUserLocation:dic block:^(BOOL success) {if (success) {XSDLog(@"上传位置ok");return ;}XSDLog(@"上传位置不ok");[weakSelf uploadUserLocationHandle:_newCoor];}];}}// 监听用户登录的通知
- (void)p_addNSNotificationObserver {[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(p_loginNotification) name:kLoginNotification object:nil];
}- (void)p_loginNotification {// 用户登录, 就开始上传位置NSString *latitude = [XSDTools objectForKey:TCPFLocationlatitude];NSString *longitude = [XSDTools objectForKey:TCPFLocationlongitude];if (!latitude || !longitude) return;// 读取本地的经纬度CLLocationCoordinate2D location = CLLocationCoordinate2DMake(latitude.doubleValue, longitude.doubleValue);[self uploadUserLocationHandle:location];
}// 是否达到条件(判断距离 大于一定距离)上传位置
- (BOOL)isCanUpload:(CLLocationCoordinate2D)coor {//  下面代码相当于 NSUserDefaults 存取数据NSString *latitude = [XSDTools objectForKey:LAST_LATI];NSString *longitude = [XSDTools objectForKey:LAST_LONG];if (!latitude || !longitude) {//  下面代码相当于 NSUserDefaults 存取数据[XSDTools setValue:[NSString stringWithFormat:@"%f",coor.latitude] forKey:LAST_LATI];[XSDTools setValue:[NSString stringWithFormat:@"%f",coor.longitude] forKey:LAST_LONG];return YES;}//  下面代码来源于百度sdk 计算两点间的距离 NSNumber *distence = [XSDBaiduMapTools calculateTwoPointLongWithStart:CLLocationCoordinate2DMake(latitude.doubleValue, longitude.doubleValue) end:coor];if (distence.integerValue >= 100) {//  下面代码相当于 NSUserDefaults 存取数据[XSDTools setValue:[NSString stringWithFormat:@"%f",coor.latitude] forKey:LAST_LATI];[XSDTools setValue:[NSString stringWithFormat:@"%f",coor.longitude] forKey:LAST_LONG];return YES;}return NO;
}// 懒加载
- (NSTimer *)uploadTimer {if (!_uploadTimer) {_uploadTimer = [NSTimer scheduledTimerWithTimeInterval:10.0 target:self selector:@selector(uploadLocationTimer) userInfo:nil repeats:YES];}return _uploadTimer;
}@end
里面用到了一些自定义的类,不过不影响,各位可以根据需求修改,挺简单的;

在AppDelegate的- (BOOL)application:(UIApplication *)application willFinishLaunchingWithOptions:(NSDictionary *)launchOptions 方法里

直接调用即可:[[XSDLocationTools shareInstance] startLocationService];

还有,是必须在如图所示,勾选location updates;

图:


最后,审核的时候,一定要说明清楚,为啥要用这个后台上传位置功能;这个审核被拒概率很大,也没有好的解决方法;

这篇关于iOS开发 程序后台上传位置CLLocationManager的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/775309

相关文章

使用Python开发一个带EPUB转换功能的Markdown编辑器

《使用Python开发一个带EPUB转换功能的Markdown编辑器》Markdown因其简单易用和强大的格式支持,成为了写作者、开发者及内容创作者的首选格式,本文将通过Python开发一个Markd... 目录应用概览代码结构与核心组件1. 初始化与布局 (__init__)2. 工具栏 (setup_t

使用Node.js制作图片上传服务的详细教程

《使用Node.js制作图片上传服务的详细教程》在现代Web应用开发中,图片上传是一项常见且重要的功能,借助Node.js强大的生态系统,我们可以轻松搭建高效的图片上传服务,本文将深入探讨如何使用No... 目录准备工作搭建 Express 服务器配置 multer 进行图片上传处理图片上传请求完整代码示例

Spring Shell 命令行实现交互式Shell应用开发

《SpringShell命令行实现交互式Shell应用开发》本文主要介绍了SpringShell命令行实现交互式Shell应用开发,能够帮助开发者快速构建功能丰富的命令行应用程序,具有一定的参考价... 目录引言一、Spring Shell概述二、创建命令类三、命令参数处理四、命令分组与帮助系统五、自定义S

SpringBoot实现微信小程序支付功能

《SpringBoot实现微信小程序支付功能》小程序支付功能已成为众多应用的核心需求之一,本文主要介绍了SpringBoot实现微信小程序支付功能,文中通过示例代码介绍的非常详细,对大家的学习或者工作... 目录一、引言二、准备工作(一)微信支付商户平台配置(二)Spring Boot项目搭建(三)配置文件

Python通过模块化开发优化代码的技巧分享

《Python通过模块化开发优化代码的技巧分享》模块化开发就是把代码拆成一个个“零件”,该封装封装,该拆分拆分,下面小编就来和大家简单聊聊python如何用模块化开发进行代码优化吧... 目录什么是模块化开发如何拆分代码改进版:拆分成模块让模块更强大:使用 __init__.py你一定会遇到的问题模www.

Spring Security基于数据库的ABAC属性权限模型实战开发教程

《SpringSecurity基于数据库的ABAC属性权限模型实战开发教程》:本文主要介绍SpringSecurity基于数据库的ABAC属性权限模型实战开发教程,本文给大家介绍的非常详细,对大... 目录1. 前言2. 权限决策依据RBACABAC综合对比3. 数据库表结构说明4. 实战开始5. MyBA

使用Python开发一个简单的本地图片服务器

《使用Python开发一个简单的本地图片服务器》本文介绍了如何结合wxPython构建的图形用户界面GUI和Python内建的Web服务器功能,在本地网络中搭建一个私人的,即开即用的网页相册,文中的示... 目录项目目标核心技术栈代码深度解析完整代码工作流程主要功能与优势潜在改进与思考运行结果总结你是否曾经

Spring Boot + MyBatis Plus 高效开发实战从入门到进阶优化(推荐)

《SpringBoot+MyBatisPlus高效开发实战从入门到进阶优化(推荐)》本文将详细介绍SpringBoot+MyBatisPlus的完整开发流程,并深入剖析分页查询、批量操作、动... 目录Spring Boot + MyBATis Plus 高效开发实战:从入门到进阶优化1. MyBatis

Python基于wxPython和FFmpeg开发一个视频标签工具

《Python基于wxPython和FFmpeg开发一个视频标签工具》在当今数字媒体时代,视频内容的管理和标记变得越来越重要,无论是研究人员需要对实验视频进行时间点标记,还是个人用户希望对家庭视频进行... 目录引言1. 应用概述2. 技术栈分析2.1 核心库和模块2.2 wxpython作为GUI选择的优

利用Python开发Markdown表格结构转换为Excel工具

《利用Python开发Markdown表格结构转换为Excel工具》在数据管理和文档编写过程中,我们经常使用Markdown来记录表格数据,但它没有Excel使用方便,所以本文将使用Python编写一... 目录1.完整代码2. 项目概述3. 代码解析3.1 依赖库3.2 GUI 设计3.3 解析 Mark