【问题标题】:Geofencing in iOS When App is closed / Killed当应用程序关闭/被杀死时,iOS 中的地理围栏
【发布时间】:2016-12-27 11:30:01
【问题描述】:

我正在研究地理围栏,我想在应用程序处于前台或后台状态时触发 "didEnterRegion" 和 "didExitRegion"。但是我也想在应用程序处于非活动状态时触发它。我的代码如下:

GeofencingClass.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

GeofencingClass.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
}

如果应用程序在后台或前台,上面的代码可以正常工作,但是如果我双击 Home Button 并从任务中关闭应用程序,那么地理围栏不起作用,任何人都可以帮助我实现这个目标.

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

提前谢谢!!!!

【问题讨论】:

  • 是的。不要双击并终止应用程序。如果你这样做,它会告诉 iOS 你不希望应用程序运行
  • 所以如果app处于InActive状态它无论如何都不会触发它?
  • 如果它被暂停(只需按下主页按钮并转到另一个应用程序),那么您将收到区域通知,但如果您终止应用程序则不会。不过,您在代码中做了一些奇怪的事情。您应该在使用时请求或始终授权,而不是两者(在您的情况下您总是想要)并且您不想开始更新位置或最佳准确性;这会杀死电池
  • 有什么办法吗?
  • 好的,我将删除 [locationManager requestWhenInUseAuthorization];

标签: ios objective-c iphone xcode7


【解决方案1】:

对不起,但有点不同: (ADC 网站)

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

所以 iOS 会唤醒您的应用,但您必须: 1) 实例化一个新的 CLLocationManager 2) 等到第一次回调使用 geoloc

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

【讨论】:

  • 感谢 ingconti 我正在尝试但无法做到。您能否为我提供上述解决方案的示例代码或任何参考链接。
  • 本地通知代码或重要位置更新的geloc代码?请写在可能的邮件上。
猜你喜欢
  • 1970-01-01
  • 2015-06-22
  • 1970-01-01
  • 1970-01-01
  • 2018-03-18
  • 1970-01-01
  • 2013-06-14
  • 1970-01-01
相关资源
最近更新 更多