Unity+IOS GPS后台更新GPS数据

本文介绍如何在Unity中利用iOS原生代码实现后台GPS数据的持续获取。通过配置Info.plist文件、添加CoreLocation库及修改UnityAppController.h/.mm文件,实现了GPS的启动、停止及后台更新。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Unity自带了Input.Location的方式去获取GPS数据,但是如果你想后台获取GPS数据是没法实现的。

那就只能使用IOS原生代码去实现这个功能了。方法也很简单。

1.设置Info.plist

<key>NSLocationAlwaysUsageDescription</key>

<string>I need Location</string>

<key>NSLocationWhenInUseUsageDescription</key>

<string></string>

<key>UIBackgroundModes</key>

<array>

<string>fetch</string>

<string>location</string>

</array>


2.添加CoreLocation库.


3.修改UnityAppController.h文件(蓝色部分内容)

#import <QuartzCore/CADisplayLink.h>

#import <CoreLocation/CoreLocation.h>

#include "PluginBase/RenderPluginDelegate.h"


@class UnityView;

@class DisplayConnection;


@interface UnityAppController :NSObject<CLLocationManagerDelegate>


4.修改UnityAppController.mm文件

//添加内容

//>>>>>>>>>>>>>>>>>>>>>>

static UnityAppController *globalSelf;

CLLocationManager *locationManager;

CLLocation *myOldLocation;

extern "C"void StartGPSUpdate(){

    locationManager = [[CLLocationManager alloc] init];

    locationManager.delegate=globalSelf;

    locationManager.desiredAccuracy=kCLLocationAccuracyBest;//定位精度

    locationManager.distanceFilter=1;//kCLDistanceFilterNone定时更新  1:每隔一米更新一次

    locationManager.pausesLocationUpdatesAutomatically=NO;//设置是否允许系统自动暂停定位,这里要设置为NO,刚开始我没有设置,后台定位持续20分钟左右就停止了!

    [locationManager requestWhenInUseAuthorization];

    [locationManager startMonitoringSignificantLocationChanges];

    if(![CLLocationManager locationServicesEnabled]){

        NSLog(@"请开启定位:设置 >隐私 > 位置 >定位服务");

    }

    

    if ([[[UIDevice currentDevice] systemVersion] floatValue] >=8) {

        //[_locationManager requestWhenInUseAuthorization];//⓵只在前台开启定位

        [locationManager requestAlwaysAuthorization];//⓶在后台也可定位

    }

    

    // 5.iOS9新特性:将允许出现这种场景:同一app中多个location manager:一些只能在前台定位,另一些可在后台定位(并可随时禁止其后台定位)。

    if ([[[UIDevice currentDevice] systemVersion] floatValue] >=9) {

        locationManager.allowsBackgroundLocationUpdates =YES;

    }

    

    [locationManager startUpdatingLocation];

    NSLog(@"start gps update");

}

extern "C"void StopGPSUpdate(){

    [locationManager stopUpdatingLocation];

    NSLog(@"stop gps update");

}




- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation

{

    CLLocation *currentLocation = newLocation;

    myOldLocation=currentLocation;

    NSString *strResult=@"didUpdateToLoation";

    if (currentLocation !=nil) {

        NSString *lat = [NSString stringWithFormat:@"%.8f", currentLocation.coordinate.latitude];

        NSString *lon=[NSString stringWithFormat:@"%.8f",currentLocation.coordinate.longitude];

        NSString *ele=[NSString stringWithFormat:@"%0.8f",currentLocation.altitude];

        strResult=[NSString stringWithFormat:@"{\"state\":\"UpdateGPS\",\"latitude\":\"%@\",\"longitude\":\"%@\",\"altitude\":\"%@\" }",lat,lon,ele];

        

         UnitySendMessage("GPSSDK","IOSGPSUpdate", [strResult UTF8String]);

        /*

         _longitudeLabel.text = [NSString stringWithFormat:@"%.8f", currentLocation.coordinate.longitude];

         _latitudeLabel.text = [NSString stringWithFormat:@"%.8f", currentLocation.coordinate.latitude];

         

         _verticalAccuracy.text=[NSString stringWithFormat:@"%.8f",currentLocation.altitude];

         _horizontalAccuracy.text=[NSString stringWithFormat:@"%.8f",currentLocation.horizontalAccuracy];

         _vertical.text=[NSString stringWithFormat:@"%.8f",currentLocation.verticalAccuracy];*/

    }

    

    // Reverse Geocoding

    NSLog(@"Resolving the Address:%@",strResult);

    

}


//<<<<<<<<<<<<<<<<<<<<<<<


- (id)init

{

if( (self = [super init]) )

{

// due to clang issues with generating warning for overriding deprecated methods

// we will simply assert if deprecated methods are present

// NB: methods table is initied at load (before this call), so it is ok to check for override

NSAssert(![self respondsToSelector:@selector(createUnityViewImpl)],

@"createUnityViewImpl is deprecated and will not be called. Override createUnityView"

);

NSAssert(![self respondsToSelector:@selector(createViewHierarchyImpl)],

@"createViewHierarchyImpl is deprecated and will not be called. Override willStartWithViewController"

);

NSAssert(![self respondsToSelector:@selector(createViewHierarchy)],

@"createViewHierarchy is deprecated and will not be implemented. Use createUI"

);

}

    globalSelf=self;//注意一定要添加该行代码

returnself;

}

这样就完成了GPS开启停止以及后台更新GPS了。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值