首先需要導(dǎo)入基本依賴庫平痰,CoreBluetooth.framework,MultipeerConnectivity.framework,GameKit.framework
#import "ViewController.h"
#import <CoreBluetooth/CoreBluetooth.h>
#define kPeripheralName @"kenshin Cui's Device" //外圍設(shè)備名稱
#define kServiceUUID @"C4FB2349-72FE-4CA2-94D6-1F3CB16331EE" //服務(wù)的UUID
#define kCharacteristicUUID @"6A3E4B28-522D-4B3B-82A9-D5E2004534FC" //特征的UUID
@interface ViewController ()<CBPeripheralManagerDelegate>
@property (strong,nonatomic) CBPeripheralManager *peripheralManager;//外圍設(shè)備管理器
@property (strong,nonatomic) NSMutableArray *centralM;//訂閱此外圍設(shè)備特征的中心設(shè)備
@property (strong,nonatomic) CBMutableCharacteristic *characteristicM;//特征
@property (weak, nonatomic) IBOutlet UITextView *log; //日志記錄
- (IBAction)Left:(UIBarButtonItem *)sender;
- (IBAction)Right:(UIBarButtonItem *)sender;
@end
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
}
#pragma mark ****************UI事件***********************
- (IBAction)Left:(UIBarButtonItem *)sender
{
_peripheralManager=[[CBPeripheralManager alloc]initWithDelegate:self queue:nil];
}
- (IBAction)Right:(UIBarButtonItem *)sender
{
[self updateCharacteristicValue];
}
#pragma mark - CBPeripheralManager代理方法
//外圍設(shè)備狀態(tài)發(fā)生變化后調(diào)用
-(void)peripheralManagerDidUpdateState:(CBPeripheralManager *)peripheral{
switch (peripheral.state) {
case CBPeripheralManagerStatePoweredOn:
NSLog(@"BLE已打開.");
[self writeToLog:@"BLE已打開."];
//添加服務(wù)
[self setupService];
break;
default:
NSLog(@"此設(shè)備不支持BLE或未打開藍(lán)牙功能哈街,無法作為外圍設(shè)備.");
[self writeToLog:@"此設(shè)備不支持BLE或未打開藍(lán)牙功能,無法作為外圍設(shè)備."];
break;
}
}
//外圍設(shè)備添加服務(wù)后調(diào)用
-(void)peripheralManager:(CBPeripheralManager *)peripheral didAddService:(CBService *)service error:(NSError *)error{
if (error) {
NSLog(@"向外圍設(shè)備添加服務(wù)失敗,錯(cuò)誤詳情:%@",error.localizedDescription);
[self writeToLog:[NSString stringWithFormat:@"向外圍設(shè)備添加服務(wù)失敗,錯(cuò)誤詳情:%@",error.localizedDescription]];
return;
}
//添加服務(wù)后開始廣播
NSDictionary *dic=@{CBAdvertisementDataLocalNameKey:kPeripheralName};//廣播設(shè)置
[self.peripheralManager startAdvertising:dic];//開始廣播
NSLog(@"向外圍設(shè)備添加了服務(wù)并開始廣播...");
[self writeToLog:@"向外圍設(shè)備添加了服務(wù)并開始廣播..."];
}
-(void)peripheralManagerDidStartAdvertising:(CBPeripheralManager *)peripheral error:(NSError *)error{
if (error) {
NSLog(@"啟動(dòng)廣播過程中發(fā)生錯(cuò)誤,錯(cuò)誤信息:%@",error.localizedDescription);
[self writeToLog:[NSString stringWithFormat:@"啟動(dòng)廣播過程中發(fā)生錯(cuò)誤丈咐,錯(cuò)誤信息:%@",error.localizedDescription]];
return;
}
NSLog(@"啟動(dòng)廣播...");
[self writeToLog:@"啟動(dòng)廣播..."];
}
//訂閱特征
-(void)peripheralManager:(CBPeripheralManager *)peripheral central:(CBCentral *)central didSubscribeToCharacteristic:(CBCharacteristic *)characteristic{
NSLog(@"中心設(shè)備:%@ 已訂閱特征:%@.",central,characteristic);
[self writeToLog:[NSString stringWithFormat:@"中心設(shè)備:%@ 已訂閱特征:%@.",central.identifier.UUIDString,characteristic.UUID]];
//發(fā)現(xiàn)中心設(shè)備并存儲(chǔ)
if (![self.centralM containsObject:central]) {
[self.centralM addObject:central];
}
/*中心設(shè)備訂閱成功后外圍設(shè)備可以更新特征值發(fā)送到中心設(shè)備,一旦更新特征值將會(huì)觸發(fā)中心設(shè)備的代理方法:
-(void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error
*/
// [self updateCharacteristicValue];
}
//取消訂閱特征
-(void)peripheralManager:(CBPeripheralManager *)peripheral central:(CBCentral *)central didUnsubscribeFromCharacteristic:(CBCharacteristic *)characteristic{
NSLog(@"didUnsubscribeFromCharacteristic");
}
-(void)peripheralManager:(CBPeripheralManager *)peripheral didReceiveWriteRequests:(CBATTRequest *)request{
NSLog(@"didReceiveWriteRequests");
}
-(void)peripheralManager:(CBPeripheralManager *)peripheral willRestoreState:(NSDictionary *)dict{
NSLog(@"willRestoreState");
}
#pragma mark -屬性
-(NSMutableArray *)centralM{
if (!_centralM) {
_centralM=[NSMutableArray array];
}
return _centralM;
}
#pragma mark - 私有方法
//創(chuàng)建特征、服務(wù)并添加服務(wù)到外圍設(shè)備
-(void)setupService{
/*1.創(chuàng)建特征*/
//創(chuàng)建特征的UUID對(duì)象
CBUUID *characteristicUUID=[CBUUID UUIDWithString:kCharacteristicUUID];
//特征值
// NSString *valueStr=kPeripheralName;
// NSData *value=[valueStr dataUsingEncoding:NSUTF8StringEncoding];
//創(chuàng)建特征
/** 參數(shù)
* uuid:特征標(biāo)識(shí)
* properties:特征的屬性龙宏,例如:可通知棵逊、可寫、可讀等
* value:特征值
* permissions:特征的權(quán)限
*/
CBMutableCharacteristic *characteristicM=[[CBMutableCharacteristic alloc]initWithType:characteristicUUID properties:CBCharacteristicPropertyNotify value:nil permissions:CBAttributePermissionsReadable];
self.characteristicM=characteristicM;
// CBMutableCharacteristic *characteristicM=[[CBMutableCharacteristic alloc]initWithType:characteristicUUID properties:CBCharacteristicPropertyRead value:nil permissions:CBAttributePermissionsReadable];
// characteristicM.value=value;
/*創(chuàng)建服務(wù)并且設(shè)置特征*/
//創(chuàng)建服務(wù)UUID對(duì)象
CBUUID *serviceUUID=[CBUUID UUIDWithString:kServiceUUID];
//創(chuàng)建服務(wù)
CBMutableService *serviceM=[[CBMutableService alloc]initWithType:serviceUUID primary:YES];
//設(shè)置服務(wù)的特征
[serviceM setCharacteristics:@[characteristicM]];
/*將服務(wù)添加到外圍設(shè)備*/
[self.peripheralManager addService:serviceM];
}
//更新特征值
-(void)updateCharacteristicValue{
//特征值
NSString *valueStr=[NSString stringWithFormat:@"%@ --%@",kPeripheralName,[NSDate date]];
NSData *value=[valueStr dataUsingEncoding:NSUTF8StringEncoding];
//更新特征值
[self.peripheralManager updateValue:value forCharacteristic:self.characteristicM onSubscribedCentrals:nil];
[self writeToLog:[NSString stringWithFormat:@"更新特征值:%@",valueStr]];
}
/**
* 記錄日志
*
* @param info 日志信息
*/
-(void)writeToLog:(NSString *)info{
self.log.text=[NSString stringWithFormat:@"%@\r\n%@",self.log.text,info];
}
@end