在iBeacon上调用Web服务在后台找到事件

时间:2015-04-04 11:42:09

标签: ios ibeacon

我的客户询问,当顾客走过他的商店时,他会收到一封今天特价的电子邮件,即使应用程序没有运行。

我的问题是:如果应用程序被iBeacon事件唤醒,iOS是否允许调用restservice?

我尝试播放系统声音以模拟restservice调用,但这不起作用。仅当应用程序位于前台时。

为了让您知道我到目前为止如何设计我的Beaconhandler,这是我的代码。也许某人有想法改进它:

#import "BeaconHandler.h"

@interface BeaconHandler ()

@property (strong, nonatomic) CLLocationManager *locationManager;
@property CLProximity lastProximity;

@end


@implementation BeaconHandler


-(void) startMonitoring{

    if(![self monitoringIsAllowed]){
        return;
    }

    [self initLocationManager];
    [self startMonitoringBeacons:[self beaconIDsToMonitor]];
}

-(BOOL) monitoringIsAllowed{

    //TODO configuration

    return YES;
}

-(NSDictionary*) beaconIDsToMonitor{

    //TODO: load beacons from server

    return @{@"region1":[[NSUUID alloc] initWithUUIDString:@"B9407F30-F5F8-466E-AFF9-25556B57FE6D"],
             @"region2":[[NSUUID alloc] initWithUUIDString:@"B9407F30-F5F8-466E-AFF9-25556B57FE6A"]
             };
}


-(void) initLocationManager{

    self.locationManager = [[CLLocationManager alloc] init];

    if([self.locationManager respondsToSelector:@selector(requestAlwaysAuthorization)]) {
        [self.locationManager requestAlwaysAuthorization];
    }
    self.locationManager.delegate = self;
    self.locationManager.pausesLocationUpdatesAutomatically = NO;
}

-(void) startMonitoringBeacons:(NSDictionary*)beacons{

    for (NSString* beaconIdentifier in beacons.allKeys) {
        NSUUID *beaconUUID = beacons[beaconIdentifier];

        CLBeaconRegion *beaconRegion = [[CLBeaconRegion alloc] initWithProximityUUID:beaconUUID identifier:beaconIdentifier];
        beaconRegion.notifyEntryStateOnDisplay = YES;

        [self.locationManager startMonitoringForRegion:beaconRegion];
        [self.locationManager startRangingBeaconsInRegion:beaconRegion];
    }

    [self.locationManager startUpdatingLocation];
}


//TODO replace by backend call
-(void)sendLocalNotificationWithMessage:(NSString*)message{

    UILocalNotification *notification = [[UILocalNotification alloc] init];
    notification.alertBody =message;

    [[UIApplication sharedApplication] presentLocalNotificationNow:notification];

}


#pragma CLLocationDelegate



-(void)locationManager:(CLLocationManager *)manager didRangeBeacons:(NSArray *)beacons inRegion:(CLBeaconRegion *)region {

    for (CLBeacon *beacon in beacons) {

        if(beacon.proximity == self.lastProximity ||
           beacon.proximity == CLProximityUnknown) {
            return;
        }
        self.lastProximity = beacon.proximity;

        [self sendLocalNotificationWithMessage:[NSString stringWithFormat:@"You are inside region %@", region.identifier]];
    }
}

1 个答案:

答案 0 :(得分:3)

是的,这是可能的。我可以确认我已经在iOS上成功完成了这项工作。有几个提示让它在后台运行:

  1. 首先让它在前台工作。

  2. 进入/退出某个区域后,您只有5秒的后台运行时间,因此请确保您的网络服务快速返回。

  3. 将NSLog语句添加到回调中,以确定后台有什么和没有完成。

  4. 如果上述方法无效,请在回调中发布您的代码。