使用Firebase中的UUID检测iBeacon

问题描述 投票:0回答:1

我正在尝试从Firebase数据库接收所有UUID。使用这些UUID,我想搜索这些UUID中的任何一个是否在设备附近。下面是我为实现此目的而编写的代码。每当我运行程序时,它只会检测某些UUID,而不是全部。有人可以帮我弄清楚为什么会这样吗?

预先感谢!

EDIT:我想一个接一个地连续检查信标

我的JSON数据库文件

{
  "UUID" : {
    "Cool Cool" : "E99B856D-2F8A-49F0-A583-E675A86F33BE",
    "Sabad's Ipad" : "44837477-B489-4BC7-83A6-D001D7FE0BD0",
    "Sweta" : "7D0D9B66-0554-4CCF-A6E4-ADE12325C4F0",
    "User 2" : "6D340D8D-005B-4610-A4FA-AA8D9437B8A8"
  },
  "User Detected" : {
    "Sabad's Ipad" : {
      "Co-ordinates" : "Latitude: 25.089279174804688   Longitude:55.17439565327509",
      "DateTime" : "2020-05-11 17:52:13 +0000",
      "UUID" : "A0719C85-E00B-4961-B9D0-7FCADD4ABA21"
    }
  }
}

我的ViewController.swift

import Firebase

import UIKit
import CoreLocation
import CoreBluetooth

//Initialise View Controller

class ViewController: UIViewController, CLLocationManagerDelegate, CBPeripheralManagerDelegate{


@IBOutlet weak var distanceReading: UILabel!
var locationManager:CLLocationManager?

var currentDateTime : Date = Date()
var currentDateTime2 : Date = Date()
var uuid = UUID()

let ref = Database.database().reference()

var dataArray = [String]()

var latitude = CLLocationDegrees(0)
var longitude = CLLocationDegrees(0)


override func viewDidLoad() {
    super.viewDidLoad()

    locationManager = CLLocationManager()
    locationManager?.delegate = self
    locationManager?.requestAlwaysAuthorization()

    view.backgroundColor = .gray

    uuid = UUID()

    let name = UIDevice.current.name
    ref.child("UUID/\(name)").setValue("\(String(describing: uuid))")

    if CLLocationManager.locationServicesEnabled() {
        locationManager?.delegate = self
        locationManager?.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
        locationManager?.startUpdatingLocation()
    }
}

//MARK: Detect iBeacon

func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
    guard let locValue: CLLocationCoordinate2D = manager.location?.coordinate else { return }
    latitude = (locValue.latitude)
    longitude = (locValue.longitude)

    if status == .authorizedAlways {
        if CLLocationManager.isMonitoringAvailable(for: CLBeaconRegion.self){
            if CLLocationManager.isRangingAvailable() {
                 startScanning()
            }
        }
    }
}

func startScanning(){
    ref.child("UUID").observe(.childAdded) { (snapshot) in
//        ref.child("UUID").observeSingleEvent(of: .childAdded) { (snapshot)
            let data = snapshot.value as? String
            if let actualPost = data{
            self.dataArray.append(actualPost)
//          print(self.dataArray)
            _ = self.dataArray.count
//          print(dataCount)
//          for i in 0..<(dataCount)
            for i2 in self.dataArray{
//              print(i2)
//                print("Next")
                let beaconRegion = CLBeaconRegion(uuid : UUID(uuidString: i2)! , major: 123, minor: 789, identifier: "MyBeaconDetector")
//                print(beaconRegion)
                self.locationManager?.startMonitoring(for: beaconRegion)
                self.locationManager?.startRangingBeacons(satisfying: beaconRegion.beaconIdentityConstraint)
            }
        }
    }
 }

  func update(distance:CLProximity){
  UIView.animate(withDuration: 0.01 ) {
      switch distance{
          case .immediate:
              self.view.backgroundColor = .blue
              self.distanceReading.text = "Right Here"
              self.currentDateTime = Date()
              print(self.currentDateTime)

          case .near:
              self.view.backgroundColor = .orange
              self.distanceReading.text = "Near"
              self.currentDateTime2 = Date()
              print(self.currentDateTime2)

          case .far:
              self.view.backgroundColor = .red
              self.distanceReading.text = "Far"

          default:
              self.view.backgroundColor = .gray
              self.distanceReading.text = "UNKNOWN"
      }
  }

  }

    func locationManager(_ manager: CLLocationManager, didRange beacons : [CLBeacon], satisfying beaconConstraint: CLBeaconIdentityConstraint) {
    let dataCount = UInt32(beacons.count)
//    print(dataCount)
    print(beaconConstraint)
//    print(dataCount)
        for i in 0...10000{
            if let beacon = beacons.randomElement() {
            print(beacon)
            update(distance: beacon.proximity)
            let name = UIDevice.current.name
            self.ref.child("User Detected/\(name)/DateTime").setValue("\(self.currentDateTime)")
            self.ref.child("User Detected/\(name)/UUID").setValue("\(String(describing: self.uuid))")
            self.ref.child("User Detected/\(name)/DateTime").setValue("\(self.currentDateTime)")
            self.ref.child("User Detected/\(name)/Co-ordinates").setValue("Latitude: \(self.latitude)   Longitude:\(self.longitude)")
            continue

          } else{
//            print("Check")
            update(distance: .unknown)
          }
       }
    }
}
ios swift firebase ibeacon
1个回答
0
投票

问题出在这些代码行:

            for i2 in self.dataArray{
                let beaconRegion = CLBeaconRegion(uuid : UUID(uuidString: i2)!,
                                                  major: 123, minor: 789, 
                                                  identifier: "MyBeaconDetector")
                self.locationManager?.startMonitoring(for: beaconRegion)
                self.locationManager?.startRangingBeacons(satisfying: beaconRegion.beaconIdentityConstraint)

问题是您正在为循环中构造的每个区域重新使用identifier字段。该字符串应该是唯一的。因此,您最终要做的是覆盖以前注册的测距/监视区域。

要解决此问题,请使每个区域的identifier唯一,如下所示:

            for i2 in self.dataArray{
                let uniqueIdentifier = i2 // adjust as needed to make this unique
                let beaconRegion = CLBeaconRegion(uuid : UUID(uuidString: i2)!,
                                                  major: 123, minor: 789, 
                                                  identifier: uniqueIdentifier)
                self.locationManager?.startMonitoring(for: beaconRegion)
                self.locationManager?.startRangingBeacons(satisfying: beaconRegion.beaconIdentityConstraint)

© www.soinside.com 2019 - 2024. All rights reserved.