为什么区域内的UILocalNotification不会触发?

时间:2014-07-10 01:28:52

标签: objective-c core-location uilocalnotification ios8

我已经按照WWDC 2014 session "What's New in iOS Notifications"中给出的示例设置了一个UILocalNotification投放,当超过区域的边界时。

然而,我的通知永远不会在运行iOS beta 3的设备或模拟器上触发。当我使用fireDate而不是region进行测试时,通知正常工作(不是同时进行 - &# 39;不允许)。

我在NSLocationWhenInUseUsageDescription中设置了Info.plist

这是我的Obj-C代码:

#import "ViewController.h"
#import <CoreLocation/CoreLocation.h>

@interface ViewController () <CLLocationManagerDelegate>

@property (nonatomic, strong) CLLocationManager *locationManager;
@property (nonatomic, strong) CLLocation *notifLocation;

@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];

    // test points at Apple HQ
    self.notifLocation = [[CLLocation alloc] initWithLatitude:37.331741 longitude:-122.030333];

    [self setupLocationMonitoring];
}

- (void) setupLocationMonitoring
{
    if (self.locationManager == nil) {
        self.locationManager = [[CLLocationManager alloc] init];
    }

    self.locationManager.delegate = self;
    self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    self.locationManager.distanceFilter = 10; // meters

    // iOS 8+ request authorization to track the user’s location
    if ([self.locationManager respondsToSelector:@selector(requestWhenInUseAuthorization)]) {
        [self.locationManager requestWhenInUseAuthorization];
    }

    [self.locationManager startUpdatingLocation];
}

- (void)registerLocationNotification
{
    UILocalNotification *locNotification = [[UILocalNotification alloc] init];
    locNotification.alertBody = @"Hello!";

    // doesn't work
    locNotification.regionTriggersOnce = NO;
    locNotification.region = [[CLCircularRegion alloc] initWithCenter:self.notifLocation.coordinate radius:50 identifier:@"PlaceName"];

    // works:
//    locNotification.fireDate = [NSDate dateWithTimeIntervalSinceNow:10];

    UIApplication *application = [UIApplication sharedApplication];
    [application cancelAllLocalNotifications];
    [application scheduleLocalNotification:locNotification];
}

#pragma mark - CLLocationManagerDelegate

- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status
{
    // check status to see if we’re authorized
    BOOL canUseLocationNotifications = (status == kCLAuthorizationStatusAuthorizedWhenInUse);
    if (canUseLocationNotifications) {
        [self registerLocationNotification];
    }
}

@end

注意:这个问题是关于iOS 8的新位置通知,而不是关于旧版iOS上的区域监控。

1 个答案:

答案 0 :(得分:4)

您的代码适用于我。以下是iPhone Simulator的步骤:

1)打开模拟器应用程序,然后从顶部菜单Debug - &gt;中选择以下选项。 Location - &gt; Custom Location并将代码中的坐标放在那里:(37.331741,-122.030333)

2)在iPhone Simulator

上运行您的Xcode项目

3)背景应用

4)打开相同的顶级菜单项Debug - &gt; Location但请将其从Custom Location更改为Freeway DriveCity Run。使用City Run / Freeway DriveCustom Location

进行游戏

当我按照这些步骤操作时,我会看到通知。看起来它不起作用,以防适当的坐标是起始坐标,但是当坐标从其他坐标变为适当时它起作用。