Swift connect to bluetooth

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

Swift framework for easy connection with Bluetooth peripherals.

License

netguru/BlueSwift

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

Readme.md

Easy to use Bluetooth open source library brought to you by Netguru.
🤟 Probably the easiest way to interact with bluetooth peripherals 🤟

  • Handles connection with remote peripherals.
  • Handles advertising an iPhone as Bluetooth LE peripheral.
  • Closure based read/write/notify requests.
  • Built in data conversion method with Command wrapper.

Below you can find an easy code sample to connect to the peripheral.
Really thats all that is needed 🍾 🍾

let connection = BluetoothConnection.shared let characteristic = try! Characteristic(uuid: "your_characteristic_uuid", shouldObserveNotification: true) let service = try! Service(uuid: "your_service_uuid", characteristics: [characteristic]) let configuration = try! Configuration(services: [service], advertisement: "your_advertising_uuid") let peripheral = Peripheral(configuration: configuration) connection.connect(peripheral) < error in // do awesome stuff >

Below you can find a code sample the setup the iPhone to advertise Bluetooth.
That’s all it takes to advertise one service containing one characteristic.

let characteristic = try! Characteristic(uuid: "your_characteristic_uuid") let service = try! Service(uuid: "your_service_uuid", characteristics: [characteristic]) let configuration = try! Configuration(services: [service], advertisement: "your_service_uuid") let peripheral = Peripheral(configuration: configuration, advertisementData: [.localName("Test"), .servicesUUIDs("your_service_uuid")]) advertisement.advertise(peripheral: peripheral) < error in // oh no, something failed in that case >

Of course data transfer is also possible, both for advertising and connection mode! Below there are some basic examples, for more please see More usage section 👇🏻

let command = Command.utf8String("Hello world") peripheral.write(command: command, characteristic: someCharacteristic, handler: < error in // written! >) peripheral.read(characteristic, handler: < data, error in // read! >)
let command = Command.int8(3) advertisement.update(command, characteristic: characteristic) < error in // data updated! > advertisement.writeRequestCallback = < characteristic, data in // written! >

For more advanced usage check out documentation page at: https://netguru.github.io/BlueSwift/.
Also feel free to check example project bundled with this repository! 👩🏼‍🏫 👨🏼‍🏫 It’s a complete app that allows connection and sending text messages between two iPhones.

Читайте также:  Тойота авенсис подключить блютуз

BlueSwift can be drag’n dropped to the project directory,
but what’s more important it’s supported by most common dependency management!

Just drop the line below to your Podfile:

(but probably you’d like to pin it to the nearest major release, so pod ‘BlueSwift’ , ‘~> 1.1.5’ )

The same as with Cocoapods, insert the line below to your Cartfile:

, or including version — github ‘netguru/BlueSwift’ ~> 1.1.5

(As all cool open source software, it’s. )
Licensed under MIT license.

Also it would be really nice if you could drop us a line about your usage!! 🚀 🚀

About

Swift framework for easy connection with Bluetooth peripherals.

Источник

How to bond/pair to a bluetooth LE device programmatically in swift Xcode?

I am currently trying to develop and application that allows users to bond to a Peripheral via a click of a button and the password will be automatically entered. Is it possible to Bond and Remove Bond programmatically using swift?

You need to read a property which needs encryption (which properties includes CBCharacteristicPropertyIndicateEncryptionRequired ).

2 Answers 2

Pairing is initiated any time that you attempt to write to or read from a characteristic on the BLE device. However, if the device is not set to require authentication and/or bonding, you will not see the iOS popup which requests the PIN code.

I struggled with this with my HM-10 because I could write data to the characteristic using the Core Bluetooth (via Swift) function writeValue() without ever seeing the pairing popup.

I couldn’t figure it out until I read the HM-10 (implements the IC cc2451) datasheet very closely and found that I needed to set the AT+TYPE to value 3. It defaults to 0 which means that the HM-10 does not require pairing/bonding so you never see the iOS popup.

Читайте также:  Ps4 controller bluetooth ps3

You can read more about the details where I asked the question and ultimately found the solution and wrote it up: How do I pair and/or bond to BLE on iOS using Swift code and an HM-10 so data sent is encrypted?

I don’t know if this is the write place to ask but I asked a question on stackoverflow, regarding, on knowing when pairing/bonding has completed. I’ve been poking around CBPeripheralDelegate and nothing gets called after bonding is complete. I’d like to know when bonding is complete so that I can start reading/writing to the secure characteristic. stackoverflow.com/questions/56814487/…

@Biclops I had some trouble with this also, because I couldn’t find a method in iOS that let me know pairing was complete or successful. At some point during my tests I was able to send data (via my iOS app) to my BLE device even though the user had hit cancel on the pairing dialog. It seems like a hole in the iOS API to me, but I’m not sure.

Follow the step to connect Ble device into iOS Program.

2) Declared the variables into the class or ViewController.

 let kServiceUART = CBUUID(string: "0x1800") var peripheralHeartRateMonitor: CBPeripheral? 

var cbManger: CBCentralManager!

3) Initialize the cbManger into ViewDidLoad function of viewController or initalize function of class.

 cbManger = CBCentralManager(delegate: self, queue: .main) 

4) Override delegate method of the CBCentralManager .

 func centralManagerDidUpdateState(_ central: CBCentralManager) < switch central.state < case .unsupported: print("BLe Unsupported") break case .unauthorized: print("BLe unauthorized") break case .poweredOff: let alertMessgesInst = AlertMessages.sharedInstance CommonUtils.showAlert(alertMessgesInst.actofit_Title, message: alertMessgesInst.trun_On_blueTooth) break case .poweredOn: if isNewFirmWareOFImpulse < let uuidString = StorageServices.readFromDefaults(key: Constants.userDefaultKeys.impulseUUID) let uuid = UUID(uuidString:uuidString as! String ) let device = cbManger.retrievePeripherals(withIdentifiers: [uuid!]) peripheralHeartRateMonitor = device.first peripheralHeartRateMonitor!.delegate = self cbManger?.connect(peripheralHeartRateMonitor!) >else < let option:[String: Any] = [CBCentralManagerScanOptionAllowDuplicatesKey: NSNumber(value: false)] cbManger.scanForPeripherals(withServices: nil, options: option) >break case .unknown: print("BLe unknown") break default: break > // End Swith > // End 'centralManagerDidUpdateState' function. func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) < if isNewFirmWareOFImpulse < peripheralHeartRateMonitor = peripheral print("UUid of band is :- \(peripheralHeartRateMonitor?.identifier.uuidString)") if impulseName == peripheral.name < peripheralHeartRateMonitor!.delegate = self cbManger.stopScan() // STEP 6: connect to the discovered peripheral of interest cbManger?.connect(peripheralHeartRateMonitor!) >// End impulse condition >else < let keysArray = advertisementData.keys if let tempImpulseName = peripheral.name < print(impulseName + " and " + tempImpulseName ) if impulseName == tempImpulseName < for key in keysArray < if key == "kCBAdvDataManufacturerData"< let manufactureData = advertisementDataSwift connect to bluetooth if let stringValue = manufactureData.debugDescription as? String < var heartValue: String = String() heartValue = stringValue heartValue.removeLast() heartValue.removeLast() let last = heartValue.removeLast() let secondLast = heartValue.removeLast() let hR = String([secondLast, last]) if let value = UInt8(hR, radix: 16)< if Int(value) >60 < hrArray.append(Int(value)) >> // End the value block > // end of if 'stringValue' condition > // end 'Key' if condition > // End for each loop > // End impulse condition > // End pheripheral if condition > // end version condition > // End function 'didDiscover peripheral'. func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) < // STEP 8: look for services of interest on peripheral peripheralHeartRateMonitor?.discoverServices(nil) >// END func centralManager(. didConnect peripheral func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) < if error != nil  

Источник

Оцените статью
Adblock
detector