简体   繁体   中英

ObservableObject not updating View

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)")
    }
}

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

Don't just call the Object in the Text.

This fixed my problem:

@ObservedObject private var altimeter = Altimeter.shared

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM