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

相关文章

这15个Vue指令,让你的项目开发爽到爆

1. V-Hotkey 仓库地址: github.com/Dafrok/v-ho… Demo: 戳这里 https://dafrok.github.io/v-hotkey 安装: npm install --save v-hotkey 这个指令可以给组件绑定一个或多个快捷键。你想要通过按下 Escape 键后隐藏某个组件,按住 Control 和回车键再显示它吗?小菜一碟: <template

Hadoop企业开发案例调优场景

需求 (1)需求:从1G数据中,统计每个单词出现次数。服务器3台,每台配置4G内存,4核CPU,4线程。 (2)需求分析: 1G / 128m = 8个MapTask;1个ReduceTask;1个mrAppMaster 平均每个节点运行10个 / 3台 ≈ 3个任务(4    3    3) HDFS参数调优 (1)修改:hadoop-env.sh export HDFS_NAMENOD

嵌入式QT开发:构建高效智能的嵌入式系统

摘要: 本文深入探讨了嵌入式 QT 相关的各个方面。从 QT 框架的基础架构和核心概念出发,详细阐述了其在嵌入式环境中的优势与特点。文中分析了嵌入式 QT 的开发环境搭建过程,包括交叉编译工具链的配置等关键步骤。进一步探讨了嵌入式 QT 的界面设计与开发,涵盖了从基本控件的使用到复杂界面布局的构建。同时也深入研究了信号与槽机制在嵌入式系统中的应用,以及嵌入式 QT 与硬件设备的交互,包括输入输出设

OpenHarmony鸿蒙开发( Beta5.0)无感配网详解

1、简介 无感配网是指在设备联网过程中无需输入热点相关账号信息,即可快速实现设备配网,是一种兼顾高效性、可靠性和安全性的配网方式。 2、配网原理 2.1 通信原理 手机和智能设备之间的信息传递,利用特有的NAN协议实现。利用手机和智能设备之间的WiFi 感知订阅、发布能力,实现了数字管家应用和设备之间的发现。在完成设备间的认证和响应后,即可发送相关配网数据。同时还支持与常规Sof

JAVA智听未来一站式有声阅读平台听书系统小程序源码

智听未来,一站式有声阅读平台听书系统 🌟&nbsp;开篇:遇见未来,从“智听”开始 在这个快节奏的时代,你是否渴望在忙碌的间隙,找到一片属于自己的宁静角落?是否梦想着能随时随地,沉浸在知识的海洋,或是故事的奇幻世界里?今天,就让我带你一起探索“智听未来”——这一站式有声阅读平台听书系统,它正悄悄改变着我们的阅读方式,让未来触手可及! 📚&nbsp;第一站:海量资源,应有尽有 走进“智听

活用c4d官方开发文档查询代码

当你问AI助手比如豆包,如何用python禁止掉xpresso标签时候,它会提示到 这时候要用到两个东西。https://developers.maxon.net/论坛搜索和开发文档 比如这里我就在官方找到正确的id描述 然后我就把参数标签换过来

安卓链接正常显示,ios#符被转义%23导致链接访问404

原因分析: url中含有特殊字符 中文未编码 都有可能导致URL转换失败,所以需要对url编码处理  如下: guard let allowUrl = webUrl.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) else {return} 后面发现当url中有#号时,会被误伤转义为%23,导致链接无法访问

Linux_kernel驱动开发11

一、改回nfs方式挂载根文件系统         在产品将要上线之前,需要制作不同类型格式的根文件系统         在产品研发阶段,我们还是需要使用nfs的方式挂载根文件系统         优点:可以直接在上位机中修改文件系统内容,延长EMMC的寿命         【1】重启上位机nfs服务         sudo service nfs-kernel-server resta

【区块链 + 人才服务】区块链集成开发平台 | FISCO BCOS应用案例

随着区块链技术的快速发展,越来越多的企业开始将其应用于实际业务中。然而,区块链技术的专业性使得其集成开发成为一项挑战。针对此,广东中创智慧科技有限公司基于国产开源联盟链 FISCO BCOS 推出了区块链集成开发平台。该平台基于区块链技术,提供一套全面的区块链开发工具和开发环境,支持开发者快速开发和部署区块链应用。此外,该平台还可以提供一套全面的区块链开发教程和文档,帮助开发者快速上手区块链开发。

Vue3项目开发——新闻发布管理系统(六)

文章目录 八、首页设计开发1、页面设计2、登录访问拦截实现3、用户基本信息显示①封装用户基本信息获取接口②用户基本信息存储③用户基本信息调用④用户基本信息动态渲染 4、退出功能实现①注册点击事件②添加退出功能③数据清理 5、代码下载 八、首页设计开发 登录成功后,系统就进入了首页。接下来,也就进行首页的开发了。 1、页面设计 系统页面主要分为三部分,左侧为系统的菜单栏,右侧