iOS 藍芽,ios藍芽

來源:互聯網
上載者:User

iOS 藍芽,ios藍芽

# 藍芽##GameKit###簡介:* 實現藍牙裝置之間的`通訊`* 只能使用在`iOS裝置`之間`同一個應用`內串連* 從`iOS7`開始到期了* 但是GameKit是`最基本的`藍芽通訊架構* 通過藍芽可以實現檔案的共用(僅限裝置沙箱中的檔案)* 此架構一般用於遊戲開發(比如五子棋對戰)##開始案例###簡介:* 使用藍芽將兩個iOS裝置串連起來* 搜尋對方的裝置* 實現將手機中的圖片發送給對方###介面的搭建:###藍芽互連:* 搜尋藍牙裝置```    // 初始化連結藍芽控制器    GKPeerPickerController *peerCtr = [[GKPeerPickerController alloc]init];    // 顯示匹配到的藍牙裝置    [peerCtr show];```* `GKPeerPickerController`最重要的兩個代理```/** *  連結成功 * *  @param picker  藍芽控制器 *  @param peerID  串連藍芽的裝置id *  @param session 串連藍芽的會話(通訊)用來傳資料 */- (void)peerPickerController:(GKPeerPickerController *)picker didConnectPeer:(NSString *)peerID toSession:(GKSession *)session{    NSLog(@"%s %d",__func__,__LINE__);    // 隱藏藍芽控制器    [picker dismiss];}// 退出串連- (void)peerPickerControllerDidCancel:(GKPeerPickerController *)picker{    NSLog(@"%s %d",__func__,__LINE__);}```###選擇圖片:* 選擇圖片方法```// 選擇圖片- (IBAction)chooseImage {    // 1.初始化圖片選擇控制器    UIImagePickerController *imgPicker = [[UIImagePickerController alloc]init];    // 2.判斷圖庫是否可用    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeSavedPhotosAlbum]) {        // 3.設定圖庫開啟的類型        imgPicker.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;        // 4. 設定代理        imgPicker.delegate = self;        // 5. 開啟圖庫        [self presentViewController:imgPicker animated:YES completion:nil];    }}```* 選擇圖片控制器的代理方法```/** *  圖片選擇完成調用 * *  @param picker 圖片選擇控制器 *  @param info   選擇的資訊 */- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{    NSLog(@"info == %@",info);    // 設定選擇的圖片為當前的顯示圖片    self.showImageView.image = info[UIImagePickerControllerOriginalImage];    // 隱藏當前選擇圖片控制器    [picker dismissViewControllerAnimated:YES completion:nil];}```###圖片相互發送:* 需要在串連成功代理方法中儲存當前的會話```// 儲存當前回話    self.m_Session = session;```* 發送圖片方法```// 發送圖片- (IBAction)sendImage {        // 拿到需要發送出去的圖片    UIImage *image = self.showImageView.image;    // 將圖片轉換成NSData類型    NSData *imgData = UIImagePNGRepresentation(image);        /**     *  發送資料給所有匹配上的使用者     *     *  @param GKSendDataMode 資料發送的模式:(安全/不安全模式)     *                        GKSendDataUnreliable : 不安全模式:就像發10個傳單,傳單直接往人群中砸過去,能不能收到不管     *                        GKSendDataReliable:安全模式:就像發10個傳單,每一個傳單都得發到路人的手上,才再發下一個傳單     *  @return     */    [self.m_Session sendDataToAllPeers:imgData withDataMode:GKSendDataUnreliable error:nil];}```###設定圖片:* GameKit提供的接受資料是方法的回調    * 需要監聽接收傳遞過來的資料        * 在串連成功代理方法中設定監聽            ```            /** 監聽傳遞過來的資料         *  setDataReceiveHandler: 由哪個對象來監聽資料的接受         *  withContext : 監聽需要傳遞的參數         */        [session setDataReceiveHandler:self withContext:nil];        ```            * 實現監聽方法        * 只設定由誰監聽傳遞過來的資料還是不足的,因為我們還是不能拿到傳遞過來的資料,進入監聽方法的標頭檔可以看到                    ```            // SEL = -receiveData:fromPeer:inSession:context:        ```        * 所以我們必須實現這個方法才能拿到接收到的資料,這個回調方法方法在Xcode 7之前的版本的解釋![](素材/回調方法.png)```/** *  實現接收資料的回調方法 * *  @param data    接收到的資料 *  @param peer    傳遞資料的裝置ID *  @param session 當前回話 *  @param context 註冊監聽傳遞過來的資料 */- (void) receiveData:(NSData *)data fromPeer:(NSString *)peer inSession: (GKSession *)session context:(void *)context{    // 因為傳遞過來的是圖片,所以我們直接使用UIImage來接受    UIImage *image = [UIImage imageWithData:data];    // 設定圖片    self.showImageView.image = image;}```
##CoreBlueTooth###簡介:* 可用於第三方藍牙裝置互動,裝置必須支援藍芽4.0* iPhone的裝置必須是4S或者更新* iPad裝置必須是iPad mini或者更新* iOS的系統必須是iOS 6或者更新* 藍芽4.0以`低功耗`著稱,所以一般被稱為BLE(bluetooth low energy)* 使用模擬器調試    - Xcode 4.6    - iOS 6.1* 應用情境    + 運動手環    + 智能家居     + 拉卡拉藍芽刷卡器###核心概念* CBCentralManager:中心裝置(用來串連到外部裝置的管家)* CBPeripheralManager:外部裝置(第三方的藍芽4.0裝置)![](素材/BLE.jpeg)###開發步驟* 建立中心管家```// 1. 建立中心管家,並且設定代理self.cmgr = [[CBCentralManager alloc]initWithDelegate:self queue:nil];```* 掃描外設(discover)```// 2. 在代理方法中掃描外部裝置 /**  *  scanForPeripheralsWithServices :如果傳入指定的數組,那麼就只會掃描數組中對應ID的裝置  *                                   如果傳入nil,那麼就是掃描所有可以發現的裝置  *  掃描完外部裝置就會通知CBCentralManager的代理  */ - (void)centralManagerDidUpdateState:(CBCentralManager *)central{    if ([central state] == CBCentralManagerStatePoweredOn) {        [self.cmgr scanForPeripheralsWithServices:nil options:nil];    }}``````/** *  發現外部裝置,每發現一個就會調用這個方法 *  所以可以使用一個數組來儲存每次掃描完成的數組 */- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary<NSString *,id> *)advertisementData RSSI:(NSNumber *)RSSI{    // 有可能會導致重複添加掃描到的外設    // 所以需要先判斷數組中是否包含這個外設    if(![self.peripherals containsObject:peripheral]){        [self.peripherals addObject:peripheral];    }}```* 串連外設```/** *  類比開始串連方法 */- (void)start{    // 3. 串連外設    for (CBPeripheral *ppl in self.peripherals) {        // 掃描外設的服務        // 這個操作應該交給外設的代理方法來做        // 設定代理        ppl.delegate = self;        [self.cmgr connectPeripheral:ppl options:nil];    }}```* 掃描外設中的服務和特徵    - 服務和特徵的關係            `每個藍芽4.0的裝置都是通過服務和特徵來展示自己的,一個裝置必然包含一個或多個服務,每個服務下面又包含若干個特徵。````/** *  串連外設成功調用 */- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral{    // 尋找外設服務    [peripheral discoverServices:nil];}``````/** *  探索服務就會調用代理方法 * *  @param peripheral 外設 */- (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error{    // 掃描到裝置的所有服務    NSArray *services = peripheral.services;    // 根據服務再次掃描每個服務對應的特徵    for (CBService *ses in services) {        [peripheral discoverCharacteristics:nil forService:ses];    }}```* 與外設做資料互動    - 在指定的特徵下做相應的操作```/** *  探索服務對應的特徵 */- (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error{    // 服務對應的特徵    NSArray *ctcs = service.characteristics;    // 遍曆所有的特徵    for (CBCharacteristic *character in ctcs) {        // 根據特徵的唯一標示過濾        if ([character.UUID.UUIDString isEqualToString:@"XMG"]) {            NSLog(@"可以吃飯了");        }    }}```* 中斷連線```/** *  中斷連線 */- (void)stop{    // 斷開所有串連上的外設    for (CBPeripheral *per in self.peripherals) {        [self.cmgr cancelPeripheralConnection:per];    }}```

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.