BTKit 0.5 on iOS and SwiftUI

Hello

I’m able to use BTKit 0.5 successfully in Xcode in a Swift App. However, I must use SwiftUI for a particular purpose.

Could you help me with a simple example on how to read RuuviTag (BTForeground.shared.scan) in SwiftUI?

Is there any other library/method available for reading RuuviTag on iOS than BTKit?

Thanks!

@priyonto Please take a look here

@tts Hi, Let me start with answering your last question first. Not in general, BTKit is build around RuuviTag and if you are planning to get RuuviTag data on your iOS app its highly recommended to use BTKit.

Now, I am assuming you have the basic idea of SwiftUI app. BTKit works just well on SwiftUI too, it is framework independent.

What you would need is to create a class and implement the BTKit. Here’s a simple example, and you may change it to your need.

import SwiftUI
import BTKit

final class ViewModel: ObservableObject {
    private let foreground: BTForeground!

    private var scanToken: ObservationToken?
    private var ruuviTagObserveToken: ObservationToken?

    init(
        foreground: BTForeground
    ) {
        self.foreground = foreground
    }

    /// Start observing all available tag advertisements
    private func startScanning() {
        scanToken?.invalidate()
        scanToken = nil

        scanToken = foreground.scan(self) { [weak self] (observer, device) in
            if let ruuviTag = device.ruuvi?.tag {
                // Do something with advertisements
            }
        }
    }

    /// Stop scanning
    private func stopScanning() {
        scanToken?.invalidate()
    }

    /// Start observing a particular tag advertisements
    private func startObserving() {
        ruuviTagObserveToken?.invalidate()
        ruuviTagObserveToken = nil

        ruuviTagObserveToken = foreground.observe(self,
                                                uuid: ruuviTag.uuid,
                                                options: [.callbackQueue(.untouch)]) {
            [weak self] (observer, device) in
            // Do something with advertisements data
        }
    }
}
2 Likes

Excellent! I got it working with your help. Thanks a lot.

2 Likes