A comprehensive iOS framework for monitoring and analyzing BackgroundTasks performance using method swizzling to provide deep insights into your app's background processing behavior.
β οΈ Beta Release: This is a beta version. APIs may change before the stable release. Feedback and contributions are welcome!
BackgroundTime SDK automatically tracks all BackgroundTasks API usage in your iOS app without requiring code changes. It uses method swizzling to intercept BGTaskScheduler calls and provides detailed analytics through a beautiful SwiftUI dashboard.
The BackgroundTime dashboard provides comprehensive insights into your app's background task performance with real-time analytics and beautiful visualizations.
- Zero-code integration - Just initialize the SDK and it automatically tracks all background tasks
- Method swizzling - Intercepts all BGTaskScheduler and BGTask method calls
- Comprehensive coverage - Tracks scheduling, execution, completion, cancellation, and failures
- Execution Statistics - Total scheduled/executed/completed/failed tasks
- Performance Metrics - Average duration, success rates, hourly patterns
- System Context - Battery level, low power mode, background app refresh status
- Error Tracking - Failure reasons, retry attempts, system constraint impacts
- Data Export - JSON export for integration with web dashboards
- Network Sync - Optional remote dashboard synchronization
- Real-time Monitoring - Live updates for production app monitoring
Get started in under 30 seconds - just add the package and initialize!
dependencies: [
.package(url: "https://github.com/yourusername/BackgroundTime", from: "0.1.0-beta")
]- File β Add Package Dependencies
- Enter:
https://github.com/yourusername/BackgroundTime - Select "Up to Next Major Version" with
0.1.0-beta - Add to your target
In your App.swift file:
import BackgroundTime
@main
struct MyApp: App {
init() {
// Initialize BackgroundTime SDK - that's it!
BackgroundTime.shared.initialize()
}
var body: some Scene {
WindowGroup {
ContentView()
}
}
}Simple one-line integration to add the powerful analytics dashboard to your app
import BackgroundTime
struct ContentView: View {
@State private var showDashboard = false
var body: some View {
NavigationView {
YourAppContent()
.toolbar {
ToolbarItem(placement: .navigationBarTrailing) {
Button("Dashboard") {
showDashboard = true
}
}
}
}
.sheet(isPresented: $showDashboard) {
BackgroundTimeDashboard()
}
}
}For UIKit-based apps, you can present the dashboard using UIHostingController:
import UIKit
import SwiftUI
import BackgroundTime
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Add dashboard button to navigation bar
let dashboardButton = UIBarButtonItem(
title: "Dashboard",
style: .plain,
target: self,
action: #selector(showDashboard)
)
navigationItem.rightBarButtonItem = dashboardButton
}
@objc private func showDashboard() {
// Create SwiftUI dashboard wrapped in UIHostingController
let dashboardView = BackgroundTimeDashboard()
let hostingController = UIHostingController(rootView: dashboardView)
// Configure presentation
hostingController.modalPresentationStyle = .pageSheet
// Present the dashboard
present(hostingController, animated: true)
}
}import UIKit
import SwiftUI
import BackgroundTime
class MainViewController: UIViewController {
@IBAction func dashboardButtonTapped(_ sender: UIButton) {
let dashboardView = BackgroundTimeDashboard()
let hostingController = UIHostingController(rootView: dashboardView)
// Present in navigation controller for better UX
let navController = UINavigationController(rootViewController: hostingController)
navController.modalPresentationStyle = .fullScreen
// Add close button
hostingController.navigationItem.leftBarButtonItem = UIBarButtonItem(
barButtonSystemItem: .close,
target: self,
action: #selector(dismissDashboard)
)
present(navController, animated: true)
}
@objc private func dismissDashboard() {
dismiss(animated: true)
}
}let config = BackgroundTimeConfiguration(
maxStoredEvents: 2000, // Maximum events to store locally
enableDetailedLogging: true // Enable detailed logging
)
BackgroundTime.shared.initialize(configuration: config)// Get current statistics
let stats = BackgroundTime.shared.getCurrentStats()
print("Success rate: \(stats.successRate * 100)%")
// Get all events
let events = BackgroundTime.shared.getAllEvents()
print("Total events: \(events.count)")
// Export for external dashboard
let dashboardData = BackgroundTime.shared.exportDataForDashboard()- Total Executed: Number of background tasks that started execution
- Success Rate: Percentage of tasks that completed successfully
- Failed Tasks: Number of tasks that failed or were cancelled
- Average Duration: Mean execution time for completed tasks
- Executions by Hour: 24-hour pattern showing when tasks typically run
- Duration Trends: Line chart showing execution times over time
- Task-Specific Metrics: Individual performance data for each task identifier
- Efficiency Metrics: Time between scheduling and execution
- Error Types: Categorized breakdown of failure reasons
- System Constraints: Impact of low power mode, background refresh settings
- Failure Patterns: When and why tasks are most likely to fail
The package includes a complete example app demonstrating integration in a social media/chat app context:
- Feed Refresh (
BGAppRefreshTask) - Updates social media feed - Media Download (
BGProcessingTask) - Downloads images/videos - Chat Sync (
BGAppRefreshTask) - Synchronizes chat messages
// Register background tasks
BGTaskScheduler.shared.register(
forTaskWithIdentifier: "refresh-social-feed",
using: nil
) { task in
await handleFeedRefresh(task as! BGAppRefreshTask)
}
// Schedule tasks
let request = BGAppRefreshTaskRequest(identifier: "refresh-social-feed")
request.earliestBeginDate = Date(timeIntervalSinceNow: 15 * 60)
try BGTaskScheduler.shared.submit(request)The SDK automatically tracks all of these operations without any additional code!
|
π Statistics Cards Quick overview with trend indicators, success rates, and performance metrics |
π Execution Patterns 24-hour visualization showing when your tasks typically run |
π 3D Performance Advanced 3D surface plots for deep performance analysis |
The SDK uses runtime method swizzling to intercept:
BGTaskScheduler.submit(_:)- Task schedulingBGTaskScheduler.cancel(taskRequestWithIdentifier:)- Task cancellationBGTask.setTaskCompleted(success:)- Task completion- Expiration handlers - Task timeouts
- Local Storage: Events stored in UserDefaults with configurable limits
- Memory Management: Automatic cleanup of old events
- Thread Safety: Concurrent queues for safe data access
- Persistence: Data survives app termination and restart
- Optional Remote Sync: Upload data to your dashboard backend
- JSON Export: Standard format for integration with existing tools
- Configurable Endpoints: Support for custom dashboard URLs
- Error Handling: Robust network error handling and retry logic
We'd love your feedback on this beta release! Please:
- π Report bugs
- π‘ Suggest features
- π Improve documentation
- β Star the repo if you find it useful!
- iOS 16.0+
- Xcode 14.0+
- Swift 5.7+
MIT License - see LICENSE file for details
- Fork the repository
- Create a feature branch
- Make your changes
- Add tests for new functionality
- Submit a pull request
For questions, issues, or feature requests:
- Open an issue on GitHub
- Check the documentation
- Review the example app for integration patterns
BackgroundTime SDK - Making background task monitoring effortless and insightful. π



