一個聊天Demo讓你知道藍(lán)牙之間的通訊

提示:本文主要是講解藍(lán)牙中心管理者和外設(shè)管理者之間的通訊過程,沒有實(shí)際的意義,因?yàn)閭鬏斒茏止?jié)限制,效率低。

老樣子,先附上效果圖和Demo


外設(shè)模式

中心模式

Demo
https://github.com/chenfanfang/CollectionsOfExample


運(yùn)行程序

1、首先得準(zhǔn)備兩部蘋果手機(jī),必須支持BLE, >=iPhone 4s即可。
2、將程序運(yùn)行到兩部手機(jī)上
3、進(jìn)入 “聊天(CoreBluetooth實(shí)戰(zhàn)1)”
4、一部手機(jī)進(jìn)入中心模式、另一部手機(jī)進(jìn)入外設(shè)模式 (記得兩部手機(jī)都要開啟藍(lán)牙哦)

寫在前面的廢話

由于懶,時隔大半年沒寫技術(shù)文章了,今天心血來潮來發(fā)表一篇文章。由于以前沒有做過藍(lán)牙的項(xiàng)目,好奇心也蠻強(qiáng)的,想知道藍(lán)牙之間的通訊是怎樣的,早就在去年6月份的時候開始看藍(lán)牙的資料,但是基本都是斷斷續(xù)續(xù),沒有一股氣完成對藍(lán)牙的研究(當(dāng)初還買了藍(lán)牙開發(fā)板,并且傻瓜式地將程序燒錄進(jìn)去,就是效果還沒完全寫出來,等有時間會寫一篇真正藍(lán)牙實(shí)戰(zhàn)的文章,你也別問我為嘛不用LightBlue,因?yàn)槟菚r我沒有第二部手機(jī)并且覺得實(shí)物實(shí)戰(zhàn)比較好)。本文demo核心內(nèi)容在去年9月份左右的時候完成的(參照了幾個demo,由于時隔太久,無法將所參照的demo所在連接找出來),但是對界面美化要求程度比較高,一直沒有發(fā)布出來,昨天套了個即時通訊界面的框架JSQMessagesViewController中demo的界面,感覺界面效果還行,稱熱打鐵,寫一篇相關(guān)文章。我已經(jīng)將藍(lán)牙通訊的相關(guān)代碼和界面相關(guān)代碼分離開來,不會影響大家對藍(lán)牙代碼的閱讀。由于demo中注釋比較詳細(xì),本文就不做過多的闡述,直接附上代碼。

相關(guān)藍(lán)牙資料

若對藍(lán)牙不是太了解的朋友,在此推薦幾篇藍(lán)牙相關(guān)博客
iOS藍(lán)牙開發(fā)(一)藍(lán)牙相關(guān)基礎(chǔ)知識
iOS藍(lán)牙開發(fā)(二)ios連接外設(shè)的代碼實(shí)現(xiàn)
iOS藍(lán)牙開發(fā)(三)app作為外設(shè)被連接的實(shí)現(xiàn)

中心管理者

中心管理者相關(guān)流程:(以下流程摘抄自一個demo)

1,主流成:程序之行,就進(jìn)入回調(diào)函數(shù)centralManagerDidUpdateState,這個相當(dāng)于起步函數(shù)
2,半主流程:上一步中,centralManager調(diào)用scan函數(shù),向周邊搜尋服務(wù)
3,當(dāng)掃描到時,會觸發(fā)centralManager的代理的centralManager:didDiscoverPeripheral函數(shù),賦值周邊成員,并試圖與其建立連接
4,如果建立建立連接失敗,會調(diào)用代理的centralManager:didFailToConnectPeripheral:函數(shù)
4,如果成功,會觸發(fā)centralManager:didConnectPeripheral:,這時候講viewc設(shè)置為周邊成員的代理
5,在上部的回調(diào)函數(shù)中,調(diào)用周邊的discoverServices方法,去發(fā)現(xiàn)服務(wù)
6,當(dāng)周邊發(fā)現(xiàn)服務(wù)時,會觸發(fā)周邊的代理的peripheral:didDiscoverServices:
7,在上述回調(diào)函數(shù)中,周邊針對每一個發(fā)現(xiàn)的服務(wù)去搜尋對應(yīng)特征
8,發(fā)現(xiàn)對應(yīng)特征后是,會觸發(fā)周邊的代理的peripheral:didDiscoverCharacteristicsForService:函數(shù)
9,在上部的回調(diào)函數(shù)中,判斷發(fā)現(xiàn)的特征是否是感興趣的特征,如果是,則通過設(shè)定特征通知狀態(tài)為真,來預(yù)訂該特征。此時會觸發(fā)服務(wù)端didSubscribeToCharacteristic函數(shù)。
10,當(dāng)周邊的特征通知狀態(tài)發(fā)生變化時,會觸發(fā)周邊代理的peripheral:didUpdateNotificationStateForCharacteristic:,并沒什么卵用,這個回調(diào)函數(shù)。
10,服務(wù)端的調(diào)用updatevalue函數(shù),會觸發(fā)客戶端的didUpdateValueForCharacteristic:函數(shù),從而獲得服務(wù)端傳遞的字符串
另外,中央管理器調(diào)用取消周邊連接函數(shù),會觸發(fā),中央管理器代理的centralManager:didDisconnectPeripheral方法,用于對斷開連接后進(jìn)行后續(xù)處理

中心管理者(CBCentralManager)相關(guān)代碼如下

//
//  CBCentralManagerController.m
//  CoreBluetooth_Demo
//
//  Created by mac on 16/9/9.
//  Copyright ? 2016年 chenfanfang. All rights reserved.
//

#import "CBCentralManagerController.h"

#import <CoreBluetooth/CoreBluetooth.h>

//可通過終端命令 uuidgen來生成
#define TRANSFER_SERVICE_UUID           @"D63D44E5-E798-4EA5-A1C0-3F9EEEC2CDEB"
#define TRANSFER_CHARACTERISTIC_UUID    @"1652CAD2-6B0D-4D34-96A0-75058E606A98"

@interface CBCentralManagerController ()<CBCentralManagerDelegate, CBPeripheralDelegate>

/** 中心管理者 */
@property (strong, nonatomic) CBCentralManager *centralManager;

/** 發(fā)現(xiàn)的外設(shè) */
@property (strong, nonatomic) CBPeripheral *discoveredPeripheral;

/** 當(dāng)前的特征 */
@property (nonatomic, strong) CBCharacteristic *characteristic;

/** 數(shù)據(jù) */
@property (strong, nonatomic) NSMutableData *data;

@end

@implementation CBCentralManagerController

- (void)viewDidLoad {
    
    [super viewDidLoad];
    
    self.navigationItem.title = @"中心模式";
    
    // 設(shè)置CBCentralManager
    _centralManager = [[CBCentralManager alloc] initWithDelegate:self queue:nil];
    
    // 保存接收數(shù)據(jù)
    _data = [[NSMutableData alloc] init];
    
    //菊花轉(zhuǎn)動
    [self.activityIndicatorView startAnimating];
}



- (void)viewWillDisappear:(BOOL)animated {
    
    [super viewWillDisappear:animated];
    
    [self.centralManager stopScan];
    
    [self cleanup];
    
    [self.activityIndicatorView stopAnimating];
    
    self.centralManager = nil;
    
    NSLog(@"掃描停止");
    
    
}

- (void)dealloc {
    
    NSLog(@"%@控制器銷毀成功,無內(nèi)存泄漏",NSStringFromClass([self class]));
}

//=================================================================
//                    CBCentralManagerDelegate
//=================================================================
#pragma mark - CBCentralManagerDelegate


//設(shè)置成功回調(diào)方法
- (void)centralManagerDidUpdateState:(CBCentralManager *)central {
    
    if (central.state != CBCentralManagerStatePoweredOn) {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"溫馨提示" message:@"請打開您的藍(lán)牙" delegate:nil cancelButtonTitle:@"確定" otherButtonTitles:nil, nil];
        [alertView show];
        return;
    }

    //開始掃描
    [self scan];
    
}


/** 通過制定的128位的UUID,掃描外設(shè)
 */
- (void)scan {
    
    [self.activityIndicatorView startAnimating];
    //掃描
    [self.centralManager scanForPeripheralsWithServices:@[[CBUUID UUIDWithString:TRANSFER_SERVICE_UUID]] options:@{ CBCentralManagerScanOptionAllowDuplicatesKey : @YES }];
    NSLog(@"正在掃描外設(shè)");

}

/** 停止掃描
 */
- (void)stop {
    [self.activityIndicatorView stopAnimating];
    [self.centralManager stopScan];
    
    NSLog(@"停止掃描外設(shè)");
    
}

//掃描成功調(diào)用此方法
- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI {
    
    NSLog(@"發(fā)現(xiàn)外設(shè) %@ at %@", peripheral.name, RSSI);
    
    if (self.discoveredPeripheral != peripheral) {
        self.discoveredPeripheral = peripheral;
        
        NSLog(@"連接外設(shè) %@", peripheral);
        [self.centralManager connectPeripheral:peripheral options:nil];
    }
}


- (void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error {
    
    NSLog(@"連接失敗 %@. (%@)", peripheral, [error localizedDescription]);
    [self cleanup];
}

//連接外設(shè)成功
- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral {
    
    [self stop];
    NSLog(@"停止掃描外設(shè)");
    
    [self.data setLength:0];//重置data屬性
    
    peripheral.delegate = self;//設(shè)置外設(shè)對象的委托為self
    
    NSLog(@"外設(shè)已連接,正在搜尋服務(wù)...");
    [peripheral discoverServices:@[[CBUUID UUIDWithString:TRANSFER_SERVICE_UUID]]];
}



//=================================================================
//                       CBPeripheralDelegate
//=================================================================
#pragma mark - CBPeripheralDelegate

//發(fā)現(xiàn)服務(wù)成功
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error {
    
    if (error) {
        NSLog(@"Error discovering services: %@", [error localizedDescription]);
        [self cleanup];
        return;
    }
    NSLog(@"成功發(fā)現(xiàn)服務(wù),正在搜尋特征...");
    
    // 發(fā)現(xiàn)特征
    for (CBService *service in peripheral.services) {
        [peripheral discoverCharacteristics:@[[CBUUID UUIDWithString:TRANSFER_CHARACTERISTIC_UUID]] forService:service];
    }
}

//發(fā)現(xiàn)特征成功
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error {
    
    if (error) {
        NSLog(@"發(fā)現(xiàn)特征錯誤: %@", [error localizedDescription]);
        [self cleanup];
        return;
    }
    NSLog(@"成功發(fā)現(xiàn)特征,正在預(yù)定特征...");
    
    for (CBCharacteristic *characteristic in service.characteristics) {
        
        if ([characteristic.UUID isEqual:[CBUUID UUIDWithString:TRANSFER_CHARACTERISTIC_UUID]]) {
            // 預(yù)定特征
            [peripheral setNotifyValue:YES forCharacteristic:characteristic];//觸發(fā)服務(wù)端(外設(shè))didSubscribeToCharacteristic函數(shù)
            
            self.characteristic = characteristic;
            
            [self.activityIndicatorView stopAnimating];
            NSLog(@"找到需要的特征,預(yù)定成功");
        }
    }
}

//特征值發(fā)生變化
- (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error {
    
    if (error) {
        NSLog(@"發(fā)現(xiàn)特征錯誤:: %@", [error localizedDescription]);
        return;
    }
    NSLog(@"特征值發(fā)生變化");
    
    NSString *stringFromData = [[NSString alloc] initWithData:characteristic.value encoding:NSUTF8StringEncoding];
    
    // 判斷是否為數(shù)據(jù)結(jié)束
    if ([stringFromData isEqualToString:@"END"]) {
        
        // 顯示數(shù)據(jù)
        NSString* recString = [[NSString alloc] initWithData:self.data encoding:NSUTF8StringEncoding];
        [self addReceiveMessage:recString];
        self.data.length = 0;
        return;
    }
    
    // 接收數(shù)據(jù)追加到data屬性中
    [self.data appendData:characteristic.value];
}

//特征通知狀態(tài)發(fā)生變化
- (void)peripheral:(CBPeripheral *)peripheral didUpdateNotificationStateForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error {
    
    if (error) {
        NSLog(@"特征通知狀態(tài)變化錯誤: %@", error.localizedDescription);
    }
    
    // 如果沒有特征傳輸過來則退出(如果不是我們感興趣的特質(zhì))
    if (![characteristic.UUID isEqual:[CBUUID UUIDWithString:TRANSFER_CHARACTERISTIC_UUID]]) {
        return;
    }
    
    NSLog(@"特征通知狀態(tài)發(fā)生變化");

    // 特征通知已經(jīng)開始
    if (characteristic.isNotifying) {
        NSLog(@"特征通知已經(jīng)開始 %@", characteristic);
    }
    // 特征通知已經(jīng)停止
    else {
        NSLog(@"特征通知已經(jīng)停止 %@", characteristic);
        [self.centralManager cancelPeripheralConnection:peripheral];
    }
}

//與外設(shè)連接斷開時回調(diào)
- (void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error {
    
    NSLog(@"外設(shè)已經(jīng)斷開");
    self.discoveredPeripheral = nil;
    //外設(shè)已經(jīng)斷開情況下,重新掃描
    [self scan];
}


/** 清除方法
 */
- (void)cleanup {
    
    NSLog(@"清除訂閱特征");
    // 如果沒有連接則退出
    if (self.discoveredPeripheral.state != CBPeripheralStateConnected) {
        return;
    }
    
    // 判斷是否已經(jīng)預(yù)定了特征
    
    for (CBService *service in self.discoveredPeripheral.services) {
        
        for (CBCharacteristic *characteristic in service.characteristics) {
            if ([characteristic.UUID isEqual:[CBUUID UUIDWithString:TRANSFER_CHARACTERISTIC_UUID]]) {
                if (characteristic.isNotifying) {
                    //停止接收特征通知
                    [self.discoveredPeripheral setNotifyValue:NO forCharacteristic:characteristic];
                    //斷開與外設(shè)連接
                    [self.centralManager cancelPeripheralConnection:self.discoveredPeripheral];
                    return;
                }
            }
        }
    }
}



//添加從外設(shè)發(fā)來的消息
-(void)addReceiveMessage:(NSString*)message{
    
    NSLog(@"收到從外設(shè)發(fā)來的消息:\n%@",message);
    
    //下面代碼無需研究,只是為了顯示在屏幕上
    [self receiveMessage:message senderId:kJSQDemoAvatarIdCook senderName:kJSQDemoAvatarDisplayNameCook];
    
}



//=================================================================
//                           發(fā)送文本數(shù)據(jù)
//=================================================================
#pragma mark - 發(fā)送文本數(shù)據(jù)

- (void)didPressSendButton:(UIButton *)button
           withMessageText:(NSString *)text
                  senderId:(NSString *)senderId
         senderDisplayName:(NSString *)senderDisplayName
                      date:(NSDate *)date {
    
    if (self.activityIndicatorView.isAnimating) {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"溫馨提示" message:@"沒有與外設(shè)建立鏈接,無法發(fā)送數(shù)據(jù)" delegate:nil cancelButtonTitle:@"" otherButtonTitles:nil, nil];
        [alertView show];
        return;
    }
    
    NSLog(@"要發(fā)送的消息為:\n%@",text);
    NSData *writeData = [text dataUsingEncoding:NSUTF8StringEncoding];
    
    if (self.characteristic.properties & CBCharacteristicPropertyWrite) {
        [self.discoveredPeripheral writeValue:writeData forCharacteristic:self.characteristic type:CBCharacteristicWriteWithResponse];
    }

    //下面代碼無需研究,只是為了顯示在屏幕上
    [super didPressSendButton:button withMessageText:text senderId:senderId senderDisplayName:senderDisplayName date:date];
}



- (void)peripheral:(CBPeripheral *)peripheral didWriteValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error {
    NSLog(@"給外設(shè)寫入數(shù)據(jù)成功");
}



//=================================================================
//                        和界面相關(guān),請忽略
//=================================================================
#pragma mark - 和界面相關(guān),請忽略

- (NSString *)senderId {
    return kJSQDemoAvatarIdWoz;
    
}

@end




外設(shè)管理者

中心管理者相關(guān)流程:(以下流程摘抄自一個demo)

1,入口函數(shù),peripheralManagerDidUpdateState,處理:特征準(zhǔn)備,服務(wù)準(zhǔn)備的工作;設(shè)置服務(wù)的特征;將服務(wù)添加到周邊管理器上
2,服務(wù)添加成功,會觸發(fā)周邊管理器代理的peripheralManager:didAddService:
3,在上部的回調(diào)函數(shù)中,廣播廣播服務(wù),等待中心即客戶端預(yù)訂改服務(wù)。。。
4,一旦客戶端預(yù)訂成功,則調(diào)用周邊管理器代理的peripheralManager:central:didSubscribeToCharacteristic:,表明管道已經(jīng)打通了,接下來將發(fā)送按鈕變?yōu)橛行顟B(tài),由服務(wù)器決定是否發(fā)送
5,在上面的回調(diào)函數(shù)中,處理發(fā)送數(shù)據(jù):通過調(diào)用周邊管理器的updateValue方法,來實(shí)現(xiàn)發(fā)送。這個應(yīng)該會觸發(fā)中央的peripheral:didUpdateValueForCharacteristic函數(shù)

外設(shè)管理者(CBPeripheralManager)相關(guān)代碼如下

//
//  CBPeripheralManagerController.m
//  CoreBluetooth_Demo
//
//  Created by mac on 16/9/9.
//  Copyright ? 2016年 chenfanfang. All rights reserved.
//

#import "CBPeripheralManagerController.h"

#import <CoreBluetooth/CoreBluetooth.h>

//可通過終端命令 uuidgen來生成
#define TRANSFER_SERVICE_UUID @"D63D44E5-E798-4EA5-A1C0-3F9EEEC2CDEB"
#define TRANSFER_CHARACTERISTIC_UUID @"1652CAD2-6B0D-4D34-96A0-75058E606A98"

//每次向中心設(shè)備發(fā)送數(shù)據(jù)的最大的數(shù)據(jù)量
#define SEND_DATA_MAX_AMOUNT 20


@interface CBPeripheralManagerController ()<CBPeripheralManagerDelegate>

/** 外設(shè)管理者 */
@property (strong, nonatomic) CBPeripheralManager *peripheralManager;

/** 特征 */
@property (strong, nonatomic) CBMutableCharacteristic *transferCharacteristic;

/** 需要發(fā)送的數(shù)據(jù) */
@property (strong, nonatomic) NSData *dataToSend;

/** 需要發(fā)送的數(shù)據(jù)的字節(jié)的下標(biāo)標(biāo)記 */
@property (nonatomic, readwrite) NSInteger sendDataIndex;


@end

@implementation CBPeripheralManagerController

- (void)viewDidLoad {
    
    [super viewDidLoad];
    
    self.navigationController.navigationBar.translucent = NO;
    
    self.navigationItem.title = @"外設(shè)模式";
    
    //設(shè)置CBPeripheralManager
    _peripheralManager = [[CBPeripheralManager alloc] initWithDelegate:self queue:nil];
    
    [self.activityIndicatorView startAnimating];
}


- (void)viewWillDisappear:(BOOL)animated {
    
    [super viewWillDisappear:animated];
    
    [self.peripheralManager stopAdvertising];
    
    self.peripheralManager = nil;

    
}


- (void)dealloc {
    
    NSLog(@"%@控制器銷毀成功,無內(nèi)存泄漏",NSStringFromClass([self class]));
}

//=================================================================
//                    CBPeripheralManagerDelegate
//=================================================================
#pragma mark - CBPeripheralManagerDelegate

//外設(shè)設(shè)置成功回調(diào)此方法
- (void)peripheralManagerDidUpdateState:(CBPeripheralManager *)peripheral {
    
    if (peripheral.state != CBPeripheralManagerStatePoweredOn) {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"溫馨提示" message:@"請您打開藍(lán)牙" delegate:nil cancelButtonTitle:@"" otherButtonTitles:nil, nil];
        [alertView show];
        return;
    }
    
    NSLog(@"藍(lán)牙處于打開狀態(tài)");
    
    // 初始化特征
    self.transferCharacteristic = [[CBMutableCharacteristic alloc]
                                   initWithType:[CBUUID UUIDWithString:TRANSFER_CHARACTERISTIC_UUID]
                                   properties:CBCharacteristicPropertyNotify | CBCharacteristicPropertyWrite
                                   value:nil
                                   permissions:CBAttributePermissionsWriteable]; //CBAttributePermissionsReadable
    
    // 初始化服務(wù)
    CBMutableService *transferService = [[CBMutableService alloc]
                                         initWithType:[CBUUID UUIDWithString:TRANSFER_SERVICE_UUID]
                                         primary:YES];
    
    // 添加特征到服務(wù)
    transferService.characteristics = @[self.transferCharacteristic];
    
    // 發(fā)布服務(wù)與特征(將服務(wù)添加到外設(shè)中)
    [self.peripheralManager addService:transferService];
}


- (void)peripheralManager:(CBPeripheralManager *)peripheral
            didAddService:(CBService *)service
                    error:(NSError *)error {
    
    if (error) {
        NSLog(@"添加服務(wù)失敗: %@", [error localizedDescription]);
        
    }else{
        NSLog( @"添加服務(wù)成功,準(zhǔn)備廣播..." );
        [self.peripheralManager startAdvertising:@{ CBAdvertisementDataServiceUUIDsKey : @[[CBUUID UUIDWithString:TRANSFER_SERVICE_UUID]] }];
    }
}


//中心管理者訂閱了特征,會回調(diào)該方法
- (void)peripheralManager:(CBPeripheralManager *)peripheral central:(CBCentral *)central didSubscribeToCharacteristic:(CBCharacteristic *)characteristic {
    
    [self.activityIndicatorView stopAnimating];
    NSLog(@"中心已經(jīng)訂閱了特征");
    
}

//中心管理者取消訂閱了特征,會回調(diào)該方法
- (void)peripheralManager:(CBPeripheralManager *)peripheral central:(CBCentral *)central didUnsubscribeFromCharacteristic:(CBCharacteristic *)characteristic {
    
    [self.activityIndicatorView startAnimating];
    NSLog(@"中心取消訂閱特征");
    
}



//向中心管理者發(fā)送數(shù)據(jù)
//注意,發(fā)送大量的數(shù)據(jù)時,需要將數(shù)據(jù)分成多個小數(shù)據(jù)發(fā)送,要不然會發(fā)送失敗
- (void)sendData {

    /** 是否開始發(fā)送 END  */
    static BOOL sendingEND = NO;
    
    
    //開始發(fā)送最后的 結(jié)束標(biāo)識符  END
    if (sendingEND == YES) {
        BOOL didSend = [self.peripheralManager updateValue:[@"END" dataUsingEncoding:NSUTF8StringEncoding] forCharacteristic:self.transferCharacteristic onSubscribedCentrals:nil];
        if (didSend == YES) {
            sendingEND = NO;
            NSLog(@"發(fā)送數(shù)據(jù)完畢");
        }
        return;
    }
    
    
    //已經(jīng)發(fā)送完畢
    if (self.sendDataIndex >= self.dataToSend.length) {
        return;
    }
    
    BOOL didSend = YES;
    
    //正在發(fā)送數(shù)據(jù)
    while (didSend) {
        
        //本次需要發(fā)送的數(shù)據(jù)量
        NSInteger amountToSend = self.dataToSend.length - self.sendDataIndex;
        
        //若發(fā)送的數(shù)量大于規(guī)定的最大發(fā)送的數(shù)據(jù)量
        if (amountToSend > SEND_DATA_MAX_AMOUNT) amountToSend = SEND_DATA_MAX_AMOUNT;
        
        //本次需要發(fā)送的數(shù)據(jù)
        NSData *smallData = [NSData dataWithBytes:self.dataToSend.bytes + self.sendDataIndex length:amountToSend];
        
        //發(fā)送數(shù)據(jù)
        didSend = [self.peripheralManager updateValue:smallData forCharacteristic:self.transferCharacteristic onSubscribedCentrals:nil];
        
        //發(fā)送數(shù)據(jù)失敗 直接return
        if (didSend == NO) {
            return;
        }
        
        //更新需要發(fā)送的數(shù)據(jù)的字節(jié)下標(biāo)
        self.sendDataIndex += amountToSend;
        
        //數(shù)據(jù)完全發(fā)送完成,記得需要發(fā)送一個結(jié)束的標(biāo)識
        if (self.sendDataIndex >= self.dataToSend.length) {
            
            sendingEND = YES;
            
            BOOL endSent = [self.peripheralManager updateValue:[@"END" dataUsingEncoding:NSUTF8StringEncoding] forCharacteristic:self.transferCharacteristic onSubscribedCentrals:nil];
            
            if (endSent) {
                sendingEND = NO;
                NSLog(@"發(fā)送數(shù)據(jù)完畢");
                
            }
            return;
        }
    }
}

//發(fā)送數(shù)據(jù)失敗后(發(fā)送數(shù)據(jù)的隊(duì)列已經(jīng)滿了)重新發(fā)送
- (void)peripheralManagerIsReadyToUpdateSubscribers:(CBPeripheralManager *)peripheral {
    [self sendData];
}


- (void)peripheralManager:(CBPeripheralManager *)peripheral didReceiveWriteRequests:(NSArray<CBATTRequest *> *)requests {
    
    CBATTRequest *request = requests.firstObject;
    NSString *receiveMsg = [[NSString alloc] initWithData:request.value encoding:NSUTF8StringEncoding];
    [peripheral respondToRequest:request withResult:CBATTErrorSuccess];
    
    NSLog(@"收到從中心管理者發(fā)來的消息:\n%@",receiveMsg);
    
    //下面代碼無需研究,只是為了顯示在屏幕上
    [self receiveMessage:receiveMsg senderId:kJSQDemoAvatarIdWoz senderName:kJSQDemoAvatarDisplayNameWoz];
    
}



//=================================================================
//                           發(fā)送文本數(shù)據(jù)
//=================================================================
#pragma mark - 發(fā)送文本數(shù)據(jù)

- (void)didPressSendButton:(UIButton *)button
           withMessageText:(NSString *)text
                  senderId:(NSString *)senderId
         senderDisplayName:(NSString *)senderDisplayName
                      date:(NSDate *)date {
    
    NSLog(@"要發(fā)送的消息為:\n%@",text);
    
    //判斷是否與中心管理者保持著鏈接
    if (self.activityIndicatorView.isAnimating) {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"溫馨提示" message:@"沒有與中心管理者建立鏈接,無法發(fā)送數(shù)據(jù)" delegate:nil cancelButtonTitle:@"確定" otherButtonTitles:nil, nil];
        [alertView show];
        return;
    }
    
    self.sendDataIndex = 0;
    self.dataToSend = [text dataUsingEncoding:NSUTF8StringEncoding];
    [self sendData];
    
    //下面代碼無需研究,只是為了顯示在屏幕上
    [super didPressSendButton:button withMessageText:text senderId:senderId senderDisplayName:senderDisplayName date:date];
}


//=================================================================
//                        和界面相關(guān),請忽略
//=================================================================
#pragma mark - 和界面相關(guān),請忽略

- (NSString *)senderId {
    return kJSQDemoAvatarIdCook;
}


@end


最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容