This is the simple code I wrote to test the Bluetooth in XCode. My intention with is this to connect to my JBL speaker to play the bell sound when I click the button. However, my JBL speaker is never picked up as a printed pname. Can anyone please help me with this? Thanks!
import UIKit
import CoreBluetooth
import AVFoundation
class ViewController: UIViewController, CBCentralManagerDelegate, CBPeripheralDelegate {
var centralManager: CBCentralManager!
var myPeripheral: CBPeripheral!
var audioPlayer = AVAudioPlayer()
override func viewDidLoad() {
super.viewDidLoad()
// Initialize central manager
centralManager = CBCentralManager(delegate: self, queue: nil)
// Audio
do {
audioPlayer = try AVAudioPlayer(contentsOf:
URL.init(fileURLWithPath: Bundle.main.path(forResource: "bell", ofType: "wav")!))
audioPlayer.prepareToPlay()
} catch{
print(error)
}
}
func centralManagerDidUpdateState(_ central: CBCentralManager) {
// Turned on
if central.state == CBManagerState.poweredOn {
print("BLE powered on.")
central.scanForPeripherals(withServices: nil, options: nil)
}
// Not on, could be different issues
else {
print("Something wrong with BLE.")
}
}
func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String: Any], rssi RSSI: NSNumber){
// Get the peripheral.name
if let pname = peripheral.name{
print(pname)
if pname == "JBL Speaker"{
// found wanted device so stop
self.centralManager.stopScan()
// assign it to myperipheral object
self.myPeripheral = peripheral
self.myPeripheral.delegate = self
//
self.centralManager.connect(peripheral, options: nil)
}
}
}
// Connected
func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) {
self.myPeripheral.discoverServices(nil)
print("Connected")
}
@IBAction func clickBell(_ sender: Any) {
audioPlayer.play()
}
}