使用核心蓝牙:
在周侧的适当的方法中(即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!");
}
如果你想发送数据到periph全部擦除,那么你可以写这样的发现特征:
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];
请注意,您不必创建一个外设的服务特点分开,如果你想你的中心来实现读取和写入。