過去我所想的點子,只要偵測到iBeacon就進行對應事件。這次幫朋友阿強實現點子,發現同一UUID的iBeacon,只會觸發一次didEnter和didExit,用圖示來說明比較清楚~
可以看到兩顆iBeacon重疊偵測範圍,只要偵測到其中一顆,就只會觸發一次didEnter和didExit。這與Android測試得到的結果不同,iOS已經幫我們處理好,再把處理過的結果回傳給開發者使用,這是限制也是方便~
Android會觸發兩次(每顆iBeacon各一次),可能也叫做didEnter和didExit。阿強測試比較過後,發現iOS偵測速度比Android慢,這其實是因為iOS SDK會有數秒鐘偵測週邊iBeacon並處理。
於是研究如何實現各別觸發didEnter和didExit,結論就是設定不同的Region ID,範例:
/** Theme: iBeacon Detect Many Regions IDE: Xcode 9 Language: Objective C Date: 107/07/14 Author: HappyMan Blog: https://cg2010studio.com/ */ -(void)setupService { self.locationManager = [[CLLocationManager alloc] init]; self.locationManager.delegate = self; [self.locationManager requestAlwaysAuthorization]; // Create a NSUUID with the same UUID as the broadcasting beacon NSUUID *uuid = [[NSUUID alloc] initWithUUIDString:@"fda50693-a4e2-4fb1-afcf-c6eb07647825"]; NSUUID *uuid2 = [[NSUUID alloc] initWithUUIDString:@"fda50693-a4e2-4fb1-afcf-c6eb07647826"]; // Setup a new region with that UUID and same identifier as the broadcasting beacon self.myBeaconRegion = [[CLBeaconRegion alloc] initWithProximityUUID:uuid identifier:@"com.happy.beacon"]; self.myBeaconRegion.notifyEntryStateOnDisplay = YES; self.myBeaconRegion.notifyOnExit = YES; self.myBeaconRegion.notifyOnEntry = YES; self.myBeaconRegion2 = [[CLBeaconRegion alloc] initWithProximityUUID:uuid2 identifier:@"com.happy.beacon2"]; self.myBeaconRegion2.notifyEntryStateOnDisplay = YES; self.myBeaconRegion2.notifyOnExit = YES; self.myBeaconRegion2.notifyOnEntry = YES; // Tell location manager to start monitoring for the beacon region [self.locationManager startMonitoringForRegion:self.myBeaconRegion]; [self.locationManager startRangingBeaconsInRegion:self.myBeaconRegion]; [self.locationManager startMonitoringForRegion:self.myBeaconRegion2]; [self.locationManager startRangingBeaconsInRegion:self.myBeaconRegion2]; }
另繪製如圖所示:
我在App前景做測試,會不斷觸發此API:
-(void)locationManager:(CLLocationManager*)manager
didRangeBeacons:(NSArray*)beacons
inRegion:(CLBeaconRegion*)region
無論beacons是否有東西,經Log觀察到,每個Region每一秒都會觸發此API。
Printing description of beacons:
<__NSArrayM 0x111dde450>(
CLBeacon (uuid:FDA50693-A4E2-4FB1-AFCF-C6EB07647825, major:10034, minor:61715, proximity:1 +/- 0.09m, rssi:-40)
)
Printing description of region:
CLBeaconRegion (identifier:’com.happy.beacon2′, uuid:FDA50693-A4E2-4FB1-AFCF-C6EB07647826, major:(null), minor:(null))
Printing description of region:
CLBeaconRegion (identifier:’com.happy.beacon’, uuid:FDA50693-A4E2-4FB1-AFCF-C6EB07647825, major:(null), minor:(null))
將兩個iBeacon放在房間(一個是iPhone 6s+模擬,一個是真的iBeacon裝置),我走出去門外20公尺,再走回來房間,在螢幕暗掉情況下測試~
結果就如同網路高人指點那樣:)~
參考:iBeacon detection rate on iOS、Is it possible to use beacon ranging in the background?。
隨意留個言吧:)~