文章转自:http://www.cnblogs.com/ctaodream/archive/2013/07/03/3169962.html
一、服务端(也叫周边设备吧。。脑残的翻译)
1.实现类必须遵守协议 CBPeripheralManagerDelegate
2.需要的主要类有:
@property(strong,nonatomic) CBPeripheralManager *peripheraManager;
@property(strong,nonatomic) CBMutableCharacteristic *customerCharacteristic;
@property (strong,nonatomic) CBMutableService *customerService;
3.调用流程代码中有注释
// // ViewController.m // BlueToothDemo // // Created by PSH_Chen_Tao on 7/3/13. // Copyright (c) 2013 wolfman. All rights reserved. // #import "ViewController.h" static NSString *const kCharacteristicUUID = @"CCE62C0F-1098-4CD0-ADFA-C8FC7EA2EE90"; static NSString *const kServiceUUID = @"50BD367B-6B17-4E81-B6E9-F62016F26E7B"; @interface ViewController () @end @implementation ViewController @synthesize peripheraManager; @synthesize customerCharacteristic; @synthesize customerService; - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. //初始化后会直接调用代理的 - (void)peripheralManagerDidUpdateState:(CBPeripheralManager *)peripheral peripheraManager = [[CBPeripheralManager alloc]initWithDelegate:self queue:nil]; // [peripheraManager startAdvertising:nil]; } -(void)setUp{ CBUUID *characteristicUUID = [CBUUID UUIDWithString:kCharacteristicUUID]; customerCharacteristic = [[CBMutableCharacteristic alloc]initWithType:characteristicUUID properties:CBCharacteristicPropertyNotify value:nil permissions:CBAttributePermissionsReadable]; CBUUID *serviceUUID = [CBUUID UUIDWithString:kServiceUUID]; customerService = [[CBMutableService alloc]initWithType:serviceUUID primary:YES]; [customerService setCharacteristics:@[characteristicUUID]]; //添加后就会调用代理的- (void)peripheralManager:(CBPeripheralManager *)peripheral didAddService:(CBService *)service error:(NSError *)error [peripheraManager addService:customerService]; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } #pragma mark -- CBPeripheralManagerDelegate - (void)peripheralManagerDidUpdateState:(CBPeripheralManager *)peripheral{ switch (peripheral.state) { //在这里判断蓝牙设别的状态 当开启了则可调用 setUp方法(自定义) case CBPeripheralManagerStatePoweredOn: NSLog(@"powered on"); [self setUp]; break; case CBPeripheralManagerStatePoweredOff: NSLog(@"powered off"); break; default: break; } } - (void)peripheralManager:(CBPeripheralManager *)peripheral didAddService:(CBService *)service error:(NSError *)error{ if (error == nil) { //添加服务后可以在此向外界发出通告 调用完这个方法后会调用代理的 //(void)peripheralManagerDidStartAdvertising:(CBPeripheralManager *)peripheral error:(NSError *)error [peripheraManager startAdvertising:@{CBAdvertisementDataLocalNameKey : @"Service",CBAdvertisementDataServiceUUIDsKey : [CBUUID UUIDWithString:kServiceUUID]}]; } } - (void)peripheralManagerDidStartAdvertising:(CBPeripheralManager *)peripheral error:(NSError *)error{ NSLog(@"in peripheralManagerDidStartAdvertisiong:error"); } @end