美文网首页
iOS后台持续定位【转】

iOS后台持续定位【转】

作者: 小船2022 | 来源:发表于2022-09-28 08:37 被阅读0次

1.开去后台模式:

![image](https://img.haomeiwen.com/i937405/f6389f976cba668e.png?imageMogr2/auto-orient/strip|imageView2/2/w/543/format/webp)

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>

*  (void)applicationDidBecomeActive:(UIApplication *)application {

    if([CLLocationManager significantLocationChangeMonitoringAvailable])

    {

    ViewController*vc=(ViewController *)self.window.rootViewController;

    ```

      [vc.manager stopMonitoringSignificantLocationChanges];

      [vc.manager startUpdatingLocation];

    ```

    }

    else

    {

    NSLog(@"significant Location Change not Available");

    }

    }</pre>

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

AppDelegate.m

<pre>

# import "AppDelegate.h"

# import <CoreLocation/CoreLocation.h>

# import "ViewController.h"

@interface AppDelegate ()

@end

@implementation AppDelegate

*  (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    self.window.rootViewController=[ViewController new];

    return YES;

    }

*  (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");

    }

    }

*  (void)applicationDidBecomeActive:(UIApplication *)application {

    if([CLLocationManager significantLocationChangeMonitoringAvailable])

    {

    ViewController*vc=(ViewController *)self.window.rootViewController;

    ```

      [vc.manager stopMonitoringSignificantLocationChanges];

      [vc.manager startUpdatingLocation];

    ```

    }

    else

    {

    NSLog(@"significant Location Change not Available");

    }

    }

@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

*  (void)viewDidLoad

    {

    [super viewDidLoad];

    PHFetchResult *result=[PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeAlbum subtype:PHAssetCollectionSubtypeAlbumRegular options:nil];

    for(PHAssetCollection *collection in result)

    {

    if ([collection.localizedTitle isEqualToString:@"FGG"]) {

    NSLog(@"%@",collection);

    }

    }

    //1.创建定位管理对象

    _manager=[[CLLocationManager alloc]init];

    _coder=[[CLGeocoder alloc]init];

    //2.设置属性 distanceFilter、desiredAccuracy

    _manager.distanceFilter=kCLDistanceFilterNone;//实时更新定位位置

    _manager.desiredAccuracy=kCLLocationAccuracyBest;//定位精确度

    //iOS8之后需要设置Info.plist,NSLocationAlwaysUsageDescription=YES以开启总是使用定位

    if([_manager respondsToSelector:@selector(requestAlwaysAuthorization)])

    {

    [_manager requestAlwaysAuthorization];

    }

    //该模式是抵抗程序在后台被杀,申明不能够被暂停

    _manager.pausesLocationUpdatesAutomatically=NO;

    //3.设置代理

    _manager.delegate=self;

    //4.开始定位

    [_manager startUpdatingLocation];

    //5.获取朝向

    [_manager startUpdatingHeading];

}

# 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>

作者:CGPointZero

链接:https://www.jianshu.com/p/4e30b0af8f51

来源:简书

著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

相关文章

  • IOS后台定位以及位置上传方案

    IOS后台定位以及位置上传方案 iOS定位原理和使用建议 iOS后台持续定位并定时上传 iOS 通过定位获取常驻后...

  • iOS 后台持续定位

    在日常的工作开发中,有时会遇到需要在后台持续运行的需求。对于这个需求,安卓实现起来比较简单,而iOS来说就比较复杂...

  • IOS后台持续定位

    因为业务需求,项目需要一直定位物流司机位置。主要难点就是APP最小化进入后台,自动被系统挂起,定位停止。 网上找了...

  • iOS后台持续定位

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

  • iOS 后台持续定位

    环境: xcode8.2.11.Target->Capabilities->Background modes,勾选...

  • iOS 后台持续定位

    前言 前文讲到程序推到后台的运行情况iOS 对APP推到后台运行时长的探究,主要还是想做个后台定位,希望APP在按...

  • iOS后台持续定位

    1.开去后台模式: 2.在plist中加入NSLocationAlwaysUsageDescription这个键,...

  • iOS开发——后台持续定位

    项目有需求,要求app能够在后台持续定位,并根据某些情况发送本地推送。 首先,打开项目的后台定位模式,TARGET...

  • iOS后台持续定位实现方法

    1.选中target-->Gapability,打开Background Modes模式,并勾选Location ...

  • iOS 后台持续定位不生效

    问题:系统升级到iOS11之后,发现APP不提示否允许始终访问位置,iBeacon不起作用。我查看了一下手机隐私设...

网友评论

      本文标题:iOS后台持续定位【转】

      本文链接:https://www.haomeiwen.com/subject/amvtartx.html