Skip to content

Commit 9a3bc2d

Browse files
committed
Add bundled driver avatars and widget behavior
Add bundled avatar assets and wire them into the widget and demo app. - Add Resources/Assets.xcassets with John and Tim image sets and update Xcode project to include a Resources group and asset references. - Replace pizza-count placeholder in WidgetDemo with circular driver avatar Image(context.state.driverName) in multiple widget layouts and show a conditional headline when the driver is reassigned. - Shorten demo delivery to 15s and normalize driver names (Tim / John). Update ContentView activity logic to: - capture the activity id and re-find the live activity to avoid stale snapshots, - add a midpoint reassign handler that swaps Tim → John (or respects a prior manual reassignment), - push state updates via the fresh Activity reference. - Update updateDeliveryPizza to set driver to John and bump the activity content accordingly. These changes enable bundled avatars shared across app/widget/Live Activity and improve activity update reliability during the demo. Project metadata (project.pbxproj and workspace user state) and development team entries were also updated to include the new Resources asset catalog.
1 parent eda8c4d commit 9a3bc2d

10 files changed

Lines changed: 242 additions & 44 deletions

File tree

‎README.md‎

Lines changed: 105 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -289,24 +289,111 @@ Updating content state for activity DA288E1B-F6F5-4BF1-AA73-E43E0CC13150
289289
Console: Pizza delivery details: DA288E1B-F6F5-4BF1-AA73-E43E0CC13150 -> PizzaDeliveryAttributes(numberOfPizzas: 1, totalAmount: "$99")
290290
```
291291

292-
## How to pass image data to the widget?
293-
Q1. Can I use Local Assets Folder?<br />
294-
A1. YES.<br />
295-
✅ Easy to implement <br/>
296-
✅ May possible to change image (string name) when updating the event<br/>
297-
❎ Limited options and big app size.<br/>
298-
If you need to add more image sets, then re-upload to App Store is required (Time wasting, and not all users can get the instant update)
299-
<br/><br/>
300-
Q2. Can I use Network Image?<br />
301-
A2. YES. Load the image from the Internet, and pass the data to the widget via App Group and AppStorage (aka UserDefaults)<br/>
302-
✅ Update in any time as the url can be changed / modify remotely.<br/>
303-
✅ No need to store in Assets Folder and reduced app size.<br/>
304-
❎ Unless the user re-open the app, the image cannot be updated in the background.
305-
<br /><br />
306-
Q3. How about AsyncImage?<br />
307-
A3. NO. (Known not working)
308-
309-
Both cases 1 & 2 are already demoed in the sample project.
292+
## Sharing Images Across App, Widget & Live Activity 🖼️
293+
294+
The main app, widget extension, and Live Activity are **three separate targets** with three separate bundles. An asset added to one target is **not** automatically visible to the others, and a widget extension cannot make network requests of its own. Pick the strategy that matches where your images come from.
295+
296+
### Demo in this project
297+
298+
The driver avatar shown next to the delivery bar (`John`) is loaded with `Image(context.state.driverName)` in [`WidgetDemo.swift`](WidgetDemo/WidgetDemo.swift). The asset name is driven by the `driverName` value passed in `ContentState`, so changing the driver in the main app automatically swaps the avatar — provided a matching image set exists in the widget's bundle.
299+
300+
This project follows **Case 1 → Option A** below: the avatars (`Tim`, `John`) live in a shared catalog at [`Resources/Assets.xcassets`](Resources/Assets.xcassets) with **target membership ticked on both `iOS16-Live-Activities` and `WidgetDemo`**, so the same image set is reachable from the app, the widget, and the Live Activity without duplication on disk.
301+
302+
---
303+
304+
### Case 1 — Bundled images (shipped with the app)
305+
306+
Best for: a known, finite set of images (logos, badges, demo avatars, fixed driver roster).
307+
308+
**Option A — Multi-target asset catalog (quickest)**
309+
310+
1. Add the image set to *one* `Assets.xcassets`.
311+
2. Select the image set → **File Inspector → Target Membership** → tick **both** the app target and the widget extension.
312+
3. Reference it as usual: `Image("John")`.
313+
314+
> ⚠️ Each ticked target gets its own copy of the image baked into its bundle, so app size grows roughly linearly with the number of targets sharing the asset.
315+
316+
**Option B — Shared Swift Package (cleanest)**
317+
318+
1. Create a local Swift Package (e.g. `SharedAssets`) with its own `Assets.xcassets`.
319+
2. Add the package as a dependency of every target that needs the image.
320+
3. Reference it with the package's bundle:
321+
```swift
322+
Image("John", bundle: .module)
323+
```
324+
4. Result: one copy of the asset for the whole app — smaller binary, single source of truth.
325+
326+
| | Multi-target catalog | Swift Package |
327+
| --- | --- | --- |
328+
| Setup | 30 seconds | A few minutes |
329+
| Storage | Duplicated per target | Single copy |
330+
| Asset name in code | `Image("John")` | `Image("John", bundle: .module)` |
331+
332+
---
333+
334+
### Case 2 — Downloaded images (fetched at runtime)
335+
336+
Best for: user-generated content, unbounded sets (real driver photos, dynamic product imagery), anything that must change without an App Store release.
337+
338+
Widget extensions and Live Activities **cannot perform network calls** during snapshot rendering, and `ActivityKit` `ContentState` payloads are capped at roughly 4 KB — so you cannot ship the image bytes inside the state. The pattern is: **the main app downloads, writes to a shared container, and the widget reads from disk.**
339+
340+
**1. Enable App Groups on both targets**
341+
342+
Xcode → *Signing & Capabilities* → add **App Groups** to the main app **and** the widget extension, both using the same identifier (e.g. `group.com.you.pizza`).
343+
344+
**2. Main app — download and persist**
345+
346+
```swift
347+
let groupID = "group.com.you.pizza"
348+
let container = FileManager.default
349+
.containerURL(forSecurityApplicationGroupIdentifier: groupID)!
350+
351+
func cacheAvatar(for driverID: String, from url: URL) async throws {
352+
let (data, _) = try await URLSession.shared.data(from: url)
353+
let dest = container.appendingPathComponent("\(driverID).png")
354+
try data.write(to: dest, options: .atomic)
355+
}
356+
```
357+
358+
**3. Activity state — pass an identifier, not the image bytes**
359+
360+
```swift
361+
struct DeliveryAttributes: ActivityAttributes {
362+
struct ContentState: Codable, Hashable {
363+
var driverID: String // e.g. "john_123" — NOT the image data
364+
var estimatedDeliveryTime: ClosedRange<Date>
365+
}
366+
}
367+
```
368+
369+
**4. Widget — load from the shared container**
370+
371+
```swift
372+
private func avatar(for driverID: String) -> Image {
373+
let url = FileManager.default
374+
.containerURL(forSecurityApplicationGroupIdentifier: "group.com.you.pizza")!
375+
.appendingPathComponent("\(driverID).png")
376+
if let ui = UIImage(contentsOfFile: url.path) {
377+
return Image(uiImage: ui)
378+
}
379+
return Image(systemName: "person.crop.circle") // graceful fallback
380+
}
381+
```
382+
383+
**Important caveats**
384+
385+
- The widget cannot trigger the download itself. Make sure the main app prefetches the image **before** calling `activity.request(...)` / `activity.update(...)`, otherwise the first snapshot will render the fallback.
386+
- `AsyncImage` does **not** work inside Live Activity / widget snapshots — there is no async render pass. Always pre-write to disk and read synchronously.
387+
- Keep cached images small (a few hundred KB max). Widget extensions have a tight memory budget — a giant image will cause the snapshot to be killed.
388+
- If the user wipes the app data or the cache is evicted, fall back to a `systemName` placeholder rather than crashing.
389+
390+
### Quick chooser
391+
392+
| Image source | Pick |
393+
| --- | --- |
394+
| Static, known at build time | **Case 1** (Swift Package preferred) |
395+
| Server-driven, per-user, or updated post-release | **Case 2** (App Group + shared container) |
396+
| Mixed — a few branded fallbacks plus dynamic content | Combine both: bundle the fallbacks via Case 1, cache the dynamic ones via Case 2 |
310397

311398
## Structure
312399
![diagram](https://raw.githubusercontent.com/1998code/iOS16-Live-Activities/main/diagram.svg)
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
{
2+
"info" : {
3+
"author" : "xcode",
4+
"version" : 1
5+
}
6+
}
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
{
2+
"images" : [
3+
{
4+
"filename" : "John.jpg",
5+
"idiom" : "universal",
6+
"scale" : "1x"
7+
},
8+
{
9+
"idiom" : "universal",
10+
"scale" : "2x"
11+
},
12+
{
13+
"idiom" : "universal",
14+
"scale" : "3x"
15+
}
16+
],
17+
"info" : {
18+
"author" : "xcode",
19+
"version" : 1
20+
}
21+
}
28.8 KB
Loading
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
{
2+
"images" : [
3+
{
4+
"filename" : "Tim.jpg",
5+
"idiom" : "universal",
6+
"scale" : "1x"
7+
},
8+
{
9+
"idiom" : "universal",
10+
"scale" : "2x"
11+
},
12+
{
13+
"idiom" : "universal",
14+
"scale" : "3x"
15+
}
16+
],
17+
"info" : {
18+
"author" : "xcode",
19+
"version" : 1
20+
}
21+
}
31.1 KB
Loading

‎WidgetDemo/WidgetDemo.swift‎

Lines changed: 21 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -110,9 +110,12 @@ struct PizzaDeliveryActivityWidget: Widget {
110110
}
111111
.frame(height: 32)
112112
Spacer()
113-
Text("\(context.attributes.numberOfPizzas) 🍕")
114-
.font(.title)
115-
.bold()
113+
Image(context.state.driverName)
114+
.resizable()
115+
.scaledToFill()
116+
.frame(width: 44, height: 44)
117+
.clipShape(Circle())
118+
.overlay(Circle().stroke(.white, lineWidth: 2))
116119
}.padding(5)
117120
Text("You've already paid: \(context.attributes.totalAmount) + $9.9 Delivery Fee 💸")
118121
.font(.caption)
@@ -121,9 +124,15 @@ struct PizzaDeliveryActivityWidget: Widget {
121124
}.padding(15)
122125
} else {
123126
VStack(alignment: .leading) {
124-
Text("Your \(context.state.driverName) is on the way!")
125-
.font(.headline)
126-
.padding(.horizontal, 5)
127+
if context.state.driverName == "Tim" {
128+
Text("Your \(context.state.driverName) is on the way!")
129+
.font(.headline)
130+
.padding(.horizontal, 5)
131+
} else {
132+
Text("Apple reassigned \(context.state.driverName) to deliver your order")
133+
.font(.headline)
134+
.padding(.horizontal, 5)
135+
}
127136
HStack {
128137
VStack(alignment: .leading) {
129138
// Bar stack:
@@ -208,9 +217,12 @@ struct PizzaDeliveryActivityWidget: Widget {
208217
}
209218
Spacer()
210219
VStack {
211-
Text("\(context.attributes.numberOfPizzas) 🍕")
212-
.font(.title)
213-
.bold()
220+
Image(context.state.driverName)
221+
.resizable()
222+
.scaledToFill()
223+
.frame(width: 44, height: 44)
224+
.clipShape(Circle())
225+
.overlay(Circle().stroke(.white, lineWidth: 2))
214226
Spacer()
215227
}
216228
}.padding(5)

‎iOS16-Live-Activities.xcodeproj/project.pbxproj‎

Lines changed: 17 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,8 @@
1616
3A34C50D2892C432003EB69F /* WidgetDemo.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3A34C50C2892C432003EB69F /* WidgetDemo.swift */; };
1717
3A34C50F2892C433003EB69F /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 3A34C50E2892C433003EB69F /* Assets.xcassets */; };
1818
3A34C5132892C433003EB69F /* WidgetDemoExtension.appex in Embed Foundation Extensions */ = {isa = PBXBuildFile; fileRef = 3A34C5052892C432003EB69F /* WidgetDemoExtension.appex */; settings = {ATTRIBUTES = (RemoveHeadersOnCopy, ); }; };
19+
3A7722902F9E312E00590CB8 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 3A77228E2F9E312E00590CB8 /* Assets.xcassets */; };
20+
3A7722912F9E312E00590CB8 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 3A77228E2F9E312E00590CB8 /* Assets.xcassets */; };
1921
3AC6C11E2893968A001B44DC /* ActivityAttributes.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3AC6C11D2893968A001B44DC /* ActivityAttributes.swift */; };
2022
3AC6C11F2893968F001B44DC /* ActivityAttributes.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3AC6C11D2893968A001B44DC /* ActivityAttributes.swift */; };
2123
AABB1100DDEE22FF33001111 /* DeliveryKeepAlive.swift in Sources */ = {isa = PBXBuildFile; fileRef = AABB1101DDEE22FF33002222 /* DeliveryKeepAlive.swift */; };
@@ -57,7 +59,8 @@
5759
3A34C50C2892C432003EB69F /* WidgetDemo.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WidgetDemo.swift; sourceTree = "<group>"; };
5860
3A34C50E2892C433003EB69F /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = "<group>"; };
5961
3A34C5102892C433003EB69F /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
60-
3A36686F2892CB94003F048E /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist; path = Info.plist; sourceTree = "<group>"; };
62+
3A36686F2892CB94003F048E /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
63+
3A77228E2F9E312E00590CB8 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = "<group>"; };
6164
3A8D01A528D6C067001A1AFD /* iOS16-Live-Activities.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = "iOS16-Live-Activities.entitlements"; sourceTree = "<group>"; };
6265
3A8D01A628D6C0A8001A1AFD /* WidgetDemoExtension.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = WidgetDemoExtension.entitlements; sourceTree = "<group>"; };
6366
3AC6C11D2893968A001B44DC /* ActivityAttributes.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ActivityAttributes.swift; sourceTree = "<group>"; };
@@ -90,6 +93,7 @@
9093
3A8D01A628D6C0A8001A1AFD /* WidgetDemoExtension.entitlements */,
9194
3A34C4F22892C3A0003EB69F /* iOS16-Live-Activities */,
9295
3A34C50B2892C432003EB69F /* WidgetDemo */,
96+
3A77228F2F9E312E00590CB8 /* Resources */,
9397
3A34C5062892C432003EB69F /* Frameworks */,
9498
3A34C4F12892C3A0003EB69F /* Products */,
9599
);
@@ -146,6 +150,14 @@
146150
path = WidgetDemo;
147151
sourceTree = "<group>";
148152
};
153+
3A77228F2F9E312E00590CB8 /* Resources */ = {
154+
isa = PBXGroup;
155+
children = (
156+
3A77228E2F9E312E00590CB8 /* Assets.xcassets */,
157+
);
158+
path = Resources;
159+
sourceTree = "<group>";
160+
};
149161
/* End PBXGroup section */
150162

151163
/* Begin PBXNativeTarget section */
@@ -228,6 +240,7 @@
228240
buildActionMask = 2147483647;
229241
files = (
230242
3A34C4FB2892C3A2003EB69F /* Preview Assets.xcassets in Resources */,
243+
3A7722902F9E312E00590CB8 /* Assets.xcassets in Resources */,
231244
3A34C4F82892C3A2003EB69F /* Assets.xcassets in Resources */,
232245
);
233246
runOnlyForDeploymentPostprocessing = 0;
@@ -236,6 +249,7 @@
236249
isa = PBXResourcesBuildPhase;
237250
buildActionMask = 2147483647;
238251
files = (
252+
3A7722912F9E312E00590CB8 /* Assets.xcassets in Resources */,
239253
3A34C50F2892C433003EB69F /* Assets.xcassets in Resources */,
240254
);
241255
runOnlyForDeploymentPostprocessing = 0;
@@ -398,7 +412,7 @@
398412
CODE_SIGN_STYLE = Automatic;
399413
CURRENT_PROJECT_VERSION = 1;
400414
DEVELOPMENT_ASSET_PATHS = "\"iOS16-Live-Activities/Preview Content\"";
401-
DEVELOPMENT_TEAM = "";
415+
DEVELOPMENT_TEAM = 9PAHLTG8AD;
402416
ENABLE_PREVIEWS = YES;
403417
GENERATE_INFOPLIST_FILE = YES;
404418
INFOPLIST_FILE = "iOS16-Live-Activities/Info.plist";
@@ -432,7 +446,7 @@
432446
CODE_SIGN_STYLE = Automatic;
433447
CURRENT_PROJECT_VERSION = 1;
434448
DEVELOPMENT_ASSET_PATHS = "\"iOS16-Live-Activities/Preview Content\"";
435-
DEVELOPMENT_TEAM = "";
449+
DEVELOPMENT_TEAM = 9PAHLTG8AD;
436450
ENABLE_PREVIEWS = YES;
437451
GENERATE_INFOPLIST_FILE = YES;
438452
INFOPLIST_FILE = "iOS16-Live-Activities/Info.plist";

0 commit comments

Comments
 (0)