BluetoothKit Easily communicate between iOS devices using BLE.

Overview

BluetoothKit

Easily communicate between iOS devices using BLE.

Build Status Cocoapods Compatible Carthage compatible

Background

Apple mostly did a great job with the CoreBluetooth API, but because it encapsulated the entire Bluetooth 4.0 LE specification, it can be a lot of work to achieve simple tasks like sending data back and forth between iOS devices, without having to worry about the specification and the inner workings of the CoreBluetooth stack.

BluetoothKit tries to address the challenges this may cause by providing a much simpler, modern, closure-based API all implemented in Swift.

Features

Common

  • More concise Bluetooth LE availability definition with enums.
  • Bluetooth LE availability observation allowing multiple observers at once.

Central

  • Scan for remote peripherals for a given time interval.
  • Continuously scan for remote peripherals for a give time interval, with an in-between delay until interrupted.
  • Connect to remote peripherals with a given time interval as time out.
  • Receive any size of data without having to worry about chunking.

Peripheral

  • Start broadcasting with only a single function call.
  • Send any size of data to connected remote centrals without having to worry about chunking.

Requirements

  • iOS 8.0+ / OSX 10.10+
  • Xcode 7.0+

Installation

CocoaPods

CocoaPods is a dependency manager for Cocoa projects.

CocoaPods 0.38.2 is required to build BluetoothKit. It adds support for Xcode 7, Swift 2.0 and embedded frameworks. You can install it with the following command:

$ gem install cocoapods

To integrate BluetoothKit into your Xcode project using CocoaPods, specify it in your Podfile:

source 'https://github.com/CocoaPods/Specs.git'
platform :ios, '8.0'
use_frameworks!

pod 'BluetoothKit', '~> 0.2.0'

Then, run the following command:

$ pod install

Carthage

Carthage is a decentralized dependency manager that automates the process of adding frameworks to your Cocoa application.

You can install Carthage with Homebrew using the following command:

$ brew update
$ brew install carthage

To integrate BluetoothKit into your Xcode project using Carthage, specify it in your Cartfile:

0.4.0 ">
github "rasmusth/BluetoothKit" ~> 0.4.0

Manual

Add the BluetoothKit project to your existing project and add BluetoothKit as an embedded binary of your target(s).

Usage

Below you find some examples of how the framework can be used. Accompanied in the repository you find an example project that demonstrates a usage of the framework in practice. The example project uses SnapKit and CryptoSwift both of which are great projects. They're bundled in the project and it should all build without further ado.

Common

Make sure to import the BluetoothKit framework in files that use it.

import BluetoothKit

Peripheral

Prepare and start a BKPeripheral object with a configuration holding UUIDs uniqueue to your app(s) and an optional local name that will be broadcasted. You can generate UUIDs in the OSX terminal using the command "uuidgen".

let peripheral = BKPeripheral()
peripheral.delegate = self
do {
	let serviceUUID = NSUUID(UUIDString: "6E6B5C64-FAF7-40AE-9C21-D4933AF45B23")!
	let characteristicUUID = NSUUID(UUIDString: "477A2967-1FAB-4DC5-920A-DEE5DE685A3D")!
	let localName = "My Cool Peripheral"
	let configuration = BKPeripheralConfiguration(dataServiceUUID: serviceUUID, dataServiceCharacteristicUUID: 	characteristicUUID, localName: localName)
	try peripheral.startWithConfiguration(configuration)
	// You are now ready for incoming connections
} catch let error {
	// Handle error.
}

Send data to a connected remote central.

let data = "Hello beloved central!".dataUsingEncoding(NSUTF8StringEncoding)
let remoteCentral = peripheral.connectedRemoteCentrals.first! // Don't do this in the real world :]
peripheral.sendData(data, toRemoteCentral: remoteCentral) { data, remoteCentral, error in
	// Handle error.
	// If no error, the data was all sent!
}

Central

Prepare and start a BKCentral object with a configuration holding the UUIDs you used to configure your BKPeripheral object.

let central = BKCentral()
central.delegate = self
central.addAvailabilityObserver(self)
do {
	let serviceUUID = NSUUID(UUIDString: "6E6B5C64-FAF7-40AE-9C21-D4933AF45B23")!
	let characteristicUUID = NSUUID(UUIDString: "477A2967-1FAB-4DC5-920A-DEE5DE685A3D")!
	let configuration = BKConfiguration(dataServiceUUID: serviceUUID, dataServiceCharacteristicUUID: characteristicUUID)
	try central.startWithConfiguration(configuration: configuration)
	// Once the availability observer has been positively notified, you're ready to discover and connect to peripherals.
} catch let error {
	// Handle error.
}

Scan for peripherals for 3 seconds.

central.scanWithDuration(3, progressHandler: { newDiscoveries in
	// Handle newDiscoveries, [BKDiscovery].
}, completionHandler: { result, error in
	// Handle error.
	// If no error, handle result, [BKDiscovery].
})

Scan continuously for 3 seconds at a time, with an in-between delay of 3 seconds.

central.scanContinuouslyWithChangeHandler({ changes, discoveries in
	// Handle changes to "availabile" discoveries, [BKDiscoveriesChange].
	// Handle current "available" discoveries, [BKDiscovery].
	// This is where you'd ie. update a table view.
}, stateHandler: { newState in
	// Handle newState, BKCentral.ContinuousScanState.
	// This is where you'd ie. start/stop an activity indicator.
}, duration: 3, inBetweenDelay: 3, errorHandler: { error in
	// Handle error.
})

Connect a peripheral with a connection attempt timeout of 3 seconds.

central.connect(remotePeripheral: peripherals[indexPath.row]) { remotePeripheral, error in
	// Handle error.
	// If no error, you're ready to receive data!
}

License

BluetoothKit is released under the MIT License.

Comments
  • Bluetooth LE not available or calling scan and/or connect before available

    Bluetooth LE not available or calling scan and/or connect before available

    I really appreciate that you share this amazing looking library. I downloaded the example project and ran it on a real device. But there is an issue with the bluetooth "Unsupported" or "Unavailable". The bluetooth on the device is active and the error says: Error from scanning: InternalError(Optional(BluetoothKit.BKCentralStateMachine.Error.Transitioning(BluetoothKit.BKCentralStateMachine.State.Unavailable(BluetoothKit.BKUnavailabilityCause.Unsupported), [BluetoothKit.BKCentralStateMachine.State.Available])))

    If you can help me, I would be thankful tastyapp

    opened by antoinebeneteau 21
  • OS X to iOS

    OS X to iOS

    May I ask some questions? I want my iPhone connect to my mac.which one do you think should be my Peripheral? And I want to keep running in background,so my mac app could connect with my iPhone(From a distance to close),how can I deal with this? thank you.

    question 
    opened by lfb-cd 15
  • tvos support

    tvos support

    tvOS is pretty new and as far as I figured out some feature are not available (yet), but do you plan to add support for it next releases even for cocoapods auto install?

    enhancement 
    opened by matteocrippa 10
  • CocoaPods release is not compatible with Swift 3

    CocoaPods release is not compatible with Swift 3

    Hey, great work as it seems!

    Unfortunately, it seems to me that you integrated Swift 3 support, but you didn't release it to CocoaPods yet, is there a specific reason for that?

    Cheers!

    opened by Hustenbonbon 7
  • peripheral.sendData very slow if NSData is larger than a few bytes

    peripheral.sendData very slow if NSData is larger than a few bytes

    Hi there - love the library so far.

    Using the example application, I have been experimenting with reading a file to NSData, then sending the NSData using the "sendData" method.

    However, if the NSData I'm sending is even a few KB, the transmission takes a very, very long time. For a 250KB NSData, I'm seeing times around 1-1.5 minutes to do the transfer. Am I doing something wrong, or is this a limitation of the library? Thanks!

    opened by matthewkrueger 5
  • Multiple characteristics per service

    Multiple characteristics per service

    If I'm reading things correctly, it looks like BluetoothKit as written only supports a single characteristic per service. Is that correct?

    If so, that's a rather crippling limitation on an otherwise well-designed library. I'm working on a project designing a new BLE device and app, with a complex custom BLE service with multiple read/write characteristics.

    opened by cpatterson 5
  • fixed build on xcode 8.0 with swift 3.0

    fixed build on xcode 8.0 with swift 3.0

    error: 1.Function types cannot have argument label 'xxx'; use '_' instead for typealias rename xxx to _xxx

    2.'ErrorProtocol' has been renamed to 'Error' rename ErrorProtocol to Error and rename inner Error to BKError

    3.Method 'xxx' with Objective-C selector 'xxx' conflicts with previous declaration with the same Objective-C selector add @nonobjc on this method

    opened by zhouliangshun 4
  • ios10: removed willRestoreState delegate so we get no warning about missing restorationID

    ios10: removed willRestoreState delegate so we get no warning about missing restorationID

    Hi, for ios10: removed willRestoreState delegate so we get no warning about missing restorationID

    // internal func peripheralManager(peripheral: CBPeripheralManager, willRestoreState dict: [String : AnyObject]) { // // print("peripheralManager: (peripheral) willRestoreState: (dict)") // }

    opened by Daij-Djan 4
  • Adds Swift Package Manager support

    Adds Swift Package Manager support

    I just tried out the project but was a little scared by the amount of warning. So I reduced them down to one. The TODO in BKContinousScanner.swift:101 is still there.

    opened by ricobeck 3
  • Option to disable chunking feature to improve compatibility with non bluetoothKit devices

    Option to disable chunking feature to improve compatibility with non bluetoothKit devices

    Added BKConfiguration option to disable the chunking feature in BluetoothKit. This to enable compatibility with non bluetoothKit devices. The linter made some changes though. That's in a separate commit. Please see the first commit and those changes.

    opened by iain17 3
  • fail to build with carthage

    fail to build with carthage

    Hi,

    using this line, in my cart file
    github "rasmusth/BluetoothKit" ~> 0.2.0 using carthage v 0.18.1, Xcode 8.1, Sierra 10.12.1

    fail, with a dependency error code 65. the log is long, I can provide it, if needed.

    I noticed that in the checkout folder, the bluetooth project seem to be in swift 2...

    if I download the project, manually, from github : it compile straight away.

    thanks for any help Olivier

    opened by olivier38070 3
  • Configuration does not support full scan

    Configuration does not support full scan

    Problem: let configuration = BKConfiguration(dataServiceUUID: serviceUUID, dataServiceCharacteristicUUID: characteristicUUID) try central.startWithConfiguration(configuration)

    I want to scan all Bluetooth devices. I find that the configuration item cannot be set, and the UUID is empty, but the device cannot be scanned

    opened by bird1423 0
  • Data Transfer Size Limitation

    Data Transfer Size Limitation

    Is there a limitation in data transfer size? can transfer small size of data but once the size increase data cannot be received? issues is generally seen when data gets higher in size which is 60000, 70000 bytes.

    my data sending code,

    let navLogData = NSKeyedArchiver.archivedData(withRootObject: navDict) Logger.info("Sending to (remotePeripheral.name)") central.sendData(navLogData, toRemotePeer: remotePeripheral) { data, remotePeripheral, error in guard error == nil else { Logger.info("Failed sending to (remotePeripheral)") Utils.showAlert(title: "", msg: "Failed to send data. Please Try Again", alertType: .ok, cancelHandler: nil) { _ in
    } return }

    opened by hrishav503 0
  • Crashes when send large data.

    Crashes when send large data.

    Thanks for the great project. It works perfectly when sending small amount of data (e.g., < 1k). However, crashes when sending large data (e.g., ~1M bytes). Looks like the processSendDataTasks function used in sendData is recursive (e.g., on my phone, each call sends 182 bytes). Does it mean that it doesn't support sending large data (e.g., ~M bytes) (limited by the stack size)?

    Why do we use a recursive function to send all data? Will a "for" loop work? Thanks!

    https://github.com/rhummelmose/BluetoothKit/blob/2f268e43495db001ae92d9fedf1982e0e69d29da/Source/BKPeer.swift#L67

    opened by tianzhuqiao 2
  • keyboard and mouse bluetooth driver

    keyboard and mouse bluetooth driver

    Hi, I searched many open source projects and couldnt find any answer and someone here might know and help.

    I want to create a virtual keyboard or mouse in mac which will connect to iphone via bluetooth and my keyboard and mouse events in macos are applied to ios device.

    any help is appreciated. thanks

    opened by krishtoautomate 0
Owner
Rasmus Høhndorf Hummelmose
Techie at @microsoft, co-founder at @Wallmob
Rasmus Høhndorf Hummelmose
The easiest way to use Bluetooth (BLE )in ios,even bady can use.

The easiest way to use Bluetooth (BLE )in ios,even bady can use.

刘彦玮 4.6k Dec 27, 2022
MacOS app which allows drag and drop of images to BLE thermal printers

Print2BLE Copyright (c) 2021 BitBank Software, Inc. Written by Larry Bank [email protected] What is it? This project is a MacOS GUI applicatio

Larry Bank 37 Jan 5, 2023
This is a simple app, which scans for BLE Peripherials and connect to them. The example works with NORDIC_UART_SERVICE.

BLE Serial IOs Example This is a simple app, which scans for BLE Peripherials and connect to them. The example works with NORDIC_UART_SERVICE. UUIDS H

Muhammad Hammad 4 May 10, 2022
BLE (Bluetooth LE) for U🎁 Bleu is the best in the Bluetooth library.

Bleu Bleu is a Bluetooth library. Bleu is the easiest way to operate CoreBluetooth. Bleu is possible to operate by replacing Bluetooth 's Peripheral a

1amageek 484 Dec 29, 2022
Swift implementation of Xiaomi's BLE authentication

MiAuth Xiaomi M365/Mi Authentication library written in Swift. Features M365 Authentication Mi Authentication (WIP - Login doesn't work reliably yet)

null 2 Jul 27, 2022
📱📲 A wrapper for the MultipeerConnectivity framework for automatic offline data transmission between devices

A wrapper for Apple's MultipeerConnectivity framework for offline data transmission between Apple devices. This framework makes it easy to automatical

Wilson Ding 197 Nov 2, 2022
Fluetooth - Flutter library for sending bytes to Bluetooth devices on Android/iOS

A Flutter library for sending bytes to Bluetooth devices. Available on Android a

Iandi Santulus 1 Jan 2, 2022
Build your own 'AirTags' 🏷 today! Framework for tracking personal Bluetooth devices via Apple's massive Find My network.

OpenHaystack is a framework for tracking personal Bluetooth devices via Apple's massive Find My network.

Secure Mobile Networking Lab 5.8k Jan 9, 2023
A very simple library to discover and retrieve data from nearby devices (even if the peer app works at background).

Discovery: A simple library to discover and retrieve data from nearby devices. Discovery is a very simple but useful library for discovering nearby de

Ömer Faruk Gül 412 Dec 19, 2022
A simple framework that brings Apple devices together - like a family

Apple Family A simple framework that brings Apple devices together - like a family. It will automatically use bluetooth, wifi, or USB to connect and c

Kiran 62 Aug 21, 2022
The official Swift Library for Vital API, HealthKit and Devices

vital-ios The official Swift Library for Vital API, HealthKit and Devices Install We currently support SPM. Documentation Please refer to the official

Vital 17 Dec 22, 2022
iOS Bluetooth LE framework

Features A futures interface replacing protocol implementations. Timeout for Peripheral connection, Service scan, Service + Characteristic discovery a

Troy Stribling 696 Dec 25, 2022
Blocks Based Bluetooth LE Connectivity framework for iOS/watchOS/tvOS/OSX. Quickly configure centrals & peripherals, perform read/write operations, and respond characteristic updates.

ExtendaBLE Introduction ExtendaBLE provides a very flexible syntax for defining centrals and peripherals with ease. Following a blocks based builder a

Anton 94 Nov 29, 2022
AZPeerToPeerConnectivity is a wrapper on top of Apple iOS Multipeer Connectivity framework. It provides an easier way to create and manage sessions. Easy to integrate

AZPeerToPeerConnection Controller Features Multipeer Connectivity Connection via Bluetooth or Wifi No need write all session, browser, services delega

Afroz Zaheer 66 Dec 19, 2022
ScanID - Homework iOS project to scan IDs MRZ code

ScanID Homework iOS project to scan IDs MRZ code Requirements for mobile applica

Artūrs Āre 0 Jan 28, 2022
The Bluetooth LE library for iOS and Mac. 100% Swift.

iOS-BLE-Library An in-development Bluetooth Low Energy Library by Nordic Semiconductor to interact with the , which is not complicated, but requires w

Nordic Semiconductor 6 Dec 19, 2022
Easily communicate between iOS/OSX devices using BLE

BluetoothKit Easily communicate between iOS devices using BLE. Background Apple mostly did a great job with the CoreBluetooth API, but because it enca

Rasmus Høhndorf Hummelmose 2.1k Dec 29, 2022
RxBluetoothKit is a Bluetooth library that makes interaction with BLE devices much more pleasant.

RxBluetoothKit is a Bluetooth library that makes interaction with BLE devices much more pleasant. It's backed by RxSwift and CoreBluetooth and it prov

Polidea 1.3k Jan 6, 2023
OpenOSCKit - Communicate among computers, sound synthesizers, and other multimedia devices via OSC over an IP network

OpenOSCKit The OpenOSCKit package provides the classes needed for your apps to c

Dan Murfin 7 Feb 3, 2022
Contains common infrastructural code for apps to communicate among computers, sound synthesizers, and other multimedia devices via OSC.

The CoreOSC package contains common infrastructural code for your apps to communicate among computers, sound synthesizers, and other multimedia devices via OSC.

Sammy Smallman 3 Oct 7, 2022