0

In Stack Overflow, I've seen answer to find closest beacon (Swift find closest Beacon by rssi).

Here I tried with accuracy to find closest in Objective-C. My app finds beacon in every sec that time accuracy is not working finding closest properly. As he said RSSI will update in every 1 sec. So I'd like to filter closest beacon using RSSI. I converted your Swift code into Objective-C but it's not working fine.

Here is Swift code:

//Swift code
var closestBeacon: CLBeacon? = nil
for beacon in beacons {
    if beacon.rssi < 0 && closestBeacon != nil && beacon.rssi > closestBeacon!.rssi {
        closestBeacon = beacon as? CLBeacon
    }
}

Here is Objective-C code I converted not working:

CLBeacon *closest = nil;

for (CLBeacon *beacon in beacons) {

    if (beacon.rssi < 0 &&  closest != nil && beacon.rssi > closest.rssi) {

        closest = beacon;

    }
}

Here please make me perfect where I'm doing wrong.

Cœur
  • 37,241
  • 25
  • 195
  • 267
Eshwar
  • 3
  • 5
  • 1
    You need to set assign a value to `closest` at some point before your loop or it will always be `nil` and the `if` will never be true – Paulw11 Jun 29 '19 at 08:01
  • 1
    @P4yam, I've approved your edit, but see my subsequent edit for how to do proper code formatting. – Cœur Jun 29 '19 at 08:29
  • I think that you could use `max(by:)` to find the Beacon with the max value, and the compare it with yours saved beacon if exists to set it. – Larme Jun 29 '19 at 11:07

1 Answers1

0

There is a bug in both versions of code as @paulw11 suggests. Since I wrote that bug in response to another question here is a fix:

Swift

var closestBeacon: CLBeacon? = nil
for beacon in beacons {
    if closestBeacon == nil || beacon.rssi < 0 && beacon.rssi > closestBeacon!.rssi {
        closestBeacon = beacon as? CLBeacon
    }
}

Objective-C

CLBeacon *closestBeacon = nil;

for (CLBeacon *beacon in beacons) {

    if (closestBeacon == nil || beacon.rssi < 0 && beacon.rssi > closest.rssi) {

        closestBeacon = beacon;

    }
}

I fixed the bug in the original post, too.

davidgyoung
  • 63,876
  • 14
  • 121
  • 204
  • let me try and comeback to you. Here in your answer closestBeacon is beacon? or need to take another CLBeacon property. Otherwise compiler throws error. – Eshwar Jun 29 '19 at 16:41
  • I edited the answer. To be consistent with the swift version, I have named the variable closestBeacon – davidgyoung Jun 29 '19 at 16:56