advertisingをやってみる

ツイート このエントリーをはてなブックマークに追加
1つ上へ / ブログトップへ

iPhoneをPeripheralにしてadvertisingをやってみましょう。CBMutableServiceオブジェクトを作るとこは前回を見てください。

まずはCBPeripheralManagerオブジェクトを作ります。ボタンクリック等で使いたいのでプロパティにしています。

self.manager = [[CBPeripheralManager alloc] initWithDelegate:self queue:nil options:nil];

次に、ManagerにServiceを登録します。

[self.manager addService:service];

開始ボタンのイベントなどで、Advertisingを開始します。

- (IBAction)startClicked:(id)sender {
  // どのServiceのAdvertisingを開始するかを指定する。
  NSDictionary *param = @{
    CBAdvertisementDataServiceUUIDsKey : @[self.service.UUID]
  };
  // Advertising開始  
  [self.manager startAdvertising:param];
}

CentralからReadのリクエストがやってくると、次のdelegate methodが呼ばれます。

- (void)peripheralManager:(CBPeripheralManager *)peripheral
  didReceiveReadRequest:(CBATTRequest *)request {
    
  CBMutableCharacteristic *myCharacteristic = (CBMutableCharacteristic*)self.service.characteristics[0];
  if (![request.characteristic.UUID isEqual:myCharacteristic.UUID]) {
    return;
  }
  // データは何でもいい
  NSData *data = [@"{\"name\":\"fkm's iPhone 5s\",\"model\":\"iPhone 5s\"}" dataUsingEncoding:NSUTF8StringEncoding];
    
  if (request.offset > data.length) {
    [self.manager respondToRequest:request
                        withResult:CBATTErrorInvalidOffset];
    return;
  }

  // create data
  request.value = [data
                   subdataWithRange:NSMakeRange(request.offset,
                                                  data.length - request.offset)];
  [self.manager respondToRequest:request withResult:CBATTErrorSuccess];
}
1つ上へ / ブログトップへ