No post iBeacon: tudo que você precisa saber, falamos sobre a nova tecnologia lançada pela Apple q promete revolucionar o sistema de marketing baseado na localização. Hoje iremos ensinar a criar um tutorial mostrando o iBeacon.
Tutorial iBeacon
Conforme comentamos no post anterior, um iBeacon possui diversas informações que o definem, sendo 3 delas as mais importantes. São elas: UUID, minor e major. Não irei entrar em detalhes sobre a utilidade de cada um, mas caso tenha dúvidas pode consultar o nosso post.
Para explicar o funcionamento de um iBeacon iremos fazer um simples aplicativo, composto por 2 telas, conforme a imagem a seguir da Storyboard do projeto.
Para começar a utilizar o iBeacon, devemos adicionar ao projeto algumas bibliotecas fundamentais, são elas:
– CoreBluetooth.framework
– CoreLocation.framework
– CoreGraphics.framework
– UIKit.framework
– Foundation.framework
Conforme citado anteriormente nosso aplicativo será composto por duas telas: A primeira será a responsável em monitorar as informações captadas do iBeacon, já a segunda será a de configuração.
Vamos começar pela segunda tela, a de configuração, que iremos chamar a partir de agora: TransmitViewController.
Bom a primeira etapa é importar as bibliotecas que iremos utilizar nessa View Controller:
TransmitViewController.h
#import <CoreLocation/CoreLocation.h> #import <CoreBluetooth/CoreBluetooth.h>
Em seguida iremos declarar três objetos, e atribuir o delegate: CBPeripheralManagerDelegate a classe..
@interface TransmitViewController : UIViewController <CBPeripheralManagerDelegate>
@property (strong, nonatomic) CLBeaconRegion *beaconRegion; @property (strong, nonatomic) NSDictionary *beaconPeripheralData; @property (strong, nonatomic) CBPeripheralManager *peripheralManager;
Mais pra frente iremos entender mais detalhadamente o uso de cada um. Por fim, temos que criar as labels responsável em reportar as informações do iBeacon e o botão que irá inicia-lo.
@property (weak, nonatomic) IBOutlet UILabel *uuidLabel; @property (weak, nonatomic) IBOutlet UILabel *majorLabel; @property (weak, nonatomic) IBOutlet UILabel *minorLabel; @property (weak, nonatomic) IBOutlet UILabel *identityLabel; - (IBAction)startBeaconAction:(UIButton *)sender;
Agora já podemos finalizar a View Controller de configuração, inicializando, alocando memória e realizando algumas configurações nos objetos criados:
A primeira função é responsável em atribuir ao objeto que irá monitorar o iBeacon suas informações como UUID, major e minor.
- (void)initBeacon {
NSUUID *uuid = [[NSUUID alloc] initWithUUIDString:@"23542266-18D1-4FE4-B4A1-23F8195B9D39"];
self.beaconRegion = [[CLBeaconRegion alloc] initWithProximityUUID:uuid
major:1
minor:1
identifier:@"iMobilis.com.Conrado"];
}
Por fim, definimos a função do botão, que irá iniciar o monitoramento.
- (IBAction)startBeaconAction:(UIButton *)sender {
self.beaconPeripheralData = [self.beaconRegion peripheralDataWithMeasuredPower:nil];
self.peripheralManager = [[CBPeripheralManager alloc] initWithDelegate:self queue:nil options:nil];
}
Como atribuímos o CBPeripheralManagerDelegate a classe, precisamos implementar a função–(void)peripheralManagerDidUpdateState:(CBPeripheralManager *)peripheral que será chamada sempre que a ‘situação’ do iBeacon alterado for alterado e sua função ficará da seguinte forma:
-(void)peripheralManagerDidUpdateState:(CBPeripheralManager *)peripheral {
if (peripheral.state == CBPeripheralManagerStatePoweredOn) {
NSLog(@"Monitoramento Ligado");
[self.peripheralManager startAdvertising:self.beaconPeripheralData];
} else if (peripheral.state == CBPeripheralManagerStatePoweredOff) {
NSLog(@"Monitoramento Desligado");
[self.peripheralManager stopAdvertising];
}
}
Outra função fundamental que precisamos nos preocupar em criar, é a função responsável em atualizar as informações na interface, ou seja, que irá alterar os valores das Labels criadas:
- (void)setLabels {
self.uuidLabel.text = self.beaconRegion.proximityUUID.UUIDString;
self.majorLabel.text = [NSString stringWithFormat:@"%@", self.beaconRegion.major];
self.minorLabel.text = [NSString stringWithFormat:@"%@", self.beaconRegion.minor];
self.identityLabel.text = self.beaconRegion.identifier;
}
Feito isso, já criamos a tela de configuração, onde será iniciado o monitoramento. Agora iremos criar a tela de monitoramento que chamaremos de TrackViewController.
Na TrackViewController.h devemos importar a seguinte biblioteca:
#import <CoreLocation/CoreLocation.h>
Também precisaremos de algumas labels, para exibir algumas informações que serão monitoradas e o Delegate, responsável em reportar as mudanças captadas na posição do usuário.
@interface TrackViewController : UIViewController <CLLocationManagerDelegate> @property (weak, nonatomic) IBOutlet UILabel *beaconFoundLabel; @property (weak, nonatomic) IBOutlet UILabel *proximityUUIDLabel; @property (weak, nonatomic) IBOutlet UILabel *majorLabel; @property (weak, nonatomic) IBOutlet UILabel *minorLabel; @property (weak, nonatomic) IBOutlet UILabel *accuracyLabel; @property (weak, nonatomic) IBOutlet UILabel *distanceLabel; @property (weak, nonatomic) IBOutlet UILabel *rssiLabel;
E dois objetos, o primeiro responsável em armazenar as informações do iBeacon monitorado e o segundo que irá monitorar a localização, criando geofences.
@property (strong, nonatomic) CLBeaconRegion *beaconRegion; @property (strong, nonatomic) CLLocationManager *locationManager;
Já na TrackViewController.m a primeira coisa a ser feita é iniciar o objeto locationManager na função ViewDidLoad:
- (void)viewDidLoad {
[super viewDidLoad];
self.locationManager = [[CLLocationManager alloc] init];
self.locationManager.delegate = self;
[self initRegion];
[self locationManager:self.locationManager didStartMonitoringForRegion:self.beaconRegion];
}
Semelhante ao realizado na tela de configurações, devemos configurar o objeto beaconRegion, com as informações do iBeacon, conforme mostrado a seguir
- (void)initRegion {
NSUUID *uuid = [[NSUUID alloc] initWithUUIDString:@"23542266-18D1-4FE4-B4A1-23F8195B9D39"];
self.beaconRegion = [[CLBeaconRegion alloc] initWithProximityUUID:uuid identifier:@"iMobilis.com.Conrado"];
[self.locationManager startMonitoringForRegion:self.beaconRegion];
}
Outra função importante que devemos declarar é a locationManager:didStartMonitoringForRegion: que foi chamada na ViewDidLoad e agora deve ser iniciado o monitoramento da região criada pelo Beacon, ficando da seguinte forma:
- (void)locationManager:(CLLocationManager *)manager didStartMonitoringForRegion:(CLRegion *)region {
[self.locationManager startRangingBeaconsInRegion:self.beaconRegion];
}
Pronto, terminado essas configurações, so resta agora chamar as funções definidas pelo CLLocationManagerDelegate fundamentais para identificar mudanças de estado, são elas:
– Quando o iBeacon definido for encontrado:
- (void)locationManager:(CLLocationManager *)manager didEnterRegion:(CLRegion *)region {
[self.locationManager startRangingBeaconsInRegion:self.beaconRegion];
}
Quando o usuário sair da região do iBeacon:
-(void)locationManager:(CLLocationManager *)manager didExitRegion:(CLRegion *)region {
[self.locationManager stopRangingBeaconsInRegion:self.beaconRegion];
self.beaconFoundLabel.text = @"No";
}
Quando a distância entre o usuário e o iBeacon mudarem, essas distancias são definidas como: longe, perto, muito perto e desconhecido.
-(void)locationManager:(CLLocationManager *)manager didRangeBeacons:(NSArray *)beacons inRegion:(CLBeaconRegion *)region {
CLBeacon *beacon = [[CLBeacon alloc] init];
beacon = [beacons lastObject];
self.beaconFoundLabel.text = @"Yes";
self.proximityUUIDLabel.text = beacon.proximityUUID.UUIDString;
self.majorLabel.text = [NSString stringWithFormat:@"%@", beacon.major];
self.minorLabel.text = [NSString stringWithFormat:@"%@", beacon.minor];
self.accuracyLabel.text = [NSString stringWithFormat:@"%f", beacon.accuracy];
if (beacon.proximity == CLProximityUnknown) {
self.distanceLabel.text = @"Proximidade desconhecida";
} else if (beacon.proximity == CLProximityImmediate) {
self.distanceLabel.text = @"Muito perto";
} else if (beacon.proximity == CLProximityNear) {
self.distanceLabel.text = @"Perto";
} else if (beacon.proximity == CLProximityFar) {
self.distanceLabel.text = @"Longe";
}
self.rssiLabel.text = [NSString stringWithFormat:@"%i", beacon.rssi];
}
Pronto, já temos um projeto básico de configuração e monitoramento do iBeacon.
iBeacon – Tudo que você precisa saber

