A simple code to detect any beacon in swift

馋奶兔 提交于 2019-12-01 12:09:34

SWIFT 3:

First of all you should add the CoreLocation.Framework

  • In the .Plist file add the key/string NSLocationAlwaysUsageDescriptionwith appropriate string

  • In your Object add the CLLocationManagerDelegate

  • Add the CLLocationManagerDelegate delegate methods in this example i will just add the didRangeBeacons method

func locationManager(_ manager: CLLocationManager, didRangeBeacons
beacons: [CLBeacon], in region: CLBeaconRegion) {
           print(beacons)   }
  • Create and initialise the locationManager

    var locationManager : CLLocationManager = CLLocationManager()

  • Create the CLBeaconRegion

    let beaconRegion : CLBeaconRegion = CLBeaconRegion(
        proximityUUID: NSUUID.init(uuidString:"****-****-****-****-******") as! UUID,
        identifier: "my beacon")
    
  • Add the delegate to your Object locationManager.delegate = self

  • Request the Location authorization from the user with

locationManager.requestAlwaysAuthorization()

Now let's start the Range

  locationManager.startRangingBeacons(in: beaconRegion)

This will automatically call the delegate method

   func locationManager(_ manager: CLLocationManager, didRangeBeacons beacons: [CLBeacon], in region: CLBeaconRegion) {
        print(beacons)

    }

Note : if you want to monitor beacon's entry/ exit state you need to add

locationManager.startMonitoring(for: beaconRegion)

Finally : Make sure that your beacon is turned ON and you are testing the iBeacon Frame Enjoy :D

Beacons can be Detected in both Foreground as well as when in Background

Step :- 1 Changes in info.plist

In info.plist you need to change the “usage description” . For that add the NSLocationAlwaysUsageDescription with String type with your Message in it.

Step :- 2 For Background Mode

Add the Following Piece of Code in App Delegate :

var window: UIWindow?
var locationManager:CLLocationManager = CLLocationManager()

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    // Override point for customization after application launch.
    locationManager.delegate = self
    locationManager.requestAlwaysAuthorization()
    // Request permission to send notifications
    let center = UNUserNotificationCenter.current()
    center.requestAuthorization(options:[.alert, .sound]) { (granted, error) in }
    return true
}

func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
    rangeBeacons()

}

func rangeBeacons(){
    let uuid = UUID(uuidString: "3e1d7817-4eac-4b27-b809-deee2f246c46")
    //let uuid = UUID(uuidString: "8492E75F-4FD6-469D-B132-043FE94921D8")
    let major:CLBeaconMajorValue = 1
    let minor:CLBeaconMinorValue = 2
    let identifier = "myBeacon"
    let region = CLBeaconRegion(proximityUUID: uuid!, major: major, minor: minor, identifier: identifier)
    region.notifyOnEntry = true
    region.notifyEntryStateOnDisplay = true
    region.notifyOnExit = true
    locationManager.startRangingBeacons(in: region)
    locationManager.startMonitoring(for: region)
}

func locationManager(_ manager: CLLocationManager, didEnterRegion region: CLRegion) {
    let content = UNMutableNotificationContent()
    content.title = "Hello!!!"
    content.body = "You Are Back in the Office"
    content.sound = .default()
    let request = UNNotificationRequest(identifier: "SufalamTech", content: content, trigger: nil)
    UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)
}

func locationManager(_ manager: CLLocationManager, didExitRegion region: CLRegion) {
    let content = UNMutableNotificationContent()
    content.title = "Alert!!!"
    content.body = "You are Out of the Office"
    content.sound = .default()
    let request = UNNotificationRequest(identifier: "identifier", content: content, trigger: nil)
    UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)
}

Also Don't Forget to add CLLocationManagerDelegate and import CoreLocations and UserNotifications

Step :- 3 For ForeGround or Active Mode

Add the Following Piece of Code in ViewController

func locationManager(_ manager: CLLocationManager, didRangeBeacons beacons: [CLBeacon], in region: CLBeaconRegion) {
    guard let discoveredbeaconProximity = beacons.first?.proximity else {print("Beacons Cannot be located"); return }

    if ((discoveredbeaconProximity == .far) || (discoveredbeaconProximity == .near) || (discoveredbeaconProximity == .immediate)) {
        let alert = UIAlertController(title: "Alert", message: "You are in the Beacon Region", preferredStyle: UIAlertControllerStyle.alert)
        alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil))
        self.window?.rootViewController?.present(alert, animated: true, completion: nil)

    }
    if discoveredbeaconProximity == .unknown{
        let alert = UIAlertController(title: "Alert", message: "You are out of the Beacon Region!!!", preferredStyle: UIAlertControllerStyle.alert)
        alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil))
        self.window?.rootViewController?.present(alert, animated: true, completion: nil)

    }
}

Note :- You Need To change your Beacon UUID and Major and Minor Value accordingly

Simple Example:

Add NSLocationAlwaysUsageDescription to your *.plist file.

In your ViewController create your locationManager and your beaconRegion. Set the locationManager delegate, request the authorization from the user and then start monitoring/ranging.

let locationManager : CLLocationManager = CLLocationManager()
let beaconRegion : CLBeaconRegion = CLBeaconRegion(
  proximityUUID: NSUUID.init(uuidString:"11111111-1111-1111-1111-111111111111") as! UUID,
  major: 1,
  minor: 1,
  identifier: "my beacon")

locationManager.delegate = self
locationManager.requestAlwaysAuthorization()
locationManager.startMonitoring(for: beaconRegion)

Add the extensions for CLLocationManagerDelegate:

extension ViewController : CLLocationManagerDelegate {
  func locationManager(manager: CLLocationManager, didRangeBeacons beacons: [CLBeacon], inRegion region: CLBeaconRegion) {
    print(beacons)
  }

  func locationManager(manager: CLLocationManager, didEnterRegion region: CLRegion) {
    let beaconRegion = region as! CLBeaconRegion
    print("Did enter region: " + (beaconRegion.major?.stringValue)!)
  }

  func locationManager(manager: CLLocationManager, didExitRegion region: CLRegion) {
    let beaconRegion = region as! CLBeaconRegion
    print("Did exit region: " + (beaconRegion.major?.stringValue)!)
  }
}

Note: Activate bluetooth, check if location-services are activated on your device (simulator not supported), with this region you will only find the beacon with exact this UUID+major+minor.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!