使用核心蓝牙:
在适当方法内的外围端(即 peripheralManager:didReceiveReadRequest:)
NSError *error = nil;
NSDictionary *dictionary = [NSDictionary dictionaryWithObject:anObject forKey:@"key"];
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dictionary options:NSJSONWritingPrettyPrinted error:&error];
if (error) {
//respond to error appropriately
}
request.value = jsonData;
[peripheral respondToRequest:request withResult:CBATTErrorSuccess];
在适当的方法中的中央端(即外围设备:didUpdateValueForCharacteristic:错误:)
NSError *error = nil;
NSData *jsonDataFromPeripheral = characteristic.value;
NSDictionary *theDictionary = [NSJSONSerialization JSONObjectWithData: jsonDataFromPeripheral options: NSJSONReadingAllowFragments error:&error];
if ([theDictionary objectForKey:@"key"]) {
NSLog(@"Success!");
}
如果您想将数据发送到外围设备,那么您可以像这样写入发现的特征:
NSError *error = nil;
NSDictionary *dictionary = [NSDictionary dictionaryWithObject:anObject forKey:@"key"];
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dictionary options:NSJSONWritingPrettyPrinted error:&error];
[peripheral writeValue:jsonData forCharacteristic:characteristic type:CBCharacteristicWriteWithResponse];
确保设置了外围设备的特性,以便可以执行读取和写入。您在创建 CBMutableCharacteristic 时执行此操作。这是一个例子:
CBMutableCharacteristic *characterisitic = [[CBMutableCharacteristic alloc]initWithType:[CBUUID UUIDWithString:CHARACTERISTIC_STRING] properties:CBCharacteristicPropertyRead|CBCharacteristicPropertyWrite value:nil permissions:CBAttributePermissionsReadable|CBAttributePermissionsWriteable];
请注意,如果您希望您的中心实现读取和写入,则不必为外围服务创建单独的特征。