Swift
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Optionals
-
Section 4: Object-Oriented and Value Types
-
Section 5: Memory Management
-
Section 6: Generics and Error Handling
-
Section 7: Concurrency
-
Section 8: Working with Collections
-
Section 9: Codable and Data Handling
-
Section 10: Protocol-Oriented Programming
-
Section 11: Testing and Tooling
-
Section 12: Practical Projects
-
Section 13: Interview Practice
-
Section 14: More Practice Exercises
-
Section 15: More Standard Library
-
Section 16: Advanced Concurrency
-
Section 17: Foundation Framework Deep Dive
-
Section 18: URLSession and Networking Deep Dive
-
Section 19: Combine Framework
-
Section 20: SwiftUI Fundamentals for Swift Developers
-
Section 21: Server-Side Swift with Vapor
-
Section 22: Swift Package Manager Deep Dive
-
Section 23: Swift Concurrency Deep Dive
-
Section 24: More Language Features
-
Section 25: Error Handling Deep Dive
-
Section 26: Testing Deep Dive
-
Section 27: Data Structures and Algorithms in Swift
-
Section 28: More Practice Exercises
-
Section 29: More Interview Practice
-
Section 30: Swift Macros (Swift 5.9+)
-
Section 31: Property Wrappers Ecosystem
-
Section 32: Swift Interop Deep Dive
-
Section 33: iOS App Architecture Patterns
-
Section 34: Performance and Debugging
-
Section 35: App Distribution and CI/CD
-
Section 36: More Practical Projects
-
Section 37: SwiftData and Persistence
-
Section 38: More Design Patterns
-
Section 39: More Review and Practice
-
Section 40: More Foundation Deep Dive
-
Section 41: Advanced Collections in Swift
-
Section 42: Advanced Generics Practice
-
Section 43: UIKit for Legacy and Hybrid Apps
-
Section 44: watchOS and visionOS Development Basics
-
Section 45: More Networking Patterns
-
Section 46: More Testing Practice
-
Section 47: Accessibility in Swift Apps
-
Section 48: Localization
-
Section 49: More Practical Projects Round 2
-
Section 50: Swift Charts Framework
-
Section 51: More Interview and Algorithm Practice
-
Section 52: Final Practice and Mastery
-
Section 53: Swift Compiler and Build System
-
Section 54: More Concurrency Practice
-
Section 55: App Store Guidelines and Review
-
Section 56: More Design and Architecture
157: Building a Simple Widget Extension
Think of a widget as a sticky note on your refrigerator. You don't walk all the way into the pantry and start rummaging through shelves (opening the full app) just to see if you're out of milk. Instead, you glance at the note on the door. The note is a snapshot of information that's updated periodically, but it's not a live, interactive conversation with the kitchen.
In Swift, building a Widget Extension follows this exact logic. We aren't building a full app; we're building a "glanceable" experience. To do this, we need three things: the Entry (the content written on the note), the TimelineProvider (the person who decides when to rewrite the note), and the View (how the note actually looks).
Defining the Snapshot Data
Before we can draw anything, we need to define what data our widget actually cares about. For this lesson, let's build a "Water Intake Tracker." We don't need the whole user profile; we just need the current count of glasses and the time that count was recorded.
struct WaterEntry: TimelineEntry {
let date: Date
let glassesDrunk: Int
}
The TimelineEntry protocol requires a date. This is crucial because the system uses this date to know exactly when this specific "version" of the widget should be displayed on the home screen.
The Brains: The TimelineProvider
This is where most developers get tripped up. A widget doesn't "run" in the background like a standard app. Instead, it tells iOS: "Here is a schedule of what I want to show for the next few hours." The TimelineProvider handles this scheduling.
I've found that the easiest way to wrap your head around this is to think of it as a movie reel. You're providing a series of frames (entries) and telling the system when to switch to the next frame.
struct WaterProvider: TimelineProvider {
// A preview version for the widget gallery
func placeholder(in context: Context) -> WaterEntry {
WaterEntry(date: Date(), glassesDrunk: 0)
}
// A quick snapshot for the system to show during transitions
func getSnapshot(in context: Context, completion: @escaping (WaterEntry) -> Void) {
completion(WaterEntry(date: Date(), glassesDrunk: 5))
}
// The actual schedule
func getTimeline(in context: Context, completion: @escaping (Timeline) -> Void) {
let currentDate = Date()
// In a real app, you'd fetch this from UserDefaults or a database
let entry = WaterEntry(date: currentDate, glassesDrunk: 8)
// We tell the system to refresh the widget again in 1 hour
let nextUpdate = Calendar.current.date(byAdding: .hour, value: 1, to: currentDate)!
let timeline = Timeline(entries: [entry], policy: .after(nextUpdate))
completion(timeline)
}
}
Designing the Glance
Because widgets are essentially SwiftUI views, the design part is the most intuitive. However, keep it simple. You have very little screen real estate, and the system will kill your process if you try to do something too computationally expensive during the render.
struct WaterWidgetView: View {
var entry: WaterProvider.Entry
var body: some View {
VStack {
Text("Hydration")
.font(.caption)
.foregroundColor(.secondary)
Text("\(entry.glassesDrunk)")
.font(.system(size: 40, weight: .bold))
Text("glasses")
.font(.caption)
}
.containerBackground(.blue.gradient, for: .widget)
}
}
Wiring the Extension Together
Finally, we need to tie the provider and the view together using a Widget configuration. This is the entry point that tells iOS, "This is a widget, here is the logic that powers it, and here is the view that displays it."
@main
struct WaterWidget: Widget {
let kind: String = "WaterTrackerWidget"
var body: some WidgetConfiguration {
StaticConfiguration(kind: kind, provider: WaterProvider()) { entry in
WaterWidgetView(entry: entry)
}
.configurationDisplayName("Water Tracker")
.description("Keep track of your daily water intake.")
.supportedFamilies([.systemSmall])
}
}
One quick tip: I highly recommend starting with StaticConfiguration. Unless you need the user to be able to customize the widget (like picking a specific city for a weather widget), StaticConfiguration is much faster to implement and less prone to bugs.
📋 Practical Task
Build a Daily Focus Goal Widget
Your task is to create a new Widget Extension for a "Focus" app. Instead of tracking water, this widget should display a single "Focus Goal" for the day (e.g., "Finish Swift Course" or "Clean the Garage").
Requirements:
- Create a
FocusEntrythat includes the goal text (a String) and the date. - Implement a
FocusProviderthat returns a hardcoded goal in thegetTimelinemethod and schedules the next update for 24 hours later. - Design a
FocusWidgetViewthat uses aZStackorVStackto display the goal text prominently with a background color of your choice. - Configure the widget using
StaticConfigurationand ensure it only supports the.systemSmallfamily.
There are no comments for now.