当应用程序关闭/终止时 iOS 中的地理围栏

2023-12-12

我正在研究地理围栏,我想触发“是否输入区域” and “退出区域”当应用程序处于前台或后台状态时它正在工作。但我也想在应用程序处于非活动状态时触发它。我的代码如下:

地理围栏Class.h

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

#define IS_OS_8_OR_LATER ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0)

@interface GeofencingClass : NSObject <UIWebViewDelegate,UIGestureRecognizerDelegate,CLLocationManagerDelegate> {

CLLocationManager *locationManager;
   NSMutableArray *geofences;
}
@property (strong, nonatomic) NSMutableArray *geofences;
@property (nonatomic,retain)CLLocationManager *locationManager;
+(void)GeofencingCoordinatesFromAPI;
+(void)StartGeoFencingWithGeoData:(NSMutableArray *)GeoDataArray;
@end

地理围栏Class.m

    #import "GeofencingClass.h"

    @implementation GeofencingClass
    @synthesize locationManager,geofences;

    +(void)GeofencingCoordinatesFromAPI {

        NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];

        NSInteger Parameter1 = [userDefaults integerForKey:@"Parameter1"];
        NSString* Parameter2 = [userDefaults objectForKey:@"Parameter2"];
        NSString* secretAgent = [userDefaults objectForKey:@"nv_secretAgent"];

        dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
        dispatch_async(queue, ^{
            NSError *error = nil;
            NSString *urlstring = [NSString stringWithFormat:@"https://geofencingapiurl.com?parm1=%ld&parm2=%@&device=ios", (long)Parameter1, Parameter2];
            urlstring = [urlstring stringByReplacingOccurrencesOfString:@"(null)" withString:@""];
        urlstring= [urlstring stringByAddingPercentEscapesUsingEncoding:NSISOLatin1StringEncoding];
            NSURL *url = [NSURL URLWithString:urlstring];
            NSMutableURLRequest* request = [[NSMutableURLRequest alloc] initWithURL:url];
            [request setValue:secretAgent forHTTPHeaderField:@"User-Agent"];
            NSURLResponse* response = nil;
            NSData* jsonData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
            if(!error) {
                //NSData *jsonData = [json dataUsingEncoding:NSASCIIStringEncoding];
                NSMutableDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:&error];

                if ([jsonDict objectForKey:@"Authentication"] && [@"success" isEqualToString:[jsonDict objectForKey:@"Authentication"]]) {
                    geofences = [[jsonDict valueForKey:@"geodata"] mutableCopy];




                    dispatch_async(dispatch_get_main_queue(), ^{

                    [self StartGeoFencingWithGeoData:geofences];
                    });





                } else {
                    NSLog(@"Invalid authentication");
                }
            }
        });
    }

    +(void)StartGeoFencingWithGeoData:(NSMutableArray *)GeoDataArray {

        locationManager = [[CLLocationManager alloc]init];
       // NSLog(@"GeoDataArray = %@",GeoDataArray);
        if(IS_OS_8_OR_LATER) {
            [locationManager requestWhenInUseAuthorization];
            [locationManager requestAlwaysAuthorization];
        }

        locationManager.delegate = self;
        [locationManager startUpdatingLocation];
        locationManager.desiredAccuracy = kCLLocationAccuracyBestForNavigation;
        locationManager.distanceFilter = kCLLocationAccuracyBest;
        NSLog(@"latitude: %f   longitude: %f",locationManager.location.coordinate.latitude,locationManager.location.coordinate.longitude);
        NSLog(@"speed: %f  altitude: %f",locationManager.location.speed,locationManager.location.altitude);

        for (int i = 0; i < [GeoDataArray count]; i++) {
            CLLocationDegrees geo_latitude = [[[GeoDataArray objectAtIndex:i] valueForKey:@"geo_lattitude"] floatValue];
            CLLocationDegrees geo_longitude = [[[GeoDataArray objectAtIndex:i] valueForKey:@"geo_longitude"] floatValue];

            float Radius  = [[[GeoDataArray objectAtIndex:i] valueForKey:@"geo_radius"] floatValue];
            CLLocationCoordinate2D coordinate = CLLocationCoordinate2DMake(geo_latitude, geo_longitude);

            CLCircularRegion *region = [[CLCircularRegion alloc]initWithCenter:coordinate radius:Radius identifier:[[GeoDataArray objectAtIndex:i] valueForKey:@"geo_id"]];
            [locationManager startMonitoringForRegion:region];
        }
    }
    -(void)locationManager:(CLLocationManager *)manager didStartMonitoringForRegion:(CLRegion *)region {

        NSLog(@"Region Monitoring has been started%@",region.identifier);
        [locationManager performSelector:@selector(requestStateForRegion:) withObject:region afterDelay:2];
    }
    -(void)locationManager:(CLLocationManager *)manager didEnterRegion:(CLRegion *)region {
        NSLog(@"Entered in some Region %@",region.identifier);
        for (int i= 0; i <[GeoData count]; i++) {

            NSInteger geo_id =[[[GeoData objectAtIndex:i] valueForKey:@"geo_id"] integerValue];

            if ([region.identifier integerValue] == geo_id) {
                NSInteger geo_action = [[[GeoData objectAtIndex:i] valueForKey:@"geo_action"] integerValue];
                if (geo_action == 0) {
        UILocalNotification *localNotification = [[UILocalNotification alloc] init];
        localNotification.fireDate = [NSDate dateWithTimeIntervalSinceNow:2];
      localNotification.alertBody = @"You are now Entered in a region";
        localNotification.timeZone = [NSTimeZone defaultTimeZone];
        localNotification.soundName = UILocalNotificationDefaultSoundName;
        NSMutableDictionary *userData = [[GeoData objectAtIndex:i] mutableCopy];
        localNotification.userInfo = userData;
     [[UIApplication sharedApplication] scheduleLocalNotification:localNotification];  
                }
            }
        }
    }

    -(void)locationManager:(CLLocationManager *)manager didExitRegion:(CLRegion *)region {
        NSLog(@"Exit from some Region %@",region.identifier);
        for (int i= 0; i <[GeoData count]; i++) {

            NSInteger geo_id =[[[GeoData objectAtIndex:i] valueForKey:@"geo_id"] integerValue];

            if ([region.identifier integerValue] == geo_id) {
                NSInteger geo_action = [[[GeoData objectAtIndex:i] valueForKey:@"geo_action"] integerValue];
                if (geo_action == 1) {
        UILocalNotification *localNotification = [[UILocalNotification alloc] init];
        localNotification.fireDate = [NSDate dateWithTimeIntervalSinceNow:2];
      localNotification.alertBody = @"You are now Exit from region";
        localNotification.timeZone = [NSTimeZone defaultTimeZone];
        localNotification.soundName = UILocalNotificationDefaultSoundName;
        NSMutableDictionary *userData = [[GeoData objectAtIndex:i] mutableCopy];
        localNotification.userInfo = userData;
     [[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
                }
            }
        }
    }
    -(void)locationManager:(CLLocationManager *)manager didDetermineState:(CLRegionState)state forRegion:(CLRegion *)region {

        if (state == CLRegionStateInside){

            [self AlreadyInsideRegion:region];

        } else if (state == CLRegionStateOutside){

            [self NotInRegion:region];

        } else if (state == CLRegionStateUnknown){
            NSLog(@"Unknown state for geofence: %@", region);
            return;
        }
    }
    - (void)AlreadyInsideRegion:(CLRegion *)region {
        NSLog(@"Already in a Region");
    }

    - (void)NotInRegion:(CLRegion *)region {
        NSLog(@"You are Outside from a Region");

    }
    @end

MYAppDelegate.h

#import <UIKit/UIKit.h>

@interface MYAppDelegate : UIResponder <UIApplicationDelegate>
@property (strong, nonatomic) UIWindow *window;
@end

MyAppDelegate.m

#import "MYAppDelegate.h"
#import "GeofencingClass.h"

@interface MYAppDelegate ()
@end

@implementation MYAppDelegate

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

    if ([launchOptions objectForKey:UIApplicationLaunchOptionsLocationKey]) {
        [GeofencingClass GeofencingCoordinatesFromAPI];
    }
    return YES;
}

- (void)applicationWillResignActive:(UIApplication *)application {
}

- (void)applicationDidEnterBackground:(UIApplication *)application {

}

- (void)applicationWillEnterForeground:(UIApplication *)application {

}

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

[GeofencingClass GeofencingCoordinatesFromAPI];
}

- (void)applicationWillTerminate:(UIApplication *)application {

}

-(BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation {

/// Handled Deeplinking here 
    return YES;
}
-(void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
 /// Registered Push Notification Here and it is working fine
}
-(void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error
{
    NSLog(@"Error:%@",error);
}
-(void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
    /// Handled received Push Notification Here and it is working fine
}

-(void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification {
    ///Handled received local push Notification Here and it is working fine
}

如果应用程序位于后台或前台,上面的代码工作正常,但如果我双击主页按钮并从任务中关闭应用程序,然后地理围栏不起作用,任何人都可以帮助我实现这一目标。

Note:我在 iPhone 5s 上测试时使用的是 XCode 7.3.1 和 iOS 9.3。

提前致谢 !!!!!


抱歉,但有点不同: (ADC 网站)

如果您让重大更改位置服务保持运行并且您的 iOS 应用程序随后被暂停或终止,该服务 当新的位置数据到达时,自动唤醒您的应用程序。在 唤醒时间,应用程序被置于后台,您会得到一个 需要少量时间(大约 10 秒)手动重新启动位置 服务并处理位置数据。 (必须手动重启 定位服务在任何待定位置之前在后台运行 可以交付更新,如了解何时开始中所述 位置服务。)

因此 iOS 将唤醒您的应用程序,但您必须: 1)实例化一个新的CLLocationManager 2) 等待第一次回电以使用 geoloc

注意 ADC 状态,您将在后台运行,因此,如果您需要用户将其放在前台,则可以使用本地通知。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

当应用程序关闭/终止时 iOS 中的地理围栏 的相关文章

  • 如果您查看内部,nib 文件到底是什么样子的?

    我刚刚学习 nibs 和 swift 并对某些东西感到好奇 我知道 如果您有一个 main storyboard 文件 则首先加载根视图控制器的笔尖 然后加载该视图控制器下可能分层存在的任何视图 但是 我想知道一些事情 当他们说笔尖已 加载
  • just_audio 无法在 ios flutter 上工作未处理的异常:(-11800)操作无法完成

    我正在尝试从它自己的存储库运行 just audio 示例项目https github com ryanheise just audio tree master just audio example https github com rya
  • NSMutableData 删除字节?

    我可以使用以下命令轻松地将字节添加到 NSMutableData 实例appendData方法 但是我没有看到任何类似的删除数据的方法 我是否忽略了某些内容 或者我是否需要创建一个新对象并仅复制我需要的字节 请参阅以下方法的文档 void
  • 当 iPhone 设备方向朝上/朝下时,我可以判断它是横向还是纵向吗?

    我得到这个代码 如果设备处于左 右横向或上下颠倒状态 它会旋转并显示另一个视图控制器 但如果它的方向朝上或朝下 那么我如何判断它是横向模式还是纵向模式 因为我只想在它面朝上或朝下以及横向模式下旋转 void viewDidAppear BO
  • 使用捏合手势;如何放大用户手指实际“捏”的位置?

    我已经在我的应用程序中的 UIImageView 上实现了 UIPinchGestureRecognizer 但是无论我在图像的哪个位置捏合 它似乎都会放大到同一个位置 有谁知道我如何让它放大到用户实际 捏 的地方 请参阅下面的代码 视图控
  • 相机叠加图片

    edit 3 好消息和坏消息 好消息是 在连接检查器中 通过断开覆盖 UIToolbar 并连接 UIImageview 我看到theKing 但是 坏消息 我没有看到我也需要的 UIToolbar 所以现在的问题是 当用户完成这里操作后
  • 处理 NSPropertyListSerialization 中的 CFNull 对象

    在我的应用程序中 我尝试序列化服务器响应字典并将其写入文件系统 但对于某些响应 我收到错误 属性列表格式无效 原因是服务器响应中的 CFNull 对象 现在 服务器响应将不断变化 因此我没有明确的方法来删除 CFNull 对象 下面是我的代
  • 将 HTML 字符串加载到 UIWebView 中的延迟

    我在导航控制器中有两个视图控制器 第一个视图控制器有一个带有按钮的菜单 按下此按钮将移动到第二个视图控制器并将 html 字符串加载到 UIWebView 中 没有其他东西被加载到 webview 中 只是一个简单的 NSString 其中
  • 无法下载应用程序 - 此时无法下载“APP”

    我的应用程序有 PLUS 版本和常规版本 我使用不同的目标对它们进行存档 我将 ipa 上传到 TestFlight 也上传到我的曲棍球服务器 PLUS 版本总是下载得很好 但普通版本总是给我 无法下载应用程序 错误 我根本没有更改两个版本
  • 处理核心数据中的重复条目

    我有一个允许用户保存收藏夹的应用程序 我正在使用 Core Data 将收藏夹存储为托管对象 我已经编写了一些代码来防止存储重复项的可能性 但我想知道是否有更好的方法来做到这一点 每个收藏夹对象都有一个唯一的 ID 字段 在下面的代码中 我
  • 使用导航控制器在 Storyboard 中呈现视图控制器 - Swift

    我目前在下面的新故事板中显示了一个 viewController var storyboard UIStoryboard UIStoryboard name AccountStoryboard bundle nil var vc Welco
  • Facebook 登录 Apple CNA

    问题 是否可以设置 Facebook 登录以在 CNA 中使用 是否为开发人员提供 CNA 文档 您可以使用任何开发人员工具调试 CNA 屏幕吗 Details 我创建了一个使用电子邮件提交表单或 Facebook 登录按钮的强制门户登录页
  • Xcode 本地化设置中没有加号或减号按钮

    我需要在两天内翻译 iOS 应用程序 但我的 XCode 版本 4 4 和 4 5 Developer Preview 都没有给我添加其他语言的选项 我只能选择单击 Make localized 但我只能选择英语 选择它后 Xcode 中的
  • SDWebImage 显示缓存中图像的占位符

    在 iOS 5 1 项目 iPad 中使用 SDWebImage 3 我们展示相当大的图像 700x500 并且我们有很多图像 1000 我们预取图像并缓存到磁盘 然后允许用户浏览它们 效果很好 除了当您浏览图像时 您总是会看到占位符显示一
  • 带约束的 Swift 动画

    是否可以通过改变约束来制作 UIView 动画 基本上 我想要动画myv UIView 具有 x y 高度和宽度约束 使用 UIView animateWithDuration 1 5 通过改变旧的限制 是的 这是可能的 你可以这样做 fu
  • 将 Facebook 图片 URL 上传到 Firebase 存储

    我正在尝试将用户的 Facebook 个人资料图片上传到 Firebase 存储 let dictionary result as NSDictionary let data dictionary objectForKey data let
  • 更改选项卡栏应用程序中的 UITableViewController 样式

    我有一个带有 4 个选项卡的选项卡栏 iPhone 应用程序 在界面生成器中 我为每个选项卡设置视图控制器 我想将一个 UITableViewController 的样式从普通样式更改为分组样式 我用这样的方式替换 init 方法 id i
  • Objective-C 声明的 @property 属性(非原子、复制、强、弱)

    有人可以向我详细解释一下我何时必须使用每个属性 nonatomic copy strong weak等等 对于声明的属性 并解释每个属性的作用是什么 某种例子也很好 我正在使用ARC 非原子的 Nonatomic https stackov
  • 如何在 XCode5 中将部署目标更改为 5.1.1 [重复]

    这个问题在这里已经有答案了 我正在一个项目中工作 我需要支持 iOS 5 1 1 但在 部署目标 的下拉菜单中我没有 5 1 1 作为选项 我的问题是如何将 iOS 5 1 1 添加为部署目标 我将非常感谢你的帮助 如果您愿意 您可以在框中
  • 桌面上的 AVAudioSession?

    在 mac 桌面上 我试图录制系统声音 以及可选的麦克风声音 但一开始我只是录制系统声音 我正在遵循本指南 https www appcoda com ios avfoundation framework tutorial https ww

随机推荐

  • 在 IIS7 中配置 ASP.NET

    有没有办法在 IIS7 中配置 ASP NET 我知道这一定是一个愚蠢的问题 但在 IIS7 中我看到了 ASP 的图标 这是经典 ASP 的配置吗 IIS 7 与以前的版本有很大不同 尤其是在 ASP NET 方面 在以前的版本中 ASP
  • 在VS2013中从SVN更新后,数据集Designer.cs生成Designer1.cs

    从 SVN 数据集 Designer cs 文件进行更新后 我遇到一个奇怪的问题生成另一个具有不同名称的文件 例如 test Designer cs 更新后重命名为 test1 Designer cs 我遵循发现的建议here 但无法再次生
  • 触摸开始无法检测到所触摸的内容

    我正在使用 NSTimer 构建一个旋转横幅来跟踪当前图像 该图像是由 5 个不同图像制作而成的动画 我设置了一个 TouchesBegan 来在有人单击横幅时继续处理横幅上的触摸事件 我的概念验证有效 但将其转移到另一个项目中时 它就崩溃
  • Google 重定向 URI 不允许使用片段 URL 的解决方法

    我使用mac开发一个MEAN堆栈项目 我的网页https localhost 3000 login and https localhost 3000 new工作 请注意 我的所有页面都需要有 中间工作 https localhost 300
  • 无法加载模块描述符类:找不到类“com.google.android.gms.dynamite.descriptors.com.google.firebase.auth.ModuleDescriptor”

    所以我是新手 我尝试使用 Firebase 9 0 0 实现电子邮件 密码身份验证 因此该活动要么执行注册操作 要么执行登录操作 登录操作运行顺利 我可以在 Firebase 控制台上看到更新 但是当我尝试注册新用户时 出现此错误 E Dy
  • Java:全局异常处理程序

    有没有办法在 Java 中创建全局异常处理程序 我想这样使用 When an exception is thrown somewhere in the WHOLE program exit 处理程序可能无法捕获抛出的异常try catch
  • 禁用列排序不适用于多个 angularjs 数据表

    我正在使用多个 angularjs 数据表 并在每次用户从下拉列表中选择一个选项时生成一个新表 根据用户的选择 我发出 http 请求以从数据库中获取新数据 对于每个表 我都有不同的dtColumnDefs 是动态设置的 因为我的表列标题是
  • 如何在 PHP 中随机化数组

    我有一个像这样的数组 arr 1 2 4 5 6 7 8 9 但我需要这个数组的随机版本 我正在使用该函数shuffle像这样 random shuffle arr 但这个函数只是返回true而不是数组的随机版本 shuffle 此函数对数
  • Django ModelForm ChoiceField 不显示实例数据

    我有一个ModelForm我在其中设置了几个字段的类ChoiceField 对于我的一个观点 我想从我的ModelForm从数据库中模型实例中提取的类 如下所示 form MyModel instance model instance 当我
  • ItemsControl 与视图模型的多个数据模板

    是否可以将以画布为模板的项目控件绑定到多个数据模板 我有 2 个集合 根据类型我想在画布上显示不同的控件 我不确定 但我可以考虑一个具有 2 个 ObservableCollections 的 Viewmodel 例如 如果我有 形状 和
  • 从字符串执行命令

    在 r 中使用 scopus 检索引用 library rscopus auth token header please add akey please add set api key akey x abstract retrieval 1
  • 为什么要在 PHP 中使用模板系统? [关闭]

    Closed 这个问题是基于意见的 目前不接受答案 为什么要在 PHP 中使用模板系统 我的问题背后的原因是 PHP 本身就是功能丰富的模板系统 为什么我应该安装另一个模板引擎 到目前为止我发现的唯一两个优点是 更简洁的语法 有时 模板引擎
  • Microsoft.AspNetCore.WebUtilities 超出行长度限制 100

    我一直在尝试自动化测试 将文本文件上传到使用 flowjshandler 的 Web api 所有这些都在 c net core 和 linux docker 容器中运行 从 Visual Studio 运行时 测试程序毫无例外地上传文件
  • 谷歌应用程序邀请 - 短信未发送

    我尝试寻找解决方案 但还没有运气 我正在尝试使用谷歌应用程序邀请来邀请朋友使用我的应用程序 android 电子邮件已发送 但短信未发送 我没有收到任何错误消息 事实上我实际上收到一条消息 表明邀请已发送 我还尝试向我的应用程序添加短信权限
  • '(引用引用)在方案中

    我正在尝试自学方案 谁能告诉我为什么 quote quote 将输出 quote and quote quote 将输出 quote 非常感谢 这个表达式 quote quote 扩展后
  • Swift 3 CVarArg 被多次传递的问题

    我在 swift 3 中有以下代码 class StringUtility static func Localizer tableName String gt key String params CVarArg gt String retu
  • 将剪贴板中的图像粘贴到 Excel 中的单元格

    我想使用 vba 将图像从剪贴板粘贴到 Excel 单元格 我可以找到这样的代码 If My Computer Clipboard ContainsImage Then Dim grabpicture My Computer Clipboa
  • Visual Studio 2010 数据源选项中缺少 SQLite 数据库文件类型

    我按照以下说明在 Visual Studio 2010 上安装了 x86 x64 官方 SQLite NuGet 包 http www tsjensen com blog post 2012 11 10 SQLite on Visual S
  • 可以同时从多个程序打开和访问伯克利数据库吗?

    根据 Berkeley 文档 数据库的事务 TS 和并发数据存储版本 多个线程可以访问 和更改 数据库 这是否也意味着我可以有两个程序链接到伯克利 客户端 并让它们访问相同的数据库文件而不会出现任何问题 我问 因为对于单独的数据库服务器来说
  • 当应用程序关闭/终止时 iOS 中的地理围栏

    我正在研究地理围栏 我想触发 是否输入区域 and 退出区域 当应用程序处于前台或后台状态时它正在工作 但我也想在应用程序处于非活动状态时触发它 我的代码如下 地理围栏Class h import