標籤:blog io ar os sp for strong 檔案 on
//// ViewController.m// BLEEx2//// Created by 我的未來不是夢 on 14-11-26.// Copyright (c) 2014年 choicemmed. All rights reserved.// #import "ViewController.h"// 1 導標頭檔#import <CoreBluetooth/CoreBluetooth.h>@interface ViewController () <CBCentralManagerDelegate, CBPeripheralDelegate>
@property(nonatomic, strong) CBCentralManager *mgr;@property(nonatomic, strong) NSMutableArray *peripherals;
@end @implementation ViewController- (NSMutableArray *)peripherals{ if (!_peripherals) { _peripherals = [NSMutableArray array]; } return _peripherals;} - (void)viewDidLoad {
[super viewDidLoad]; // 2 建立 中心管理者對象 CBCentralManager *mgr = [[CBCentralManager alloc] init]; mgr.delegate = self; self.mgr = mgr; // 3 掃描外設 參數傳nil 表示搜尋所有外設 [mgr scanForPeripheralsWithServices:nil options:nil]; } // 類比串連外設- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{ // 掃描外設中的服務和特徵 for (CBPeripheral *peripheral in self.peripherals) { peripheral.delegate = self;
// 利用mgr 串連外設 [self.mgr connectPeripheral:peripheral options:nil]; }} #pragma mark - CBCentralManagerDelegate// 中心管理 掃描到外設- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI{ // 將外設儲存 if (![self.peripherals containsObject:peripheral]) { [self.peripherals addObject:peripheral]; }} // 中心管理 串連外設成功(void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral{ // 掃描外設中的服務 [peripheral discoverServices:nil];} // 中心管理 串連外設失敗- (void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error{ NSLog(@"%@",error);} #pragma mark - CBPeripheralDelegate// 外設掃描到服務- (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error{ NSArray *services = peripheral.services; for (CBService *service in services) { // 取得需要的服務 if ([@"needService" isEqualToString:service.UUID.UUIDString]) { [peripheral discoverCharacteristics:nil forService:service]; } }} - (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error{ NSArray *characteristics = service.characteristics; for (CBCharacteristic *characteristic in characteristics) { if ([@"needCharacteristic" isEqualToString:characteristic.UUID.UUIDString]) { NSLog(@"do somthing~"); } }}@end
iOS中的BLE開發流程