0

我只想为 iphone 构建一个计步应用程序。我的应用程序在前台运行时正确运行并将步数数据保存到火力库,但是当用户终止应用程序时,步数停止,所以我挖了互联网来解决问题,但无法弄清楚。你们能帮我在后台继续计算步骤并在后台将它们写入firebase吗?

import UIKit
import CoreMotion
import FirebaseAuth
import FirebaseDatabase
class MainViewController: UIViewController {

//MARK: - Constants and Variables
let pedometer = CMPedometer()
let userDefault = UserDefaults.standard
var ref : DatabaseReference!
let user = Auth.auth().currentUser
var someInt: Int?

//MARK: - IBOutlets and IBActions
@IBOutlet weak var stepCountLabel: UILabel!

@IBAction func logOutBtn(_ sender: UIButton) {
    logout()
}

//MARK: - viewDidLoad
override func viewDidLoad() {
    super.viewDidLoad()
    stepCountLabel.text = "0"
    getFirebaseData()
    
}


//MARK: - Functions
func getFirebaseData() {
    ref = Database.database().reference()
    let uid = user!.uid
    ref.child("users").child(uid).observeSingleEvent(of: .value, with: { (snapshot) in
        
        // Get user value
        let value = snapshot.value as? [String : Any]
        let userDict = [
            "nickname" : value?["nickname"],
            "step_count" : value?["step_count"]
        ]
        
        
        DispatchQueue.main.async {
            self.someInt = userDict["step_count"] as? Int
            self.startPedometer(number: self.someInt ?? 0)
            self.stepCountLabel.text = String(self.someInt ?? 0)
        }
    })
    {
        (error) in
        print(error.localizedDescription)
    }
}

func startPedometer (number: Int) {
    pedometer.startUpdates(from: Date()) { (data, error) in
        if error == nil {
            self.getFirebaseData()
            //create data reference
            self.ref = Database.database().reference()
            //rewrite the step data on the child
            self.ref.child("users/ (self.user!.uid)/step_count").setValue(data!.numberOfSteps.intValue + number)
        } else{
            print("An error was occured: \(error!)")
        }
    }
}



func logout() {
    pedometer.stopUpdates()
    do {
        try Auth.auth().signOut()
        userDefault.setValue(false, forKey: "userSignedIn")
    }
    catch {
        print("already logged out")
    }
    navigationController?.popToRootViewController(animated: true)
  }
}
4

0 回答 0