iOS-藍牙的簡單使用

藍牙實現(xiàn)方案

之前項目有用到藍牙,這里記錄一下藍牙的一些簡單使用.

iOS提供了4個用于實現(xiàn)藍牙連接的方案:

1. ExternalAccessory.framework

提供了配件鏈接iOS的通道,可用于第三方藍牙設備交互(藍牙設備必須需要蘋果MFI認證,比較麻煩)

2.MultipeerConnectivity.framework

iOS7引入的多點連接,只能用于Apple設備,可在較近的距離基于藍牙和WIFI發(fā)現(xiàn)和連接實現(xiàn)進場通信,有點和AirDrop類似,不過AirDrop必須同時打開WiFi和藍牙,而且要保持較近的距離 ( 其過程相當于A放出廣播,B用于搜索,B搜到之后向A發(fā)邀請,請求建立連接,A接受之后向B發(fā)送一個會話,建立連接)

MCPeerID *_peerID = [[MCPeerID alloc] initWithDisplayName:[UIDevice currentDevice].name];//給設備自定義個名字
MCSession *_session = [[MCSession alloc] initWithPeer:_peerID];//創(chuàng)建會話
_session.delegate = self;//遵守<MCSessionDelegate>協(xié)議
MCAdvertiserAssistant *_advertiser = [[MCAdvertiserAssistant alloc] initWithServiceType:@"chat-files"
                                                                   discoveryInfo:nil
                                                                   session:_session];
//初始化廣播服務,serviceType是類型標識符,通過文本描述來讓瀏覽器發(fā)現(xiàn)廣播者,只有相同的serviceType才能相互連接(要求1-15個字符,只能包含ASCII小寫字母,數(shù)字和連字符)
[_advertiser start]; //開始廣播   stop關閉廣播

MCBrowserViewController *_browser = [[MCBrowserViewController alloc] initWithServiceType:@"chat-files"session:_session]; // 創(chuàng)建視圖瀏覽器
_browser.delegate = self; //遵守<MCBrowserViewControllerDelegate>協(xié)議
[self presentViewController: _browser animated:YES completion:nil]; //彈出視窗

//<MCBrowserViewControllerDelegate>
-(void)browserViewControllerDidFinish:(MCBrowserViewController *)browserViewController{//完成
    [_browser dismissViewControllerAnimated:YES completion:nil];
}

-(void)browserViewControllerWasCancelled:(MCBrowserViewController *)browserViewController{//取消
    [_browser dismissViewControllerAnimated:YES completion:nil];
}

//瀏覽器提供連接功能 ,等連接之后就根據(jù)情況實現(xiàn)<MCSessionDelegate>方法
-(void)session:(MCSession *)session peer:(MCPeerID *)peerID didChangeState:(MCSessionState)state{
    //新的連接發(fā)生時,會被調(diào)用   state狀態(tài)如下:
    //MCSessionStateNotConnected,     // Not connected to the session.
    //    MCSessionStateConnecting,       // Peer is connecting to the session.
    //    MCSessionStateConnected    
}


-(void)session:(MCSession *)session didReceiveData:(NSData *)data fromPeer:(MCPeerID *)peerID{
    //接受數(shù)據(jù)
}


-(void)session:(MCSession *)session didStartReceivingResourceWithName:(NSString *)resourceName fromPeer:(MCPeerID *)peerID withProgress:(NSProgress *)progress{
    //開始接受資源
}


-(void)session:(MCSession *)session didFinishReceivingResourceWithName:(NSString *)resourceName fromPeer:(MCPeerID *)peerID atURL:(NSURL *)localURL withError:(NSError *)error{
    //結(jié)束接收資源
}


-(void)session:(MCSession *)session didReceiveStream:(NSInputStream *)stream withName:(NSString *)streamName fromPeer:(MCPeerID *)peerID{
    //接收流
}

[_session sendData: dataToSend toPeers:_session.connectedPeers withMode:MCSessionSendDataReliable error:&error]; //發(fā)送數(shù)據(jù)給所有連接的設備
連接流程圖.png
3.GameKit.framework

用于Apple設備之間的連接,更多用于游戲方面,從iOS7廢棄.此方案可以增加對等連接,無需連接到互聯(lián)網(wǎng)

GKPeerPickerController *gpp = [[GKPeerPickerController alloc] init];//創(chuàng)建查找設備控制器
gpp.connectionTypesMask = GKPeerPickerConnectionTypeNearby | GKPeerPickerConnectionTypeOnline;
//nearby指藍牙 online指WIFI
gpp.delegate = self; // 遵守<GKPeerPickerControllerDelegate>協(xié)議
[gpp show];//彈出控制器

//<GKPeerPickerControllerDelegate>協(xié)議
- (void)peerPickerController:(GKPeerPickerController *)picker didConnectPeer:(NSString *)peerID toSession:(GKSession *)session
{
    //設備連接成功后調(diào)用方法
    [self.session setDataReceiveHandler:self withContext:nil]; // 設置數(shù)據(jù)接受者
    [picker dismiss]; // 退出查找設備的控制器
}

- (void) receiveData:(NSData *)data fromPeer:(NSString *)peer inSession: (GKSession *)session context:(void *)context
{
    //接收數(shù)據(jù)的時候會調(diào)用該方法
}

[self.session sendDataToAllPeers: data withDataMode:GKSendDataReliable error:nil];//發(fā)送數(shù)據(jù)
[self.session sendData:data toPeers: peers withDataMode:GKSendDataReliable error:nil];//往指定peer發(fā)送數(shù)據(jù)

4.CoreBluetooth.framework (藍牙4.0)

以低功耗著稱,可用于第三方藍牙設備交互,對硬件上是有一定要求的柬脸,iPhone 4S及以后的設備,第三代iPad及以后的設備是支持這一標準的

核心結(jié)構(gòu)圖如下

CoreBluetooth結(jié)構(gòu)圖.png

每個藍牙設備必有一個或多個Service ,一個Service有若干個Characteristic,它們都是用UUID來唯一識別

@property(nonatomic,strong)CBCentralManager *_mgr;//中央管理者

//初始化中央管理者
 _mgr = [[CBCentralManager alloc] initWithDelegate:self queue:nil];

//遵守<CBCentralManagerDelegate>協(xié)議
- (void)centralManagerDidUpdateState:(CBCentralManager *)central
{
    //狀態(tài)發(fā)生改變的時候會執(zhí)行該方法(藍牙4.0沒有打開變成打開狀態(tài)就會調(diào)用該方法)
     switch (central.state) {
        case CBCentralManagerStatePoweredOn:
            NSLog(@"打開西乖,可用");
            //掃描周圍的藍牙 options參數(shù) 允許中央設備多次收到曾經(jīng)監(jiān)聽到的設備的消息
            [_mgr scanForPeripheralsWithServices:nil options:@{CBCentralManagerScanOptionAllowDuplicatesKey:@(NO)}];
            break;
        case CBCentralManagerStatePoweredOff:
            NSLog(@"可用,未打開");
            break;
        case CBCentralManagerStateUnsupported:
            NSLog(@"SDK不支持");
            break;
        case CBCentralManagerStateUnauthorized:
            NSLog(@"程序未授權(quán)");
            break;
        case CBCentralManagerStateResetting:
            NSLog(@"CBCentralManagerStateResetting");
            break;
        case CBCentralManagerStateUnknown:
            NSLog(@"CBCentralManagerStateUnknown");
            break;
}

//搜索到藍牙設備之后調(diào)用
- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI
{
//一次返回一個設備信息 RSSI為信號強度宋梧,可以將信息放入數(shù)組中
   //peripheral.identifier.UUIDString 藍牙設備的唯一標識
}

//連接設備
[self.mgr connectPeripheral:peripheral options:@{CBConnectPeripheralOptionNotifyOnDisconnectionKey:@(YES)}];

[self.manager stopScan];//停止掃描外設

//連接外圍設備之后調(diào)用
- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral
{
    // 1.掃描所有的服務
    // serviceUUIDs:指定要掃描該外圍設備的哪些服務(傳nil,掃描所有的服務)
    [peripheral discoverServices:nil];
    
    // 2.設置代理芜茵,為了后面查詢外設的服務和外設的特性
    //<CBPeripheralDelegate>協(xié)議
    peripheral.delegate = self;
}
- (void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(nullable NSError *)error
{
    //連接失敗調(diào)用
    NSLog(@"didFailToConnectPeripheral");
}

//遵循<CBPeripheralDelegate>協(xié)議
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error
{
//發(fā)現(xiàn)外圍設備的服務
    for (CBService *serivce in peripheral.services) {
        if ([serivce.UUID.UUIDString isEqualToString:@"123456"]) {
            // characteristicUUIDs : 可以指定想要掃描的特征(傳nil,掃描所有的特征)
            [peripheral discoverCharacteristics:nil forService:serivce];
        }
    }
}

- (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error
{
//發(fā)現(xiàn)服務后硫狞,當掃描到服務的特征時調(diào)用
    for (CBCharacteristic *characteristic in service.characteristics) {
        if ([characteristic.UUID.UUIDString isEqualToString:@"456"]) {
            // 拿到特征,和外圍設備進行交互
             CBCharacteristicProperties proper = characteristic.properties;   
             if (proper & CBCharacteristicPropertyBroadcast){} //廣播特性
             if (proper & CBCharacteristicPropertyRead){
             //讀特性
                   [peripheral readValueForCharacteristic:characteristic];
             }
             if (proper & CBCharacteristicPropertyWriteWithoutResponse){
             //寫特性不需要響應烛卧,可以保存特征以便后續(xù)寫數(shù)據(jù)
             }
             if (properties & CBCharacteristicPropertyWrite) {
             //如果具備寫入值的特性,這個應該會有一些響應
             }
             if (properties & CBCharacteristicPropertyNotify) {
             //如果具備通知的特性
             [peripheral setNotifyValue:YES forCharacteristic:character];
             } 
        }
    }
}

//通知代理
- (void)peripheral:(CBPeripheral *)peripheral didUpdateNotificationStateForCharacteristic:(nonnull CBCharacteristic *)characteristic error:(nullable NSError *)error
{
    CBCharacteristicProperties properties = characteristic.properties;
    if (properties & CBCharacteristicPropertyRead) {
        //如果具備讀特性验辞,即可以讀取特性的value
        [peripheral readValueForCharacteristic:characteristic];
    }
}

//讀取特性中的值調(diào)用
- (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error
{
    NSData *data = characteristic.value;
    if (data.length <= 0) {
        return;
    }
    NSString *info = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
}

//往設備寫數(shù)據(jù)
 [peripheral writeValue: data forCharacteristic: chatacter type:CBCharacteristicWriteWithoutResponse];

//取消與設備連接
[self.manager cancelPeripheralConnection:peripheral];
//斷開連接的代理
- (void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(nullable NSError *)error;
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末稿黄,一起剝皮案震驚了整個濱河市喊衫,隨后出現(xiàn)的幾起案子跌造,更是在濱河造成了極大的恐慌,老刑警劉巖族购,帶你破解...
    沈念sama閱讀 221,406評論 6 515
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件壳贪,死亡現(xiàn)場離奇詭異,居然都是意外死亡寝杖,警方通過查閱死者的電腦和手機违施,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,395評論 3 398
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來瑟幕,“玉大人磕蒲,你說我怎么就攤上這事≈豁铮” “怎么了辣往?”我有些...
    開封第一講書人閱讀 167,815評論 0 360
  • 文/不壞的土叔 我叫張陵,是天一觀的道長殖卑。 經(jīng)常有香客問我站削,道長,這世上最難降的妖魔是什么孵稽? 我笑而不...
    開封第一講書人閱讀 59,537評論 1 296
  • 正文 為了忘掉前任许起,我火速辦了婚禮,結(jié)果婚禮上菩鲜,老公的妹妹穿的比我還像新娘园细。我一直安慰自己,他們只是感情好接校,可當我...
    茶點故事閱讀 68,536評論 6 397
  • 文/花漫 我一把揭開白布猛频。 她就那樣靜靜地躺著,像睡著了一般馅笙。 火紅的嫁衣襯著肌膚如雪伦乔。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 52,184評論 1 308
  • 那天董习,我揣著相機與錄音烈和,去河邊找鬼。 笑死皿淋,一個胖子當著我的面吹牛招刹,可吹牛的內(nèi)容都是我干的恬试。 我是一名探鬼主播,決...
    沈念sama閱讀 40,776評論 3 421
  • 文/蒼蘭香墨 我猛地睜開眼疯暑,長吁一口氣:“原來是場噩夢啊……” “哼训柴!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起妇拯,我...
    開封第一講書人閱讀 39,668評論 0 276
  • 序言:老撾萬榮一對情侶失蹤幻馁,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后越锈,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體仗嗦,經(jīng)...
    沈念sama閱讀 46,212評論 1 319
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 38,299評論 3 340
  • 正文 我和宋清朗相戀三年甘凭,在試婚紗的時候發(fā)現(xiàn)自己被綠了稀拐。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 40,438評論 1 352
  • 序言:一個原本活蹦亂跳的男人離奇死亡丹弱,死狀恐怖德撬,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情躲胳,我是刑警寧澤蜓洪,帶...
    沈念sama閱讀 36,128評論 5 349
  • 正文 年R本政府宣布,位于F島的核電站泛鸟,受9級特大地震影響蝠咆,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜北滥,卻給世界環(huán)境...
    茶點故事閱讀 41,807評論 3 333
  • 文/蒙蒙 一刚操、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧再芋,春花似錦菊霜、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,279評論 0 24
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至司训,卻和暖如春构捡,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背壳猜。 一陣腳步聲響...
    開封第一講書人閱讀 33,395評論 1 272
  • 我被黑心中介騙來泰國打工勾徽, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人统扳。 一個月前我還...
    沈念sama閱讀 48,827評論 3 376
  • 正文 我出身青樓喘帚,卻偏偏與公主長得像畅姊,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子吹由,可洞房花燭夜當晚...
    茶點故事閱讀 45,446評論 2 359

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

  • Guide to BluetoothSecurity原文 本出版物可免費從以下網(wǎng)址獲得:https://doi.o...
    公子小水閱讀 8,016評論 0 6
  • iOS中提供了4個框架用于實現(xiàn)藍牙連接 GameKit.framework(用法簡單)-只能用于iOS設備之間的同...
    Hyman0819閱讀 1,532評論 0 0
  • 本未曾打算選擇小長假去西溪若未,只是很想趁著假期外出透透氣。拖家?guī)Э诘穆眯行枰櫦傻奶啵郝眯袝r的合拍倾鲫、舒適粗合、默契以及...
    獨憐幽竹閱讀 1,050評論 2 2
  • #4 熊熊是個很普通的孩子,但他有一點異于常人级乍,他能聽見身邊物品的聲音舌劳。 比如今天早上他起床時,他的被子悄悄地和他...
    俗世半仙閱讀 233評論 0 0
  • 了解JRebel 從字面意義上看玫荣,JRebel稱為Java Rebel - Java反叛者,看來有點“革命”的味道...
    ethnchao閱讀 2,159評論 0 3