取得UUID
先前文章CoreBluetooth For Central (3)中,在didDiscoverPeripheral
Delegate取得可連線裝置的物件CBPeripheral
,
1
2
3
4
5
6
|
//-----------start-----------
- (
void
)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(
NSDictionary
*)advertisementData RSSI:(
NSNumber
*)RSSI {
NSLog
(@
"%"
,peripheral);
}
//------------end------------
|
將CBPeripheral
內容印出時會得到下面內容:
<CBPeripheral: 0x14d3f810 identifier = 9D027D39-5A77-3B6B-BC45-5A1E00115269, Name = "TI BLE Keyfob", state = disconnected>
其中identifier
為裝置的UUID,將它記錄下來可以在重新連線中使用。
重新連線方法
重新連線的方式依照iOS版本分為兩種如下:
iOS 7 以前
- (void)retrievePeripherals:(NSArray *)peripheralUUIDs
iOS 8 之後
- (NSArray *)retrievePeripheralsWithIdentifiers:(NSArray *)identifiers
iOS 7之前使用上只需利用此方法後,整個過程就會自動連線至裝置,但iOS 8之後分的比較細,個人認為比較有流程,也就是需要使用此方法取得裝置的CBPeripheral
物件後,再利用此物件來連線,意思iOS 8需要兩個流程:
-
取得裝置CBPeripheral
-
連線至裝置
該方法在使用時可以傳入多個UUID,後續流程也相同,範例中都只針對單一BLE週邊連線做說明。
使用UUID連線至裝置
這裡有兩個版本的程式如下:
iOS 7
1
2
3
4
|
//-----------start-----------
CFUUIDRef uuid = CFUUIDCreateFromString(
nil
, (CFStringRef) @
"9D027D39-5A77-3B6B-BC45-5A1E00115269"
);
[CM retrievePeripherals:[
NSArray
arrayWithObject:(__bridge
id
)(uuid) ]];
//------------end------------
|
iOS 8
1
2
3
4
5
6
7
8
9
10
11
|
//-----------start-----------
<br> NSUUID *uuid = [[NSUUID UUID] initWithUUIDString:@
"9D027D39-5A77-3B6B-BC45-5A1E00115269"
];
NSArray
*peripheralArray = [CM retrievePeripheralsWithIdentifiers:[
NSArray
arrayWithObject:uuid]];
//成功後會返回裝置CBPeripheral物件,範例使用UUID只傳入一個UUID至陣例,所以陣列返回內容只會有一個物件
if
(peripheralArray.count>0) {
NSLog
(@
"%@"
,[peripheralArray objectAtIndex:0]);
[CM connectPeripheral:[peripheralArray objectAtIndex:0] options:
nil
];
}
else
{
NSLog
(@
"fail"
);
}
//------------end------------
|
後續的過程、Service的使用需一般方式相同,這裡附帶一提的是,iOS 8後將UUID改由NSUUID
物件來管理使用,當然也變的比較方便。
http://cms.35g.tw/coding/corebluetooth-central-5/