Real-Time Fitness Tracking on watchOS with SwiftUI
Todd Bernson
Award Winning Technology Leader | AWS Ambassador | AWS Machine Learning Community Builder | Lifelong Learner | Data Analytics, ML, AI
Fitness tracking apps on watchOS require real-time data synchronization, an intuitive user interface, and optimized energy consumption. This article covers:
By integrating AWS API Gateway with SwiftUI, the fitness tracking app can dynamically update progress while ensuring optimal performance on Apple Watch.
Building Dynamic Interfaces with SwiftUI for watchOS
watchOS apps must provide minimalistic yet informative real-time tracking interfaces. The app UI consists of:
Step 1: Creating the Main watchOS View
The ContentView.swift file defines a real-time progress screen:
import SwiftUI
struct ContentView: View {
@ObservedObject private var connectivityManager = WatchConnectivityManager.shared
@State private var totalLifted: Int = 0
@State private var isLoading: Bool = true
@State private var errorMessage: String?
var body: some View {
VStack {
if isLoading {
ProgressView("Loading...")
} else if let errorMessage = errorMessage {
Text(errorMessage).foregroundColor(.red)
} else {
Text("Workout Progress")
.font(.headline)
Text("\(totalLifted) lbs lifted")
.font(.title)
.bold()
}
}
.onAppear {
fetchData()
}
}
private func fetchData() {
isLoading = true
APIClient.fetchData(for: connectivityManager.userEmail) { result in
DispatchQueue.main.async {
isLoading = false
switch result {
case .success(let data):
totalLifted = Int(data["total_lifted"] as? Double ?? 0.0)
case .failure(let error):
errorMessage = "Error fetching data: \(error.localizedDescription)"
}
}
}
}
}
How This Works:
Leveraging AWS API Gateway for Real-Time Data Updates
The watchOS app retrieves real-time data using AWS API Gateway. The API fetches workout progress and updates in response to new workout sessions.
Step 2: Fetching Data from AWS
The APIClient.swift file manages API calls:
import Foundation
class APIClient {
static func fetchData(for userEmail: String, completion: @escaping (Result<[String: Any], Error>) -> Void) {
guard let apiUrl = URL(string: "https://your-api-gateway.amazonaws.com/getFitnessData") else {
completion(.failure(NSError(domain: "APIClient", code: 1, userInfo: [NSLocalizedDescriptionKey: "Invalid URL"])))
return
}
var request = URLRequest(url: apiUrl)
request.setValue(userEmail, forHTTPHeaderField: "x-user-email")
request.httpMethod = "GET"
let task = URLSession.shared.dataTask(with: request) { data, response, error in
if let error = error {
completion(.failure(error))
return
}
guard let data = data else {
completion(.failure(NSError(domain: "APIClient", code: 2, userInfo: [NSLocalizedDescriptionKey: "No data received"])))
return
}
do {
let jsonResponse = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any]
completion(.success(jsonResponse ?? [:]))
} catch {
completion(.failure(error))
}
}
task.resume()
}
}
Why This Matters:
领英推荐
Designing an Energy-Efficient watchOS App
Optimizing battery life on watchOS is essential. The app:
Step 3: Implementing Efficient Data Fetching
To reduce unnecessary updates, the app only fetches data when:
import WatchKit
import WatchConnectivity
class WatchConnectivityManager: NSObject, ObservableObject, WCSessionDelegate {
static let shared = WatchConnectivityManager()
@Published var userEmail: String = "Guest"
private override init() {
super.init()
if WCSession.default.isSupported() {
WCSession.default.delegate = self
WCSession.default.activate()
}
}
func session(_ session: WCSession, didReceiveMessage message: [String : Any]) {
if let email = message["userEmail"] as? String {
DispatchQueue.main.async {
self.userEmail = email
}
}
}
func retryFetchingEmail() {
if WCSession.default.isReachable {
WCSession.default.sendMessage(["requestEmail": true], replyHandler: nil, errorHandler: nil)
}
}
}
How This Works:
Visuals
Real-Time Tracking Interface on watchOS
By using SwiftUI, AWS API Gateway, and WatchConnectivity, the watchOS fitness tracker:
This architecture ensures an efficient, real-time fitness tracking experience for Apple Watch users.
Purdue Professor | Wiley Author | Forbes Columnist. I teach, write, and speak about leadership, team, and organizational performance from a biology of behavior perspective.
1 个月I love this space you’ve carved out, Todd, bringing such innovative thinking to the intersection of tech and human performance. Keep it up!