Last active
November 27, 2016 09:49
-
-
Save nbhasin2/960ef477671f5c3623da6cc2ec050d9b to your computer and use it in GitHub Desktop.
Bluetooth Discovery / Connection
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
More links - | |
http://clover-lemongrass.cloudvent.net/blog/2015/06/11/zero-to-ble-on-ios-part-one/ | |
http://clover-lemongrass.cloudvent.net/blog/2015/10/15/developing-ios-app-using-ble-standard/ | |
Here is the complete code to discover peripheral, connect to it and discover its services and characteristics. | |
1.Connect peripheral | |
func centralManager(central: CBCentralManager, didDiscoverPeripheral peripheral: CBPeripheral, advertisementData: [String : AnyObject], RSSI: NSNumber) { | |
print("Discovered: \(peripheral.name) at \(RSSI)") | |
print("AdvertisementData:\(advertisementData)") | |
if peri != peripheral | |
{ | |
peri = peripheral | |
peri.delegate = self | |
centralManager.connectPeripheral(peri, options: nil) | |
} | |
} | |
Connection failure or success | |
func centralManager(central: CBCentralManager, didFailToConnectPeripheral peripheral: CBPeripheral, error: NSError?) { | |
print("Failed to connect \(peripheral) cause of \(error)") | |
} | |
func centralManager(central: CBCentralManager, didConnectPeripheral peripheral: CBPeripheral) { | |
print("connected to \(peripheral)") | |
// centralManager.stopScan() | |
peripheral.discoverServices(nil) | |
} | |
3.DiscoverServices | |
func peripheral(peripheral: CBPeripheral, didDiscoverServices error: NSError?) { | |
print("Services:\(peripheral.services) and error\(error)") | |
if let services = peripheral.services { | |
for service in services { | |
peripheral.discoverCharacteristics(nil, forService: service) | |
} | |
} | |
} | |
Discover Characteristics and set notification | |
func peripheral(peripheral: CBPeripheral, didDiscoverCharacteristicsForService service: CBService, error: NSError?) | |
{ | |
print("peripheral:\(peripheral) and service:\(service)") | |
for characteristic in service.characteristics! | |
{ | |
peripheral.setNotifyValue(true, forCharacteristic: characteristic) | |
} | |
} | |
Handle notification for update value of characteristics | |
func peripheral(peripheral: CBPeripheral, didUpdateValueForCharacteristic characteristic: CBCharacteristic, error: NSError?) | |
{ | |
print("characteristic changed:\(characteristic)") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment