Tuesday, December 30, 2014

How would you scan for nearby BLE devices using Swift

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
  1. CBCentralManager (class)
  2. CBPeripheral (class)
  3. 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


So, what happens here is that

  1. We added a local variable of type CBCentralManager
  2. We added a local variable of type BLEHandler which acts as a delegate (Note: we will create this class in a minute)
  3. We initialize the ble handler
  4. 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


  1. Start scanning somewhere in our code
  2. 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

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.


Final notes

  1. You can wrap the functionality however you want, the BLEManager is just a simple way to wrap and manage things easily.
  2. 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
  3. 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

60 comments:

  1. Hello.
    Thanks 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

    ReplyDelete
    Replies
    1. Yeah,

      I am having the same issue...

      Delete
    2. I am having the same issue, anyone found the solution yet?

      I am clicking the button, but nothing is getting displayed

      Delete
  2. como hacer que esta funcion se ejecute aun cuando la aplicacion no se esta ejecutando

    ReplyDelete
  3. thanks 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?

    ReplyDelete
    Replies
    1. you need to implement func centralManagerDidUpdateState(central: CBCentralManager) {

      }

      Delete
  4. 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.
    swift Mobile app Development

    ReplyDelete
  5. self.centralManager = CBCentralManager(delegate:self, queue:nil)
    -> error: Cannot convert value of type 'BLEManager' to expected argument type 'CBCentralManagerDelegate?'

    ReplyDelete
  6. Guys just move the variable declaration to the very top of your class
    smth like:

    class ViewController: NSViewController {

    var bleManager : BLEManager!
    ...

    ReplyDelete
    Replies
    1. Great comment. This is the solution of error. BTW, do not forget to add environment variable of NSZombieEnabled = YES

      Delete
  7. Thanks 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..
    please sharing like this information......
    Android training in chennai
    Ios training in chennai

    ReplyDelete
  8. 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...

    Mobile App Development Company
    Mobile App Development Company
    Mobile app Development Companies

    ReplyDelete
  9. I 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

    ReplyDelete
  10. Thank you for your post. This is excellent information. It is amazing and wonderful to visit your site.
    ios app development course

    ReplyDelete
  11. This comment has been removed by the author.

    ReplyDelete
  12. The article is good.I got some knowledge about iOS.Thanks for sharing this blog.
    iOS Training In Chennai | iOS Training Institute In Chennai

    ReplyDelete
  13. The Content was super and useful.Thankyou for posting this blog.I got some knowledge.
    iOS Training In Chennai | iOS Training Institute In Chennai

    ReplyDelete
  14. I liked the way of presention.Its good and Informative.Thank you for posting this article
    iOS Training In Chennai | iOS Training Institute In Chennai

    ReplyDelete
  15. 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

    ReplyDelete
  16. Its really good article.I got new information.Tyhank you for posting this articleiOS Training In Chennai | iOS Training Institute In Chennai

    ReplyDelete
  17. Thankyou for posting this article.I got clear idea.Its easy to understand and the presentation is good
    iOS Training in Chennai | iOS Training Institute in Chennai

    ReplyDelete
  18. Thanks 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.
    digital marketing training in annanagar

    digital marketing training in marathahalli

    digital marketing training in rajajinagar

    Digital Marketing online training

    full stack developer training in pune

    ReplyDelete
  19. 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.
    full stack developer training in annanagar

    full stack developer training in tambaram

    full stack developer training in velachery

    ReplyDelete
  20. 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…
    python training institute in chennai
    python training in Bangalore
    python training institute in chennai

    ReplyDelete
  21. Thanks you for sharing this unique useful information content with us. Really awesome work. keep on blogging

    java training in omr | oracle training in chennai

    java training in annanagar | java training in chennai

    ReplyDelete
  22. 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. 

    angularjs Training in bangalore

    angularjs Training in btm

    angularjs Training in electronic-city

    angularjs online Training

    angularjs Training in marathahalli

    ReplyDelete
  23. 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.


    AWS 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


    ReplyDelete
  24. 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.
    Website Design
    SEO Company

    ReplyDelete
  25. : 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.
    - For chrome browsers: Include the autocomplete attribute for all the credit card form fields. scscan

    ReplyDelete
  26. One of the key features said to be coming to
    the HomePod is the ability to make or receive phone calls
    Read More At iOS Online Course

    ReplyDelete
  27. 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. 

    devops online training

    aws online training

    data science with python online training

    data science online training

    rpa online training

    ReplyDelete
  28. This comment has been removed by the author.

    ReplyDelete
  29. Thanks for this great information,
    i'm really appreciate your information related to swift mobile app |
    ios development with swift

    ReplyDelete
  30. 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!!
    Artificial Intelligence Course

    ReplyDelete
  31. 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.
    360digitmg data analytics course malaysia

    ReplyDelete
  32. 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.

    data analytics courses malaysia

    ReplyDelete

  33. click here for more info.
    ................................................................

    ReplyDelete
  34. Thanks for your contribution in sharing such a useful information. This was really helpful to me. Waiting for your further updates.
    Java training in Chennai

    Java training in Bangalore

    Java training in Hyderabad

    Java Training in Coimbatore

    Java Online Training

    ReplyDelete
  35. Your good knowledge and kindness in playing with all the pieces were
    very 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

    ReplyDelete
  36. video-game-game-criteria-for-players-players-genesis-isis-a - Video
    › 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

    ReplyDelete
  37. Is there anyone who can recommend the best service among the ones listed here?
    Indoor Navigation For Hospitals

    ReplyDelete
  38. Play Free Slots Games Online at JTG Hub
    Slots 정읍 출장샵 Free 춘천 출장마사지 Casino 공주 출장샵 Games Online at JTG Hub. Play the best free slots 충청북도 출장안마 games with no download needed & 100% safe. Play 경기도 출장샵 Now.

    ReplyDelete
  39. I feel very grateful that I read this. It is very helpful and very informative and I really learned a lot from it. data science training in kanpur

    ReplyDelete
  40. Hire ReactJS Developers from CronJ to leverage 9+ years of React handling and 15+ industrial experience at just $8 per hour!

    hire reactjs developers
    hire react developer

    ReplyDelete