Easily communicate between iOS/OSX 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:

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
iOS & OSX Bluetooth library for RxSwift

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 Dec 16, 2022
WatchCon is a tool which enables creating easy connectivity between iOS and WatchOS.

WatchCon WatchCon is a tool which enables creating easy connectivity between iOS and WatchOS Requirements iOS 9.0+ / watchOS 2.0+ CocoaPods CocoaPods

Abdullah Selek 33 Sep 22, 2022
Easily take a photo or video or choose from library

FDTake Easily take a photo or video or choose from library ?? Author's tip jar: https://amazon.com/hz/wishlist/ls/EE78A23EEGQB Usage To run the exampl

William Entriken 322 Nov 30, 2022
Swift library to easily check the current device and some more info about it.

Usage To run the example project, clone the repo, and run pod install from the Example directory first. let device = Deviice.current device is a Devi

Andrea Mario Lufino 56 Nov 3, 2022
Demo using Terminal.Gui with Llama Swift

Hola! This repo is a demo which shows the use of Llama Swift with Terminal.Gui. Llama is my exploratory project to compile "other languages" for .NET

Eric Sink 6 May 22, 2021
This is an POC for showing current Air Quality of different Cities in graphical format using webSocket

Air-Quality-Monitoring This is an POC for showing current Air Quality of different Cities in graphical format using webSocket. It Used danielgindi/Cha

null 1 Jun 14, 2022
AmiiboReader - Reading data from amiibo by using Core NFC

AmiiboReader Reading data from amiibo by using Core NFC NTAG215 Data Sheet https

Shinichiro Oba 7 Mar 24, 2022
Library for iOS Camera API. Massively increase performance and ease of use within your next iOS Project.

CameraKit helps you add reliable camera to your app quickly. Our open source camera platform provides consistent capture results, service that scales,

CameraKit 628 Dec 27, 2022
A better way to operate QR Code in Swift, support iOS, macOS, watchOS and tvOS.

EFQRCode is a lightweight, pure-Swift library for generating stylized QRCode images with watermark or icon, and for recognizing QRCode from images, in

EFPrefix 4.3k Jan 2, 2023
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
You will learn how to scan QR code with iOS framework.

QR Code Scanner You will learn how to scan QR code with in iOS without using any library. It is as simple to scan QR code in iOS. In this example, We

Nitin Aggarwal 11 Dec 8, 2022
Luminous provides you a lot of information about the system and a lot of handy methods to quickly get useful data on the iOS platform.

Luminous Example To run the example project, clone the repo, and run pod install from the Example directory first. Requirements iOS 8+ Swift 5 Xcode 1

Andrea Mario Lufino 324 Nov 27, 2022
TapticEngine generates haptic feedback vibrations on iOS device.

TapticEngine Overview TapticEngine generates haptic feedback vibrations on iOS device. This library wrapps on UIImpactFeedbackGenerator, UISelectionFe

WorldDownTown 253 Oct 28, 2022
NFCPassportReader for iOS 13

NFCPassportReader This package handles reading an NFC Enabled passport using iOS 13 CoreNFC APIS THIS IS AN IN-PROGRESS BRANCH AND NOT EVEN REMOTELY S

Andy Qua 581 Dec 27, 2022
Just simple template - example how to use haptics in iOS Development

Haptics Just simple template - example how to use haptics in iOS Development imp

Alexander Ryakhin 1 Jan 31, 2022
Grab kbsync dynamically from your jailbroken iOS device.

KbsyncTool Grab kbsync dynamically from your jailbroken iOS device. Usage Test1:~ root# kbsynctool -s 9000 [DEBUG] Did open IPv4 listening socket 3 [D

i_82 13 Oct 31, 2022
Writes twitter and contact (links) to writable nfcs on iPhone 7+ iOS 14+

nfc writer ios app nfc writer app is a hacky fun side project that writes twitter and contact (links) to writable nfcs. runs on iPhone 7+ iOS 14+. joi

Vivian Phung 5 Nov 23, 2022
BluetoothKit Easily communicate between iOS 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 Jan 8, 2023
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