skip to Main Content

I have created an Atimeter as ObservableObject, so that I can access it from several points in my App. Unfortunately the view is not updating, when the @Published variable pressure changes. Can somebody explain why?

I already tried {willSet {objectWillChange.send()} }, which will trigger but also not update the View!

The Altimeter:

//
//  Altimeter.swift
//  iAlti_v2
//
//  Created by Lukas Wheldon on 14.12.20.
//

import Foundation
import CoreMotion
import Combine

class Altimeter: CMAltimeter, ObservableObject {
    static let shared = Altimeter()
    
    @Published var pressure: Double = 0
    
    func start() {
        if Altimeter.isRelativeAltitudeAvailable() {
            switch Altimeter.authorizationStatus() {
            case .notDetermined: // Handle state before user prompt
                debugPrint("CM: Awaiting user prompt...")
            //fatalError("Awaiting CM user prompt...")
            case .restricted: // Handle system-wide restriction
                fatalError("CM Authorization restricted!")
            case .denied: // Handle user denied state
                fatalError("CM Authorization denied!")
            case .authorized: // Ready to go!
                debugPrint("CM Authorized!")
            @unknown default:
                fatalError("Unknown CM Authorization Status!")
            }
            Altimeter.shared.startRelativeAltitudeUpdates(to: OperationQueue.main) { data, error in
                if let trueData = data {
                    //debugPrint(#function, trueData)
                    Altimeter.shared.pressure = trueData.pressure.doubleValue * 10
                } else {
                    debugPrint("Error starting relative Altitude Updates: (error?.localizedDescription ?? "Unknown Error")")
                }
            }
        }
    }
}

The View:

import SwiftUI

struct SwiftUIView: View {
    var body: some View {
        Text("(Altimeter.shared.pressure)")
    }
}

2

Answers


  1. Chosen as BEST ANSWER

    This fixed my problem:

    @ObservedObject private var altimeter = Altimeter.shared
    

  2. You need to use the @ObservedObject wrapper in the SwiftUIView.

    Don’t just call the Object in the Text.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search