-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathios-14-widget-tutorial-mini-apps.html
More file actions
602 lines (543 loc) · 35.3 KB
/
ios-14-widget-tutorial-mini-apps.html
File metadata and controls
602 lines (543 loc) · 35.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://use.fontawesome.com/afd448ce82.js"></script>
<!-- Meta Tag -->
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<!-- SEO -->
<meta name="author" content="Bruno Rocha">
<meta name="keywords" content="Software, Engineering, Blog, Posts, iOS, Xcode, Swift, Articles, Tutorials, OBJ-C, Objective-C, Apple">
<meta name="description" content="Widgets existed in iOS for a long time, but iOS 14 completely revamped them. With the new Widget APIs, not you're able to add widgets directly to your home screen, but they are also completely written in SwiftUI.">
<meta name="title" content="How to create Widgets in iOS 14 in Swift">
<meta name="url" content="https://swiftrocks.com/ios-14-widget-tutorial-mini-apps">
<meta name="image" content="https://swiftrocks.com/images/thumbs/thumb_dark.jpg">
<meta name="copyright" content="Bruno Rocha">
<meta name="robots" content="index,follow">
<meta property="og:title" content="How to create Widgets in iOS 14 in Swift"/>
<meta property="og:image" content="https://swiftrocks.com/images/thumbs/thumb_dark.jpg"/>
<meta property="og:description" content="Widgets existed in iOS for a long time, but iOS 14 completely revamped them. With the new Widget APIs, not you're able to add widgets directly to your home screen, but they are also completely written in SwiftUI."/>
<meta property="og:type" content="website"/>
<meta property="og:url" content="https://swiftrocks.com/ios-14-widget-tutorial-mini-apps"/>
<meta name="twitter:card" content="summary_large_image"/>
<meta name="twitter:image" content="https://swiftrocks.com/images/thumbs/thumb_dark.jpg"/>
<meta name="twitter:image:alt" content="Page Thumbnail"/>
<meta name="twitter:title" content="How to create Widgets in iOS 14 in Swift"/>
<meta name="twitter:description" content="Widgets existed in iOS for a long time, but iOS 14 completely revamped them. With the new Widget APIs, not you're able to add widgets directly to your home screen, but they are also completely written in SwiftUI."/>
<meta name="twitter:site" content="@rockbruno_"/>
<meta name="fediverse:creator" content="@rockbruno@hachyderm.io">
<!-- Favicon -->
<!-- 16x16 -->
<link rel="shortcut icon" href="images/favicon/favicon.ico" type="image/x-icon">
<link rel="apple-touch-icon" href="images/favicon/favicon_180.png" sizes="180x180">
<link rel="icon" href="images/favicon/favicon_32.png" sizes="32x32" type="image/png">
<link rel="icon" href="images/favicon/favicon_48.png" sizes="48x48" type="image/png">
<link rel="icon" href="images/favicon/favicon_96.png" sizes="96x96" type="image/png">
<link rel="icon" href="images/favicon/favicon_144.png" sizes="144x144" type="image/png">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Source+Sans+3:ital,wght@0,200..900;1,200..900&display=swap" rel="stylesheet">
<link rel="canonical" href="https://swiftrocks.com/ios-14-widget-tutorial-mini-apps"/>
<!-- Bootstrap CSS Plugins -->
<link rel="stylesheet" type="text/css" href="css/bootstrap.css">
<!-- Prism CSS Stylesheet -->
<link rel="stylesheet" type="text/css" href="css/prism5.css">
<!-- Main CSS Stylesheet -->
<link rel="stylesheet" type="text/css" href="css/style49.css">
<link rel="stylesheet" type="text/css" href="css/sponsor5.css">
<!-- HTML5 shiv and Respond.js support IE8 or Older for HTML5 elements and media queries -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
<script type="application/ld+json">
{
"@context": "https://schema.org",
"@type": "BlogPosting",
"mainEntityOfPage": {
"@type": "WebPage",
"@id": "https://swiftrocks.com/ios-14-widget-tutorial-mini-apps"
},
"image": [
"https://swiftrocks.com/images/thumbs/thumb_dark.jpg"
],
"datePublished": "2020-06-23T18:10:00+02:00",
"dateModified": "2020-06-25T13:50:00+02:00",
"author": {
"@type": "Person",
"name": "Bruno Rocha"
},
"publisher": {
"@type": "Organization",
"name": "SwiftRocks",
"logo": {
"@type": "ImageObject",
"url": "https://swiftrocks.com/images/thumbs/thumb_dark.jpg"
}
},
"headline": "How to create Widgets in iOS 14 in Swift",
"abstract": "Widgets existed in iOS for a long time, but iOS 14 completely revamped them. With the new Widget APIs, not you're able to add widgets directly to your home screen, but they are also completely written in SwiftUI."
}
</script>
</head>
<body>
<div id="main">
<!-- Blog Header -->
<!-- Blog Post (Right Sidebar) Start -->
<div class="container">
<div class="col-xs-12">
<div class="page-body">
<div class="row">
<div><a class="logo-link" href="https://swiftrocks.com">
<img id="logo" class="logo" alt="SwiftRocks" src="images/bg/logo2dark.png">
</a>
<div class="menu-large">
<div class="menu-arrow-right"></div>
<div class="menu-header menu-header-large">
<div class="menu-item">
<a href="blog">blog</a>
</div>
<div class="menu-item">
<a href="about">about</a>
</div>
<div class="menu-item">
<a href="talks">talks</a>
</div>
<div class="menu-item">
<a href="projects">projects</a>
</div>
<div class="menu-item">
<a href="software-engineering-book-recommendations">book recs</a>
</div>
<div class="menu-item">
<a href="games">game recs</a>
</div>
<div class="menu-arrow-right-2"></div>
</div>
</div>
<div class="menu-small">
<div class="menu-arrow-right"></div>
<div class="menu-header menu-header-small-1">
<div class="menu-item">
<a href="blog">blog</a>
</div>
<div class="menu-item">
<a href="about">about</a>
</div>
<div class="menu-item">
<a href="talks">talks</a>
</div>
<div class="menu-item">
<a href="projects">projects</a>
</div>
<div class="menu-arrow-right-2"></div>
</div>
<div class="menu-arrow-right"></div>
<div class="menu-header menu-header-small-2">
<div class="menu-item">
<a href="software-engineering-book-recommendations">book recs</a>
</div>
<div class="menu-item">
<a href="games">game recs</a>
</div>
<div class="menu-arrow-right-2"></div>
</div>
</div>
</div>
<div class="content-page" id="WRITEIT_DYNAMIC_CONTENT">
<!--WRITEIT_POST_NAME=How to create Widgets in iOS 14 in Swift-->
<!--WRITEIT_POST_HTML_NAME=ios-14-widget-tutorial-mini-apps-->
<!--Add here the additional properties that you want each page to possess.-->
<!--These properties can be used to change content in the template page or in the page itself as shown here.-->
<!--Properties must start with 'WRITEIT_POST'.-->
<!--Writeit provides and injects WRITEIT_POST_NAME and WRITEIT_POST_HTML_NAME by default.-->
<!--WRITEIT_POST_SHORT_DESCRIPTION=Widgets existed in iOS for a long time, but iOS 14 completely revamped them. With the new Widget APIs, not you're able to add widgets directly to your home screen, but they are also completely written in SwiftUI.-->
<!--WRITEIT_POST_SITEMAP_DATE_LAST_MOD=2020-06-25T13:50:00+02:00-->
<!--WRITEIT_POST_SITEMAP_DATE=2020-06-23T18:10:00+02:00-->
<title>How to create Widgets in iOS 14 in Swift</title>
<div class="blog-post">
<div class="post-title-index">
<h1>How to create Widgets in iOS 14 in Swift</h1>
</div>
<div class="post-info">
<div class="post-info-text">
Published on 23 June 2020
</div>
</div>
<p>Widgets existed in iOS for a long time, but iOS 14 completely revamped them. With the new Widget APIs, not you're able to add widgets directly to your home screen, but they are also completely written in SwiftUI. iOS 14's Widgets come in a variety of shapes (literally), ranging from simple information squares to widgets that can retrieve and display information from its parent app's <b>Siri Intents</b>.</p>
<div class="sponsor-article-ad-auto hidden"></div>
<p>One trick that has drawn my attention the most however is that having widgets directly in your home means that technically you're now able to make visual "mini apps". If you find yourself doing the same tasks over and over in your job such as checking the number of crashes in a release or the latest release supported by one of your apps, you can create a Widget in iOS 14 that essentially behaves like a super-charged, UI-enabled <b>Siri Shortcut</b>.</p>
<p>Although you can't interact with a Widget besides touching it (which triggers a deep link to your app), there aren't many limitations in what you can display in them, so you can use them to develop read-only visual apps. In this article, we'll develop a Widget that shows us <b>the latest commit in the Swift repository.</b></p>
<h2>Developing a "Swift commit tracker" Widget</h2>
<p>I find myself going to the Swift repo once in a while to see what the community is up to. To make my life easier, how about displaying this information directly on my home screen?</p>
<div class="post-image margin-top-40 margin-bottom-40">
<img src="https://i.imgur.com/7iNmotK.jpg" alt="">
</div>
<p>To do something like this, we can make a request to GitHub's public APIs, parse the information and render it to our widget.</p>
<p>We can start by creating a new iOS project -- the details of the project don't matter as in this tutorial all the code will be inside the Widget's module.</p>
<p>With your project created, add a Widget module by going to <b>File -> New -> Target</b> and selecting the <b>Widget Extension</b> target:</p>
<div class="post-image margin-top-40 margin-bottom-40">
<img src="https://i.imgur.com/xDsjmiD.png" alt="">
</div>
<p>Make sure to uncheck the <b>Include Configuration Intent</b> checkbox, as this involves a feature that will be presented only later in this article! After generating the target, make sure to erase the example code so we can inspect it step by step.</p>
<p>To define a Widget, all you have to do is create a struct that inherits from <b>Widget</b> and configures its capabilities:</p>
<pre><code>@main
struct CommitCheckerWidget: Widget {
private let kind: String = "CommitCheckerWidget"
public var body: some WidgetConfiguration {
StaticConfiguration(kind: kind, provider: CommitTimeline(), placeholder: PlaceholderView()) { entry in
CommitCheckerWidgetView(entry: entry)
}
.configurationDisplayName("Swift's Latest Commit")
.description("Shows the last commit at the Swift repo.")
}
}</code></pre>
<p>This code will not compile before we define such capabilities, but this is important as a first step because this is the Widget itself. The <code>WidgetConfiguration</code> return value describes what this widget is and how it's built, but most importantly, how it fetches its content.</p>
<h2>Types of Widgets</h2>
<p>The <code>StaticConfiguration</code> <code>WidgetConfiguration</code> defines a Widget that can resolve itself without any input from the user. You could fetch any relevant data in the Widget's parent app and send the result to the Widget module as an "user input", but as you are allowed to make API calls when configuring your Widget, there's no need to do so if there's no contextual information involved in the request.</p>
<p>On the other hand, you can use the <code>IntentConfiguration</code> <code>WidgetConfiguration</code> to define a Widget that depends on a Siri Intent from the parent app, which allows you to build configurable dynamic widgets. For example, when using intents, a food delivery app can create a widget that displays the delivery status for the user's latest order. This is done by having the app dispatch a Siri Intent (just like when developing Siri Shortcuts), which are automatically picked up by <code>IntentConfiguration</code> and used to update a Widget. You can create a base <code>IntentConfiguration</code> Widget by checking the intents box when creating the Widget Extension, but since all we need to do is parse GitHub's public API, we can use a <code>StaticConfiguration</code> Widget and avoid interacting with the app itself.</p>
<h2>TimelineProvider</h2>
<p>The content displayed by iOS 14's Widgets works similarly to watchOS's complications in the sense that instead of having an extension that is running all the time, you provide, at once, a "timeline" of events that the OS should display throughout the hours, days or even weeks. This is useful for apps like <b>Weather</b> and <b>Calendar</b> where you can "predict" what is going to be displayed in the future as you already have that information.</p>
<p>In our case, since we are unable to predict Swift's commits, we'll provide a timeline that contains only a single event -- making iOS refresh our Widget in a more regular basis.</p>
<p>To create a <code>Timeline</code>, we first need to define a <code>TimelineEntry</code>. A <code>TimelineEntry</code> only requires the <code>Date</code> when this entry is expected to be rendered in the Widget, but it can also contain any additional information that you require. In our case, our entries will contain the <code>Commit</code> that we want to display in the Widget.</p>
<pre><code>struct Commit {
let message: String
let author: String
let date: String
}
struct LastCommitEntry: TimelineEntry {
public let date: Date
public let commit: Commit
}</code></pre>
<p>But before creating the timeline, we need to be able to fetch such commits. Let's create a <code>CommitLoader</code> class that fetches and parses Swift's latest commit:</p>
<pre><code>struct Commit {
let message: String
let author: String
let date: String
}
struct CommitLoader {
static func fetch(completion: @escaping (Result<Commit, Error>) -> Void) {
let branchContentsURL = URL(string: "https://api.github.com/repos/apple/swift/branches/main")!
let task = URLSession.shared.dataTask(with: branchContentsURL) { (data, response, error) in
guard error == nil else {
completion(.failure(error!))
return
}
let commit = getCommitInfo(fromData: data!)
completion(.success(commit))
}
task.resume()
}
static func getCommitInfo(fromData data: Foundation.Data) -> Commit {
let json = try! JSONSerialization.jsonObject(with: data, options: []) as! [String: Any]
let commitParentJson = json["commit"] as! [String: Any]
let commitJson = commitParentJson["commit"] as! [String: Any]
let authorJson = commitJson["author"] as! [String: Any]
let message = commitJson["message"] as! String
let author = authorJson["name"] as! String
let date = authorJson["date"] as! String
return Commit(message: message, author: author, date: date)
}
}</code></pre>
<p>When <code>fetch</code> is called, this loader type sends a request to GitHub's public API and parses the latest commit -- giving us the message, author and its timestamp. We can now create a <code>Timeline</code> that fetches the latest commit, adds it as an entry and schedules itself to be updated after a while.</p>
<pre><code>struct CommitTimeline: TimelineProvider {
typealias Entry = LastCommitEntry
/* protocol methods implemented below! */
}</code></pre>
<p>The <code>TimelineProvider</code> protocol has two methods that we need to implement:</p>
<h3><code>snapshot()</code> - The fake information of the Widget</h3>
<p>The <code>snapshot()</code> required method of the <code>TimelineProvider</code> protocol defines how your Widget should be configured when your Widget appears in transient situations, such as the Widget selection screen. This configuration will be used when showing correct information doesn't matter:</p>
<div class="post-image margin-top-40 margin-bottom-40">
<img src="https://i.imgur.com/CpKrwmv.jpg" alt="">
</div>
<p>To create a snapshot configuration, all you have to do is create and return a fake entry of your <code>TimelineEntry</code> object.</p>
<pre><code>public func snapshot(with context: Context, completion: @escaping (LastCommitEntry) -> ()) {
let fakeCommit = Commit(message: "Fixed stuff", author: "John Appleseed", date: "2020-06-23")
let entry = LastCommitEntry(date: Date(), commit: fakeCommit)
completion(entry)
}</code></pre>
<h3><code>timeline()</code> - The true information of the Widget</h3>
<p>The <code>timeline()</code> method, however, defines the real information that should be used by your widget. The objective is for you to return a <code>Timeline</code> instance that contains all the entries you want to display, <b>when</b> they are expected to be displayed (the <code>date</code> of the entry) and when the timeline "expires".</p>
<p>Because our app can't "predict" its future state like a Weather app, it suffices for us to create a timeline with a single entry that should be displayed immediately, which can be done by setting the entry's <code>date</code> to the current <code>Date()</code>:</p>
<pre><code>public func timeline(with context: Context, completion: @escaping (Timeline<LastCommitEntry>) -> ()) {
let currentDate = Date()
let refreshDate = Calendar.current.date(byAdding: .minute, value: 5, to: currentDate)!
CommitLoader.fetch { result in
let commit: Commit
if case .success(let fetchedCommit) = result {
commit = fetchedCommit
} else {
commit = Commit(message: "Failed to load commits", author: "", date: "")
}
let entry = LastCommitEntry(date: currentDate, commit: commit)
let timeline = Timeline(entries: [entry], policy: .after(refreshDate))
completion(timeline)
}
}</code></pre>
<p>The <code>policy</code> property of the timeline is what defines <b>when</b> should iOS attempt to discard this timeline and fetch a new one. Currently, they can be <code>.never</code> (Widgets displaying a static content that never changes), <code>.atEnd</code> (when the last entry in the timeline is displayed), or <code>.after(Date)</code>, which is after a specific amount of time after displaying the timeline for the first time. Since our timeline only has one entry, I decided to use <code>.after</code> to tell iOS that this widget should be reloaded every 5 minutes.</p>
<p>Note, however, that the Widget API's documentation states that you <b>can't predict when the Widget will be updated.</b> Even though the timeline itself will be indeed fetched again after 5 minutes, there's no guarantee that the iOS will update the view at the same time. From my personal experience when writing this, the view actually took around <b>~20 minutes</b> to update by itself. The update time is based on a few factors, which includes how often the Widget is seen by the user. If you need to <b>force</b> a Widget to update, you can use the <code>WidgetCenter</code> APIs from your main app to reload all timelines (or a specific one):</p>
<pre><code>WidgetCenter.shared.reloadAllTimelines()</code></pre>
<p>While not necessary by our Widget, it's important to mention that timelines and entries have other interesting capabilities. For example, it's possible to set a <b>relevance</b> value to an entry, which will allow iOS to determine how important your Widget is. This is used, for example, to determine the order of Widgets inside a stack:</p>
<pre><code>struct LastCommit: TimelineEntry {
public let date: Date
public let commit: Commit
var relevance: TimelineEntryRelevance? {
return TimelineEntryRelevance(score: 10) // 0 - not important | 100 - very important
}
}</code></pre>
<h2>Creating a Widget View</h2>
<p>Now that our timeline is configured, we can create the Widget's visual components. We need to create <b>two</b> views: A <b>placeholder</b> that is displayed while the timeline is loading, and the actual Widget view that is capable of rendering our timeline entry.</p>
<pre><code>struct PlaceholderView : View {
var body: some View {
Text("Loading...")
}
}
struct CommitCheckerWidgetView : View {
let entry: LastCommitEntry
var body: some View {
VStack(alignment: .leading, spacing: 4) {
Text("apple/swift's Latest Commit")
.font(.system(.title3))
.foregroundColor(.black)
Text(entry.commit.message)
.font(.system(.callout))
.foregroundColor(.black)
.bold()
Text("by \(entry.commit.author) at \(entry.commit.date)")
.font(.system(.caption))
.foregroundColor(.black)
Text("Updated at \(Self.format(date:entry.date))")
.font(.system(.caption2))
.foregroundColor(.black)
}.frame(minWidth: 0, maxWidth: .infinity, minHeight: 0, maxHeight: .infinity, alignment: .leading)
.padding()
.background(LinearGradient(gradient: Gradient(colors: [.orange, .yellow]), startPoint: .top, endPoint: .bottom))
}
static func format(date: Date) -> String {
let formatter = DateFormatter()
formatter.dateFormat = "MM-dd-yyyy HH:mm"
return formatter.string(from: date)
}
}</code></pre>
<h3>Interacting with a Widget View</h3>
<p>Optionally, you can detect taps in your Widget and redirect them to a deeplink. This is unfortunately the only interaction you're allowed to have in your widget, so no scrolling or other forms of interaction are possible.</p>
<p>You can configure which deeplink is triggered when your Widget is tapped through the <code>.widgetURL(myDeeplink)</code> method, but you can also make different parts of the widget trigger different deeplinks by using a <code>Link</code>. Note that since widgets are small, you shouldn't pack a ton of actions into a single Widget.</p>
<p>Here's an example of a Widget View that redirects to the app's home screen when tapped, but also contains two labels that redirect to different parts of the app when tapped.</p>
<pre><code>var body: some View {
VStack {
Link(destination: homeDeepLink) {
Text("Home")
}
Link(destination: settingsDeepLink) {
Text("Settings")
}
}.widgetURL(homeDeeplink)
}</code></pre>
<p>If you don't provide a <code>widgetURL</code>, your app will simply open when tapped.</p>
<h2>Seeing the Widget in action</h2>
<p>You should be able to compile your code, and now that all components were provided, we can take a second look at our configuration method to see how this is all wrapped together:</p>
<pre><code>@main
struct CommitCheckerWidget: Widget {
private let kind: String = "CommitCheckerWidget"
public var body: some WidgetConfiguration {
StaticConfiguration(kind: kind, provider: CommitTimeline(), placeholder: PlaceholderView()) { entry in
CommitCheckerWidgetView(entry: entry)
}
.configurationDisplayName("Swift's Latest Commit")
.description("Shows the last commit at the Swift repo.")
}
}</code></pre>
<p>We've created a static widget that fetches its content from our <code>CommitTimeline</code>, has a <code>PlaceholderView</code> as a placeholder and generates a <code>CommitCheckerWidgetView</code> when an entry is ready to be displayed.</p>
<p>After running our app and adding the Widget to our home, we're now able to see an auto-updating Swift commit displayer!</p>
<div class="post-image margin-top-40 margin-bottom-40">
<img src="https://i.imgur.com/h8bBgyJ.jpg" alt="">
</div>
<h2>Allowing the user to configure which repo / branch to visualize</h2>
<p>As mentioned before, iOS 14's new APIs also support Widgets that are tied to <b>Siri Intents</b>, allowing you to create dynamic Widgets that are configurable by your users. We can have an intent-based Widget that allows the user to configure which repo to watch, directly from the Widget itself.</p>
<p>To create an intent-based Widget, we first need a Siri intent. Inside your Widget Extensions, add a <b>SiriKit Intent Definition File</b>.</p>
<p>To allow the user to see the commits of any repo or branch, let's create a <code>LastCommitIntent</code> that supports the <b>account</b>, <b>repo</b> and <b>branch</b> properties. Make sure to also tick the <b>Intent is eliglible for Widgets</b> box.</p>
<div class="post-image margin-top-40 margin-bottom-40">
<img src="https://i.imgur.com/3HuvF8V.png" alt="">
</div>
<p>It's possible to use Widgets with the data of any donated Siri Intent, but the magic lies in not needing to. If the intent has widget capabilities, like the one we created, you're able to set the parameters <b>directly at the Widget</b> as we'll see later on.</p>
<p>Before upgrading our Widget, let's make sure our code supports fetching commits from other repos. Let's upgrade our timeline entry to support a repo configuration:</p>
<pre><code>struct RepoBranch {
let account: String
let repo: String
let branch: String
}
struct LastCommit: TimelineEntry {
public let date: Date
public let commit: Commit
public let branch: RepoBranch
}</code></pre>
<p>From here, we can upgrade our fetcher's <code>fetch()</code> method to download any branch from any repo:</p>
<pre><code>static func fetch(account: String, repo: String, branch: String, completion: @escaping (Result
<commit, error>
) -> Void) {
</commit,>
let branchContentsURL = URL(string: "https://api.github.com/repos/\(account)/\(repo)/branches/\(branch)")!
// ...
}</code></pre>
<p>As mentioned before, intents-based Widgets require the usage of <code>IntentConfiguration</code>, whose's only major difference from our previous static approach is that we have to provide the intent which this widget is linked to. Let's update our Widget to use <code>IntentConfiguration</code> and <code>LastCommitIntent</code>:</p>
<pre><code>@main
struct CommitCheckerWidget: Widget {
private let kind: String = "CommitCheckerWidget"
public var body: some WidgetConfiguration {
IntentConfiguration(kind: kind, intent: LastCommitIntent.self, provider: CommitTimeline(), placeholder: PlaceholderView()) { entry in
CommitCheckerWidgetView(entry: entry)
}
.configurationDisplayName("A Repo's Latest Commit")
.description("Shows the last commit at the a repo/branch combination.")
}
}</code></pre>
<p>One additional modification we have to make is updating our timeline to inherit from <code>IntentTimelineProvider</code> instead of <code>TimelineProvider</code>. They work mostly the same way, with the difference being that the intents variant provides access to an instance of our intent, allowing us to grab a hold of any customizations made by our users. In this case, we'll update <code>snapshot()</code> to additionally return a fake repo and our timeline method to fetch the user's repo configuration and fetch the commit using those parameters.</p>
<pre><code>struct CommitTimeline: IntentTimelineProvider {
typealias Entry = LastCommit
typealias Intent = LastCommitIntent
public func snapshot(for configuration: LastCommitIntent, with context: Context, completion: @escaping (LastCommit) -> ()) {
let fakeCommit = Commit(message: "Fixed stuff", author: "John Appleseed", date: "2020-06-23")
let entry = LastCommit(
date: Date(),
commit: fakeCommit,
branch: RepoBranch(
account: "apple",
repo: "swift",
branch: "main"
)
)
completion(entry)
}
public func timeline(for configuration: LastCommitIntent, with context: Context, completion: @escaping (Timeline<Entry>) -> ()) {
let currentDate = Date()
let refreshDate = Calendar.current.date(byAdding: .minute, value: 5, to: currentDate)!
guard let account = configuration.account,
let repo = configuration.repo,
let branch = configuration.branch
else {
let commit = Commit(message: "Failed to load commits", author: "", date: "")
let entry = LastCommit(date: currentDate, commit: commit, branch: RepoBranch(
account: "???",
repo: "???",
branch: "???"
))
let timeline = Timeline(entries: [entry], policy: .after(refreshDate))
completion(timeline)
return
}
CommitLoader.fetch(account: account, repo: repo, branch: branch) { result in
let commit: Commit
if case .success(let fetchedCommit) = result {
commit = fetchedCommit
} else {
commit = Commit(message: "Failed to load commits", author: "", date: "")
}
let entry = LastCommit(date: currentDate, commit: commit, branch: RepoBranch(
account: account,
repo: repo,
branch: branch
))
let timeline = Timeline(entries: [entry], policy: .after(refreshDate))
completion(timeline)
}
}
}</code></pre>
<p>While this code works, our view still has "apple/swift" hardcoded into it. Let's update it to use the new parameters the entry now possesses:</p>
<pre><code>struct RepoBranchCheckerEntryView : View {
var entry: Provider.Entry
var body: some View {
VStack(alignment: .leading, spacing: 4) {
Text("\(entry.branch.account)/\(entry.branch.repo)'s \(entry.branch.branch) Latest Commit")
.font(.system(.title3))
.foregroundColor(.black)
Text("\(entry.commit.message)")
.font(.system(.callout))
.foregroundColor(.black)
.bold()
Text("by \(entry.commit.author) at \(entry.commit.date)")
.font(.system(.caption))
.foregroundColor(.black)
Text("Updated at \(Self.format(date:entry.date))")
.font(.system(.caption2))
.foregroundColor(.black)
}.frame(minWidth: 0, maxWidth: .infinity, minHeight: 0, maxHeight: .infinity, alignment: .leading)
.padding()
.background(LinearGradient(gradient: Gradient(colors: [.orange, .yellow]), startPoint: .top, endPoint: .bottom))
}
static func format(date: Date) -> String {
let formatter = DateFormatter()
formatter.dateFormat = "MM-dd-yyyy HH:mm"
return formatter.string(from: date)
}
}</code></pre>
<p>Now, run your app and check the Widget. The repo configuration you see will be determined by the default value you added in the intents file, but if you long press your Widget and click the <b>Edit</b> button, you will now be able to customize the intent's parameters and change the repo that is fetched!</p>
<div class="post-image margin-top-40 margin-bottom-40">
<img src="https://i.imgur.com/NvMfu2e.jpg" alt="">
</div>
<div class="post-image margin-top-40 margin-bottom-40">
<img src="https://i.imgur.com/mu8tBgl.jpg" alt="">
</div>
<h2>Supporting Multiple Widgets</h2>
<p>It's possible to make your app provide <b>multiple</b> choices of Widgets by creating a <code>WidgetBundle</code> that returns the <code>WidgetConfiguration</code> of one or more Widgets. To do so, you need to remove the <code>@main</code> declaration of your main Widget's configuration and instead add it to a new bundle struct:</p>
<pre><code>@main
struct SwiftWidgetsBundle: WidgetBundle {
@WidgetBundleBuilder
var body: some Widget {
RepoBranchChecker()
}
}</code></pre>
<p>You can then support multiple Widgets by simply adding more configurations to this bundle:</p>
<pre><code>@main
struct SwiftWidgetsBundle: WidgetBundle {
@WidgetBundleBuilder
var body: some Widget {
RepoBranchChecker()
CommitNumberChecker()
AppleOpenSourceProjectsChecker()
}
}</code></pre>
<div class="sponsor-article-ad-auto hidden"></div>
<p>With this in place, when trying to add a Widget from your app, you'll be able to see the additional Widget options by swiping.</p>
<h2>Where to go from here?</h2>
<p>There are further customizations you can do Widgets, including rendering different info depending on the container size of the Widget, locking the possible Widget sizes and more. Check WWDC 2020's sessions for more information on Widgets.</p>
</div></div>
<div class="blog-post footer-main">
<div class="footer-logos">
<a href="https://swiftrocks.com/rss.xml"><i class="fa fa-rss"></i></a>
<a href="https://hachyderm.io/@rockbruno"><svg class="svg-logo-link" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 448 512"><!--!Font Awesome Free 6.7.2 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free Copyright 2025 Fonticons, Inc.--><path d="M433 179.1c0-97.2-63.7-125.7-63.7-125.7-62.5-28.7-228.6-28.4-290.5 0 0 0-63.7 28.5-63.7 125.7 0 115.7-6.6 259.4 105.6 289.1 40.5 10.7 75.3 13 103.3 11.4 50.8-2.8 79.3-18.1 79.3-18.1l-1.7-36.9s-36.3 11.4-77.1 10.1c-40.4-1.4-83-4.4-89.6-54a102.5 102.5 0 0 1 -.9-13.9c85.6 20.9 158.7 9.1 178.8 6.7 56.1-6.7 105-41.3 111.2-72.9 9.8-49.8 9-121.5 9-121.5zm-75.1 125.2h-46.6v-114.2c0-49.7-64-51.6-64 6.9v62.5h-46.3V197c0-58.5-64-56.6-64-6.9v114.2H90.2c0-122.1-5.2-147.9 18.4-175 25.9-28.9 79.8-30.8 103.8 6.1l11.6 19.5 11.6-19.5c24.1-37.1 78.1-34.8 103.8-6.1 23.7 27.3 18.4 53 18.4 175z"/></svg></a>
<a href="https://twitter.com/rockbruno_"><i class="fa fa-twitter"></i></a>
<a href="https://github.com/rockbruno"><i class="fa fa-github"></i></a>
</div>
<div class="footer-text">
© 2025 Bruno Rocha
</div>
<div class="footer-text">
<p><a href="https://swiftrocks.com">Home</a> / <a href="blog">See all posts</a></p>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- Blog Post (Right Sidebar) End -->
</div>
</div>
</div>
<!-- All Javascript Plugins -->
<script type="text/javascript" src="js/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>
<script type="text/javascript" src="js/prism5.js"></script>
<!-- Main Javascript File -->
<script type="text/javascript" src="js/scripts30.js"></script>
<!-- Google tag (gtag.js) -->
<script async src="https://www.googletagmanager.com/gtag/js?id=G-H8KZTWSQ1R"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'G-H8KZTWSQ1R');
</script>
</body>
</html>