【发布时间】:2014-05-21 16:18:40
【问题描述】:
我正在使用自定义 BeaconManager 委托,因此信标范围不是由视图控制器的生命周期决定的。一切正常,但每隔一段时间(1-2 天)信标测距将停止工作,并且 didRangeBeacons 永远不会被调用。解决此问题的唯一方法是重置我的 iPhone,一旦我这样做,它就可以完美运行。下面是我正在使用的代码。基本流程是,当我的 ViewController 调用 ViewDidLoad 时,它会向 AppDelegate 发送一个通知,告诉它开始对信标进行测距,但我从不告诉它停止,因为无论用户导航到哪里,我都希望它继续为信标测距在应用程序中。我想知道我的代码是否导致了这种情况,或者这只是蓝牙的一个错误。感谢您的帮助!
BeaconManager.m
#import "BeaconManager.h"
#import "AppDelegate.h"
@interface BeaconManager()<CLLocationManagerDelegate>
@property (nonatomic, strong) CLLocationManager *locationManager;
@property (nonatomic, strong) CLBeaconRegion *beaconRegion;
@end
@implementation BeaconManager
+ (id)sharedManager
{
static BeaconManager *sharedBeaconManager = nil;
static dispatch_once_t once;
dispatch_once(&once, ^{
sharedBeaconManager = [[self alloc] init];
});
return sharedBeaconManager;
}
- (id)init
{
self = [super init];
if(self)
{
self.locationManager = [[CLLocationManager alloc] init];
self.locationManager.delegate = self;
}
return self;
}
- (void)startBeaconMonitoring:(NSString*)forUUID
{
NSUUID * uuid = [[NSUUID alloc] initWithUUIDString:forUUID];
self.beaconRegion = [[CLBeaconRegion alloc] initWithProximityUUID:uuid identifier:@"com.beacons.publicRegion"];
[self.locationManager startMonitoringForRegion:self.beaconRegion];
[self.locationManager startRangingBeaconsInRegion:self.beaconRegion];
}
- (void)stopBeaconMonitoring
{
//Stop the region monitoring
if(self.locationManager != nil && self.beaconRegion != nil) {
[self.locationManager stopRangingBeaconsInRegion:self.beaconRegion];
}
}
#pragma mark - CLLocationManagerDelegate
- (void)locationManager:(CLLocationManager *)manager didRangeBeacons:(NSArray *)beacons inRegion:(CLBeaconRegion *)region
{
self.beacons = beacons;
if(self.delegate != nil) {
[self.delegate beaconManager:self didRangeBeacons:self.beacons];
}
}
@end
ViewController.m
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
[[NSNotificationCenter defaultCenter] postNotificationName:@"startRanging" object:nil userInfo:nil];
}
AppDelegate.m
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(startRangingForZombies) name:@"startRanging" object: nil];
return YES;
}
- (void)startRanging
{
//Start the beacon region monitoring when the controller loads
BeaconManager *beaconManager = [BeaconManager sharedManager];
beaconManager.delegate = self;
[beaconManager startBeaconMonitoring:@"1234-54324-34242-34242-43243"];
}
【问题讨论】:
标签: ios objective-c bluetooth delegates ibeacon