Since the rise of BLE devices like StickNFind, which can be used in many applications such as Indoor Navigation, Finding Stuff and other useful applications, you would need to build an application that use the power of BLE.
The first step in building a mobile application that uses BLE devices is to know how to scan for them. If you checked the Core Bluetooth Framework Reference you can find a list of all classes and protocols you will need to handle every single scenario in the BLE world.
Here we are going to concentrate on 2 classes and 1 protocol
As mentioned in the reference CBCentralManager objects are used to manage discovered or connected remote peripheral devices, including scanning for, discovering, and connecting to advertising peripherals. While the CBPeripheral class represents remote peripheral devices that your app—by means of a central manager (an instance of CBCentralManager)—has discovered advertising or is currently connected to. And the CBCentralManagerDelegate protocol defines the methods that a delegate of a CBCentralManager object must adopt.
Creating a wrapper class
We will create a wrapper class to wrap all the functionality that deals with BLE, let's call it BLEManager and initially it will be empty.
Creating a CBCentralManager
Now we want to add a central manager and initialize it, but to initialize a central manager you will need a central manager delegate that implements the functions needed by the central manager to perform its tasks
So, what happens here is that
Creating a CBCentralManagerDelegate
Now we want to create a class called BLEHandler and make a our delegate, so for any class to act as as a CBCentralManagerDelegate it should adopts the CBCentralManagerDelegate protocol.
There is only one required function to be implemented in the delegate which is the centralManagerDidUpdateState function.
The code of the function is user-defined, but to know what code to write in this function we should know first when this function is called, its called when the central manager is first created and whenever its state changed.
So we can check the state of the BLE in this function by the following code
The central manager that changed its state is passed in the function parameters, so we can check its state easily
Now we have a complete code for the BLEManager that compiles and runs but doesn't scan or report any nearby devices, so we have to do 2 things
Simply, if the state is powered ON, start scanning, else do not start scanning
Did Discovered Peripheral ?
Central Manager: Scanning ... Scanning ... Scanning ... Scanning ... Device Discovered .. Let's call some function in our delegate that deals with a discovered peripheral
The signature of this function seems complex but it gives you everything you need to deal with the detected device, here I wrote a simple one line of code that prints its name and RSSI (Received Signal Strength Indication)
Run this code
We have already implemented a complete BLE Manager that detected nearby devices, but we haven't called it anywhere yet.
All you have to do now is to create a variable of type BLEManager and call it's initializer, as follows
You write these lines in the viewDidLoad function of your viewer but ensure that the first line (the variable definition) will not be deleted automatically by defining it as a local variable in the view controller class instead of the viewDidLoad function to last for the lifetime of the view controller.
Final notes
Where to go from here ?
Now you have a sample code that scan for devices, after that you can search for other functionality that the central manager can do and can be implemented in the delegate like connecting do devices and sending/receiving data to/from devices.
This is a small book that talks briefly about BLE 4.0 technology, you can understand the BLE APIs easily if you understand the BLE technology well.
Finally, try to take a look at iBeacon
New to iOS/Swift ?
This course is taught by Kunal Chawla and it is really a great start for iOS development with Swift.
Thanks for reading my blog
The first step in building a mobile application that uses BLE devices is to know how to scan for them. If you checked the Core Bluetooth Framework Reference you can find a list of all classes and protocols you will need to handle every single scenario in the BLE world.
Here we are going to concentrate on 2 classes and 1 protocol
- CBCentralManager (class)
- CBPeripheral (class)
- CBCentralManagerDelegate (protocol)
As mentioned in the reference CBCentralManager objects are used to manage discovered or connected remote peripheral devices, including scanning for, discovering, and connecting to advertising peripherals. While the CBPeripheral class represents remote peripheral devices that your app—by means of a central manager (an instance of CBCentralManager)—has discovered advertising or is currently connected to. And the CBCentralManagerDelegate protocol defines the methods that a delegate of a CBCentralManager object must adopt.
Creating a wrapper class
We will create a wrapper class to wrap all the functionality that deals with BLE, let's call it BLEManager and initially it will be empty.
Creating a CBCentralManager
Now we want to add a central manager and initialize it, but to initialize a central manager you will need a central manager delegate that implements the functions needed by the central manager to perform its tasks
- We added a local variable of type CBCentralManager
- We added a local variable of type BLEHandler which acts as a delegate (Note: we will create this class in a minute)
- We initialize the ble handler
- And finally we initialize the central manager
Creating a CBCentralManagerDelegate
Now we want to create a class called BLEHandler and make a our delegate, so for any class to act as as a CBCentralManagerDelegate it should adopts the CBCentralManagerDelegate protocol.
There is only one required function to be implemented in the delegate which is the centralManagerDidUpdateState function.
The code of the function is user-defined, but to know what code to write in this function we should know first when this function is called, its called when the central manager is first created and whenever its state changed.
So we can check the state of the BLE in this function by the following code
The central manager that changed its state is passed in the function parameters, so we can check its state easily
Now we have a complete code for the BLEManager that compiles and runs but doesn't scan or report any nearby devices, so we have to do 2 things
- Start scanning somewhere in our code
- Catch detected devices somewhere in our code
Try to answer these 2 questions before going down ...
Start Scanning
When I ask my central manager to start scanning for BLE devices, I should be sure 100% that the Bluetooth is ready, working and ON on my devices. It shouldn't be unsupported, unauthorized, unknown, resetting or powered off. Seems intuitive !! YES :)
OUR BLE SHOULD BE POWERED ON
OUR BLE SHOULD BE POWERED ON
If you rechecked the piece of code that checks the state of the BLE and read the previous paragraph carefully, you would easily answer the first question by the following piece of code
Simply, if the state is powered ON, start scanning, else do not start scanning
Did Discovered Peripheral ?
Central Manager: Scanning ... Scanning ... Scanning ... Scanning ... Device Discovered .. Let's call some function in our delegate that deals with a discovered peripheral
The signature of this function seems complex but it gives you everything you need to deal with the detected device, here I wrote a simple one line of code that prints its name and RSSI (Received Signal Strength Indication)
Run this code
We have already implemented a complete BLE Manager that detected nearby devices, but we haven't called it anywhere yet.
All you have to do now is to create a variable of type BLEManager and call it's initializer, as follows
You write these lines in the viewDidLoad function of your viewer but ensure that the first line (the variable definition) will not be deleted automatically by defining it as a local variable in the view controller class instead of the viewDidLoad function to last for the lifetime of the view controller.
- You can wrap the functionality however you want, the BLEManager is just a simple way to wrap and manage things easily.
- You can start scanning whenever and wherever you want, not necessary with the creation of the BLEManager (in this code) but do not forget to ensure that the BLE state is poweredOn
- Ensure the the BLEManager (specifically), the central manager will last for the lifetime of the application and it's not created as a local variable in a function that will end and clear its local variables.
Where to go from here ?
Now you have a sample code that scan for devices, after that you can search for other functionality that the central manager can do and can be implemented in the delegate like connecting do devices and sending/receiving data to/from devices.
This is a small book that talks briefly about BLE 4.0 technology, you can understand the BLE APIs easily if you understand the BLE technology well.
Finally, try to take a look at iBeacon
New to iOS/Swift ?
This course is taught by Kunal Chawla and it is really a great start for iOS development with Swift.
Thanks for reading my blog
Hello.
ReplyDeleteThanks for the great tutorial.
I'm trying to get my app to do exactly what it says here. However nothing is displayed in the console at the end.
Any idea what the issue could be? Does the application have to request access to the bluetooth? If so, how do I go about doing this?
Ben
Yeah,
DeleteI am having the same issue...
I am having the same issue, anyone found the solution yet?
DeleteI am clicking the button, but nothing is getting displayed
como hacer que esta funcion se ejecute aun cuando la aplicacion no se esta ejecutando
ReplyDeletethanks for making the code available. when I try compiling the code i get an error stating: "BLEHandler does not conform to protocol CBCentralManagerDelegate. Any idea why that is?
ReplyDeleteyou need to implement func centralManagerDidUpdateState(central: CBCentralManager) {
Delete}
Swift is a robust and intuitive programming language created by Apple for building apps.Employ the service of Volive developer and lets turn your app into someone great ahead of other competitors with the use of Swift.
ReplyDeleteswift Mobile app Development
self.centralManager = CBCentralManager(delegate:self, queue:nil)
ReplyDelete-> error: Cannot convert value of type 'BLEManager' to expected argument type 'CBCentralManagerDelegate?'
Guys just move the variable declaration to the very top of your class
ReplyDeletesmth like:
class ViewController: NSViewController {
var bleManager : BLEManager!
...
Great comment. This is the solution of error. BTW, do not forget to add environment variable of NSZombieEnabled = YES
DeleteThanks for posting useful information.You have provided an nice article, Thank you very much for this one. And i hope this will be useful for many people.. and i am waiting for your next post keep on updating these kinds of knowledgeable things...Really it was an awesome article...very interesting to read..
ReplyDeleteplease sharing like this information......
Android training in chennai
Ios training in chennai
You have provided an nice article, Thank you very much for this one. And i hope this will be useful for many people.. and i am waiting for your next post keep on updating these kinds of knowledgeable things...
ReplyDeleteMobile App Development Company
Mobile App Development Company
Mobile app Development Companies
This comment has been removed by the author.
ReplyDeleteYou are shared a wonderful information,& great article. Android Application Development Company Bangalore
ReplyDeleteits looking great ios Online Training Bangalore
ReplyDeleteI wish we had those code snippets as text not images or source available for ease download. But thanks for hint to make wrapper class for BLE. Best - Sunzala Technology
ReplyDeleteThank you for your post. This is excellent information. It is amazing and wonderful to visit your site.
ReplyDeleteios app development course
This comment has been removed by the author.
ReplyDeleteThe article is good.I got some knowledge about iOS.Thanks for sharing this blog.
ReplyDeleteiOS Training In Chennai | iOS Training Institute In Chennai
The Content was super and useful.Thankyou for posting this blog.I got some knowledge.
ReplyDeleteiOS Training In Chennai | iOS Training Institute In Chennai
I liked the way of presention.Its good and Informative.Thank you for posting this article
ReplyDeleteiOS Training In Chennai | iOS Training Institute In Chennai
This is an one of the excellent blog.I liked your way of presentation.I gained some Information.Thank you for posting this articleiOS Training In Chennai | iOS Training Institute In Chennai
ReplyDeleteIts really good article.I got new information.Tyhank you for posting this articleiOS Training In Chennai | iOS Training Institute In Chennai
ReplyDeleteThankyou for posting this article.I got clear idea.Its easy to understand and the presentation is good
ReplyDeleteiOS Training in Chennai | iOS Training Institute in Chennai
Custom Android App Development Company Lucknow India| Android App Development Services USA| Top Android App Development Agency UK
ReplyDeleteThanks a lot very much for the high quality and results-oriented help. I won’t think twice to endorse your blog post to anybody who wants and needs support about this area.
ReplyDeletedigital marketing training in annanagar
digital marketing training in marathahalli
digital marketing training in rajajinagar
Digital Marketing online training
full stack developer training in pune
The knowledge of technology you have been sharing thorough this post is very much helpful to develop new idea. here by i also want to share this.
ReplyDeletefull stack developer training in annanagar
full stack developer training in tambaram
full stack developer training in velachery
Nice tutorial. Thanks for sharing the valuable information. it’s really helpful. Who want to learn this blog most helpful. Keep sharing on updated tutorials…
ReplyDeletepython training institute in chennai
python training in Bangalore
python training institute in chennai
Thank you for allowing me to read it, welcome to the next in a recent article. And thanks for sharing the nice article, keep posting or updating news article.
ReplyDeleteData Science training in rajaji nagar
Data Science training in chennai
Data Science training in electronic city
Data Science training in USA
Data science training in pune
Data science training in kalyan nagar
Thanks you for sharing this unique useful information content with us. Really awesome work. keep on blogging
ReplyDeletejava training in omr | oracle training in chennai
java training in annanagar | java training in chennai
Nice post. By reading your blog, i get inspired and this provides some useful information. Thank you for posting this exclusive post for our vision.
ReplyDeleteangularjs Training in bangalore
angularjs Training in btm
angularjs Training in electronic-city
angularjs online Training
angularjs Training in marathahalli
Whoa! I’m enjoying the template/theme of this website. It’s simple, yet effective. A lot of times it’s very hard to get that “perfect balance” between superb usability and visual appeal. I must say you’ve done a very good job with this.
ReplyDeleteAWS Training in Bangalore | Amazon Web Services Training in bangalore , india
AWS Training in pune | Amazon Web Services Training in Pune, india
AWS Training in Chennai|Amazon Web Services Training in Chennai,India
aws online training and certification | amazon web services online training ,india
Hi! Thank you for the share this information. This is very useful information for online blog review readers. Keep it up such a nice posting like this.
ReplyDeleteWebsite Design
SEO Company
Wonderful blog!!! I would like to share with my colleagues and friends.
ReplyDeleteSelenium Training in Chennai
Best Selenium Training Institute in Chennai
ios developer training in chennai
Digital Marketing Training in Chennai
.Net coaching centre in chennai
Future of testing professional
Different functions in testing
cloud computing training centers in chennai
cloud computing training institutes in chennai
: Inject jQuery and a custom javascript (CSK_CC_SAFARI) which replaces the capitalized ID value (e.g.: id = 'CCNUMBER') with the mixed case ID value (e.g.: id = 'ccNumber'). Refer following section for more details.
ReplyDelete- For chrome browsers: Include the autocomplete attribute for all the credit card form fields. scscan
One of the key features said to be coming to
ReplyDeletethe HomePod is the ability to make or receive phone calls
Read More At iOS Online Course
Good Post, Keep Sharing!
ReplyDeleteJava Training in Chennai
Python Training in Chennai
IOT Training in Chennai
Selenium Training in Chennai
Data Science Training in Chennai
FSD Training in Chennai
MEAN Stack Training in Chennai
Thanks for the good words! Really appreciated. Great post. I’ve been commenting a lot on a few blogs recently, but I hadn’t thought about my approach until you brought it up.
ReplyDeletedevops online training
aws online training
data science with python online training
data science online training
rpa online training
This comment has been removed by the author.
ReplyDeleteThanks for this great information,
ReplyDeletei'm really appreciate your information related to swift mobile app |
ios development with swift
Such a nice post, thanks for sharing this with us really so impressible and attractive post. I really happy to read your great post. Keep it up to the good work!!
ReplyDeleteArtificial Intelligence Course
Glad to chat your blog, I seem to be forward to more reliable articles and I think we all wish to thank so many good articles, blog to share with us.
ReplyDelete360digitmg data analytics course malaysia
Nice information, valuable and excellent design, as share good stuff with good ideas and concepts, lots of great information and inspiration, both of which I need, thanks to offer such a helpful information here.
ReplyDeletedata analytics courses malaysia
click here for more info.
ReplyDeleteclick here for more info.
ReplyDelete
ReplyDeleteclick here for more info.
................................................................
click here for more info.
ReplyDeleteYou have provided an nice article, Thank you very much for this one. And i hope this will be useful for many people.. and i am waiting for your next post keep on updating these kinds of knowledgeable things...
ReplyDeleteMicrosoft Windows Azure Training | Online Course | Certification in chennai | Microsoft Windows Azure Training | Online Course | Certification in bangalore | Microsoft Windows Azure Training | Online Course | Certification in hyderabad | Microsoft Windows Azure Training | Online Course | Certification in pune
A debt of gratitude is in order for sharing this marvelous information.I have taken in numerous things from your post nice to read.
ReplyDeleteAi & Artificial Intelligence Course in Chennai
PHP Training in Chennai
Ethical Hacking Course in Chennai Blue Prism Training in Chennai
UiPath Training in Chennai
"This blog is very nice
ReplyDelete.
Digital Marketing Training Course in Chennai | Digital Marketing Training Course in Anna Nagar | Digital Marketing Training Course in OMR | Digital Marketing Training Course in Porur | Digital Marketing Training Course in Tambaram | Digital Marketing Training Course in Velachery
"
Thanks for your contribution in sharing such a useful information. This was really helpful to me. Waiting for your further updates.
ReplyDeleteJava training in Chennai
Java training in Bangalore
Java training in Hyderabad
Java Training in Coimbatore
Java Online Training
Your good knowledge and kindness in playing with all the pieces were
ReplyDeletevery useful. I don’t know what I would have done if I had not
encountered such a step like this.
unix training in chennai
Software training institute in chennai
video-game-game-criteria-for-players-players-genesis-isis-a - Video
ReplyDelete› Videos-Game-criteria-for-players-genesis-is › Videos-Game-criteria-for-players-genesis-is-a › Videos-Game-criteria-for-players-genesis-is-a Watch, Download and Stream: 918 views. $35.50. May 29, 2019. $35.50. May 29, 2019. $36.50. May 30, 2019. $39.50. May youtube to mp3 320 31, 2019. $39.50. May 32, 2019. $43.50. May
Is there anyone who can recommend the best service among the ones listed here?
ReplyDeleteIndoor Navigation For Hospitals
Play Free Slots Games Online at JTG Hub
ReplyDeleteSlots 정읍 출장샵 Free 춘천 출장마사지 Casino 공주 출장샵 Games Online at JTG Hub. Play the best free slots 충청북도 출장안마 games with no download needed & 100% safe. Play 경기도 출장샵 Now.
FON PERDE MODELLERİ
ReplyDeleteNumara onay
mobil ödeme bozdurma
nft nasıl alınır
ANKARA EVDEN EVE NAKLİYAT
TRAFİK SİGORTASI
DEDEKTOR
WEB SİTE KURMA
aşk kitapları
Smm panel
ReplyDeleteSmm panel
iş ilanları
instagram takipçi satın al
hirdavatciburada.com
beyazesyateknikservisi.com.tr
servis
tiktok jeton hilesi
özel ambulans
ReplyDeleteuc satın al
minecraft premium
en son çıkan perde modelleri
nft nasıl alınır
lisans satın al
en son çıkan perde modelleri
yurtdışı kargo
Hire ReactJS Developers from CronJ to leverage 9+ years of React handling and 15+ industrial experience at just $8 per hour!
ReplyDeletehire reactjs developers
hire react developer
This is a fantastic read. I appreciate the thorough research and attention to detail. It’s always refreshing to find well-written content that’s both informative and engaging
ReplyDeleteMysore Ooty Coorg Tour Package
Mysore Ooty Kodaikanal Tour Package
Manali Rohtang Tour Package
This is a really interesting post. I appreciate the depth of your research and the clarity of your writing. Looking forward to reading more
ReplyDeleteKhajuraho Tour Packages
Western Group of Temples in Khajuraho
This post was exactly what I needed to read today. It’s very well-written and provides practical advice. Keep up the great work
ReplyDeleteDestination Wedding Planner Packages
Mice Tour Operators
Corporate Event Planner