Skip to content

A cross platform Audiobookshelf client for Android and iOS

Dart

Add iOS homescreen widgets with WidgetKit

Nathan Poulson15318b3434fb
diff --git a/ios/NowPlayingWidget/Assets.xcassets/AccentColor.colorset/Contents.json b/ios/NowPlayingWidget/Assets.xcassets/AccentColor.colorset/Contents.json
new file mode 100644
index 00000000..eb878970
--- /dev/null
+++ b/ios/NowPlayingWidget/Assets.xcassets/AccentColor.colorset/Contents.json
@@ -0,0 +1,11 @@
+{
+ "colors" : [
+ {
+ "idiom" : "universal"
+ }
+ ],
+ "info" : {
+ "author" : "xcode",
+ "version" : 1
+ }
+}
diff --git a/ios/NowPlayingWidget/Assets.xcassets/AppIcon.appiconset/Contents.json b/ios/NowPlayingWidget/Assets.xcassets/AppIcon.appiconset/Contents.json
new file mode 100644
index 00000000..13613e3e
--- /dev/null
+++ b/ios/NowPlayingWidget/Assets.xcassets/AppIcon.appiconset/Contents.json
@@ -0,0 +1,13 @@
+{
+ "images" : [
+ {
+ "idiom" : "universal",
+ "platform" : "ios",
+ "size" : "1024x1024"
+ }
+ ],
+ "info" : {
+ "author" : "xcode",
+ "version" : 1
+ }
+}
diff --git a/ios/NowPlayingWidget/Assets.xcassets/Contents.json b/ios/NowPlayingWidget/Assets.xcassets/Contents.json
new file mode 100644
index 00000000..73c00596
--- /dev/null
+++ b/ios/NowPlayingWidget/Assets.xcassets/Contents.json
@@ -0,0 +1,6 @@
+{
+ "info" : {
+ "author" : "xcode",
+ "version" : 1
+ }
+}
diff --git a/ios/NowPlayingWidget/Assets.xcassets/WidgetBackground.colorset/Contents.json b/ios/NowPlayingWidget/Assets.xcassets/WidgetBackground.colorset/Contents.json
new file mode 100644
index 00000000..eb878970
--- /dev/null
+++ b/ios/NowPlayingWidget/Assets.xcassets/WidgetBackground.colorset/Contents.json
@@ -0,0 +1,11 @@
+{
+ "colors" : [
+ {
+ "idiom" : "universal"
+ }
+ ],
+ "info" : {
+ "author" : "xcode",
+ "version" : 1
+ }
+}
diff --git a/ios/NowPlayingWidget/Info.plist b/ios/NowPlayingWidget/Info.plist
new file mode 100644
index 00000000..49ceae7e
--- /dev/null
+++ b/ios/NowPlayingWidget/Info.plist
@@ -0,0 +1,29 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0">
+<dict>
+ <key>CFBundleDevelopmentRegion</key>
+ <string>$(DEVELOPMENT_LANGUAGE)</string>
+ <key>CFBundleDisplayName</key>
+ <string>Absorb</string>
+ <key>CFBundleExecutable</key>
+ <string>$(EXECUTABLE_NAME)</string>
+ <key>CFBundleIdentifier</key>
+ <string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
+ <key>CFBundleInfoDictionaryVersion</key>
+ <string>6.0</string>
+ <key>CFBundleName</key>
+ <string>$(PRODUCT_NAME)</string>
+ <key>CFBundlePackageType</key>
+ <string>$(PRODUCT_BUNDLE_PACKAGE_TYPE)</string>
+ <key>CFBundleShortVersionString</key>
+ <string>$(MARKETING_VERSION)</string>
+ <key>CFBundleVersion</key>
+ <string>$(CURRENT_PROJECT_VERSION)</string>
+ <key>NSExtension</key>
+ <dict>
+ <key>NSExtensionPointIdentifier</key>
+ <string>com.apple.widgetkit-extension</string>
+ </dict>
+</dict>
+</plist>
diff --git a/ios/NowPlayingWidget/NowPlayingWidget.swift b/ios/NowPlayingWidget/NowPlayingWidget.swift
new file mode 100644
index 00000000..bee9703c
--- /dev/null
+++ b/ios/NowPlayingWidget/NowPlayingWidget.swift
@@ -0,0 +1,271 @@
+import AppIntents
+import WidgetKit
+import SwiftUI
+
+private let appGroup = "group.com.barnabas.absorb"
+
+// MARK: - Darwin Notification Helper
+
+/// Posts a Darwin notification visible to the main app process.
+private func postDarwinNotification(_ name: String) {
+ let center = CFNotificationCenterGetDarwinNotifyCenter()
+ CFNotificationCenterPostNotification(center, CFNotificationName(name as CFString), nil, nil, true)
+}
+
+// MARK: - App Intents (background-capable widget buttons)
+
+struct SkipBackIntent: AppIntent {
+ static var title: LocalizedStringResource = "Skip Back"
+ static var description = IntentDescription("Skip backward in the current audiobook.")
+
+ func perform() async throws -> some IntentResult {
+ postDarwinNotification("com.barnabas.absorb.widget.skipBack")
+ return .result()
+ }
+}
+
+struct PlayPauseIntent: AppIntent {
+ static var title: LocalizedStringResource = "Play or Pause"
+ static var description = IntentDescription("Toggle audiobook playback.")
+
+ func perform() async throws -> some IntentResult {
+ // Optimistic UI: flip the stored state so the widget redraws immediately.
+ let defaults = UserDefaults(suiteName: appGroup)
+ let wasPlaying = defaults?.bool(forKey: "widget_is_playing") ?? false
+ defaults?.set(!wasPlaying, forKey: "widget_is_playing")
+
+ postDarwinNotification("com.barnabas.absorb.widget.playPause")
+ WidgetCenter.shared.reloadTimelines(ofKind: "NowPlayingWidget")
+ return .result()
+ }
+}
+
+struct SkipForwardIntent: AppIntent {
+ static var title: LocalizedStringResource = "Skip Forward"
+ static var description = IntentDescription("Skip forward in the current audiobook.")
+
+ func perform() async throws -> some IntentResult {
+ postDarwinNotification("com.barnabas.absorb.widget.skipForward")
+ return .result()
+ }
+}
+
+// MARK: - Entry
+
+struct NowPlayingEntry: TimelineEntry {
+ let date: Date
+ let hasBook: Bool
+ let title: String
+ let author: String
+ let isPlaying: Bool
+ let progress: Double
+ let coverImage: UIImage?
+ let skipBack: Int
+ let skipForward: Int
+}
+
+// MARK: - Provider
+
+struct NowPlayingProvider: TimelineProvider {
+ func placeholder(in context: Context) -> NowPlayingEntry {
+ NowPlayingEntry(
+ date: .now, hasBook: true, title: "Audiobook Title",
+ author: "Author Name", isPlaying: false, progress: 0.35,
+ coverImage: nil, skipBack: 10, skipForward: 30
+ )
+ }
+
+ func getSnapshot(in context: Context, completion: @escaping (NowPlayingEntry) -> Void) {
+ completion(readEntry())
+ }
+
+ func getTimeline(in context: Context, completion: @escaping (Timeline<NowPlayingEntry>) -> Void) {
+ completion(Timeline(entries: [readEntry()], policy: .never))
+ }
+
+ private func readEntry() -> NowPlayingEntry {
+ let d = UserDefaults(suiteName: appGroup)
+ let hasBook = d?.bool(forKey: "widget_has_book") ?? false
+ let title = d?.string(forKey: "widget_title") ?? ""
+ let author = d?.string(forKey: "widget_author") ?? ""
+ let isPlaying = d?.bool(forKey: "widget_is_playing") ?? false
+ let progress = Double(d?.integer(forKey: "widget_progress") ?? 0) / 1000.0
+ let skipBack = d?.integer(forKey: "widget_skip_back") ?? 0
+ let skipForward = d?.integer(forKey: "widget_skip_forward") ?? 0
+
+ var cover: UIImage? = nil
+ if let path = d?.string(forKey: "widget_cover_path"), !path.isEmpty {
+ cover = UIImage(contentsOfFile: path)
+ }
+
+ return NowPlayingEntry(
+ date: .now,
+ hasBook: hasBook,
+ title: title.isEmpty ? "Absorb" : title,
+ author: author.isEmpty ? (hasBook ? "" : "Not playing") : author,
+ isPlaying: isPlaying,
+ progress: progress,
+ coverImage: cover,
+ skipBack: skipBack > 0 ? skipBack : 10,
+ skipForward: skipForward > 0 ? skipForward : 30
+ )
+ }
+}
+
+// MARK: - Cover Art
+
+struct CoverArtView: View {
+ let image: UIImage?
+ let cornerRadius: CGFloat
+
+ var body: some View {
+ if let image = image {
+ Image(uiImage: image)
+ .resizable()
+ .aspectRatio(contentMode: .fill)
+ .clipShape(RoundedRectangle(cornerRadius: cornerRadius))
+ } else {
+ RoundedRectangle(cornerRadius: cornerRadius)
+ .fill(.quaternary)
+ .overlay {
+ Image(systemName: "book.closed.fill")
+ .font(.title2)
+ .foregroundStyle(.secondary)
+ }
+ }
+ }
+}
+
+// MARK: - Small Widget
+
+struct SmallWidgetView: View {
+ let entry: NowPlayingEntry
+
+ var body: some View {
+ VStack(spacing: 4) {
+ CoverArtView(image: entry.coverImage, cornerRadius: 10)
+ .frame(maxWidth: .infinity)
+ .aspectRatio(1, contentMode: .fit)
+
+ Text(entry.title)
+ .font(.caption)
+ .fontWeight(.semibold)
+ .lineLimit(1)
+ .frame(maxWidth: .infinity, alignment: .leading)
+
+ Text(entry.author)
+ .font(.caption2)
+ .foregroundStyle(.secondary)
+ .lineLimit(1)
+ .frame(maxWidth: .infinity, alignment: .leading)
+
+ HStack(spacing: 16) {
+ Button(intent: SkipBackIntent()) {
+ Image(systemName: "backward.fill")
+ .font(.caption)
+ }
+ Button(intent: PlayPauseIntent()) {
+ Image(systemName: entry.isPlaying ? "pause.fill" : "play.fill")
+ .font(.caption)
+ }
+ Button(intent: SkipForwardIntent()) {
+ Image(systemName: "forward.fill")
+ .font(.caption)
+ }
+ }
+ .buttonStyle(.plain)
+ .foregroundStyle(.primary)
+ }
+ .containerBackground(.fill.tertiary, for: .widget)
+ }
+}
+
+// MARK: - Medium Widget
+
+struct MediumWidgetView: View {
+ let entry: NowPlayingEntry
+
+ var body: some View {
+ HStack(spacing: 12) {
+ CoverArtView(image: entry.coverImage, cornerRadius: 12)
+ .frame(width: 110, height: 110)
+
+ VStack(alignment: .leading, spacing: 4) {
+ Spacer(minLength: 0)
+
+ Text(entry.title)
+ .font(.subheadline)
+ .fontWeight(.semibold)
+ .lineLimit(2)
+
+ Text(entry.author)
+ .font(.caption)
+ .foregroundStyle(.secondary)
+ .lineLimit(1)
+
+ Spacer(minLength: 0)
+
+ HStack(spacing: 28) {
+ Button(intent: SkipBackIntent()) {
+ Image(systemName: "backward.fill")
+ .font(.title3)
+ .frame(width: 36, height: 36)
+ .contentShape(Rectangle())
+ }
+
+ Button(intent: PlayPauseIntent()) {
+ Image(systemName: entry.isPlaying ? "pause.fill" : "play.fill")
+ .font(.title2)
+ .frame(width: 40, height: 40)
+ .contentShape(Rectangle())
+ }
+
+ Button(intent: SkipForwardIntent()) {
+ Image(systemName: "forward.fill")
+ .font(.title3)
+ .frame(width: 36, height: 36)
+ .contentShape(Rectangle())
+ }
+ }
+ .buttonStyle(.plain)
+ .foregroundStyle(.primary)
+
+ Spacer(minLength: 0)
+ }
+ .frame(maxWidth: .infinity, alignment: .leading)
+ }
+ .containerBackground(.fill.tertiary, for: .widget)
+ }
+}
+
+// MARK: - Entry View
+
+struct NowPlayingWidgetView: View {
+ @Environment(\.widgetFamily) var family
+ let entry: NowPlayingEntry
+
+ var body: some View {
+ switch family {
+ case .systemSmall:
+ SmallWidgetView(entry: entry)
+ default:
+ MediumWidgetView(entry: entry)
+ }
+ }
+}
+
+// MARK: - Widget
+
+@main
+struct AbsorbWidget: Widget {
+ let kind = "NowPlayingWidget"
+
+ var body: some WidgetConfiguration {
+ StaticConfiguration(kind: kind, provider: NowPlayingProvider()) { entry in
+ NowPlayingWidgetView(entry: entry)
+ }
+ .configurationDisplayName("Now Playing")
+ .description("See and control your current audiobook.")
+ .supportedFamilies([.systemSmall, .systemMedium])
+ }
+}
diff --git a/ios/NowPlayingWidget/NowPlayingWidgetExtension.entitlements b/ios/NowPlayingWidget/NowPlayingWidgetExtension.entitlements
new file mode 100644
index 00000000..416ca0e8
--- /dev/null
+++ b/ios/NowPlayingWidget/NowPlayingWidgetExtension.entitlements
@@ -0,0 +1,10 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0">
+<dict>
+ <key>com.apple.security.application-groups</key>
+ <array>
+ <string>group.com.barnabas.absorb</string>
+ </array>
+</dict>
+</plist>
diff --git a/ios/Runner.xcodeproj/project.pbxproj b/ios/Runner.xcodeproj/project.pbxproj
index 6eddd373..4bdd0ae4 100644
--- a/ios/Runner.xcodeproj/project.pbxproj
+++ b/ios/Runner.xcodeproj/project.pbxproj
@@ -17,6 +17,9 @@
97C146FC1CF9000F007C117D /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FA1CF9000F007C117D /* Main.storyboard */; };
97C146FE1CF9000F007C117D /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FD1CF9000F007C117D /* Assets.xcassets */; };
97C147011CF9000F007C117D /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */; };
+ AB10020000000000000E0001 /* NowPlayingWidget.swift in Sources */ = {isa = PBXBuildFile; fileRef = AB10010000000000000E0001 /* NowPlayingWidget.swift */; };
+ AB10020000000000000E0002 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = AB10010000000000000E0002 /* Assets.xcassets */; };
+ AB10020000000000000E0003 /* NowPlayingWidgetExtension.appex in Embed App Extensions */ = {isa = PBXBuildFile; fileRef = AB10010000000000000E0004 /* NowPlayingWidgetExtension.appex */; settings = {ATTRIBUTES = (RemoveHeadersOnCopy, ); }; };
/* End PBXBuildFile section */
/* Begin PBXContainerItemProxy section */
@@ -27,6 +30,13 @@
remoteGlobalIDString = 97C146ED1CF9000F007C117D;
remoteInfo = Runner;
};
+ AB10060000000000000E0001 /* PBXContainerItemProxy */ = {
+ isa = PBXContainerItemProxy;
+ containerPortal = 97C146E61CF9000F007C117D /* Project object */;
+ proxyType = 1;
+ remoteGlobalIDString = AB10050000000000000E0001;
+ remoteInfo = NowPlayingWidgetExtension;
+ };
/* End PBXContainerItemProxy section */
/* Begin PBXCopyFilesBuildPhase section */
@@ -40,6 +50,17 @@
name = "Embed Frameworks";
runOnlyForDeploymentPostprocessing = 0;
};
+ AB100A0000000000000E0001 /* Embed App Extensions */ = {
+ isa = PBXCopyFilesBuildPhase;
+ buildActionMask = 2147483647;
+ dstPath = "";
+ dstSubfolderSpec = 13;
+ files = (
+ AB10020000000000000E0003 /* NowPlayingWidgetExtension.appex in Embed App Extensions */,
+ );
+ name = "Embed App Extensions";
+ runOnlyForDeploymentPostprocessing = 0;
+ };
/* End PBXCopyFilesBuildPhase section */
/* Begin PBXFileReference section */
@@ -63,6 +84,12 @@
97C146FD1CF9000F007C117D /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = "<group>"; };
97C147001CF9000F007C117D /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = "<group>"; };
97C147021CF9000F007C117D /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
+ AB10010000000000000E0001 /* NowPlayingWidget.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NowPlayingWidget.swift; sourceTree = "<group>"; };
+ AB10010000000000000E0002 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = "<group>"; };
+ AB10010000000000000E0003 /* NowPlayingWidgetExtension.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = NowPlayingWidgetExtension.entitlements; sourceTree = "<group>"; };
+ AB10010000000000000E0004 /* NowPlayingWidgetExtension.appex */ = {isa = PBXFileReference; explicitFileType = "wrapper.app-extension"; includeInIndex = 0; path = NowPlayingWidgetExtension.appex; sourceTree = BUILT_PRODUCTS_DIR; };
+ AB10010000000000000E0005 /* Runner.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = Runner.entitlements; sourceTree = "<group>"; };
+ AB10010000000000000E0006 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
B7990BE5669E13951B2BAD46 /* Pods-Runner.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.release.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.release.xcconfig"; sourceTree = "<group>"; };
DAACD72AEC68ADA3FA213E6C /* Pods_Runner.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_Runner.framework; sourceTree = BUILT_PRODUCTS_DIR; };
E4A191144C46AC47851AEE49 /* Pods-RunnerTests.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-RunnerTests.release.xcconfig"; path = "Target Support Files/Pods-RunnerTests/Pods-RunnerTests.release.xcconfig"; sourceTree = "<group>"; };
@@ -86,6 +113,13 @@
);
runOnlyForDeploymentPostprocessing = 0;
};
+ AB10040000000000000E0002 /* Frameworks */ = {
+ isa = PBXFrameworksBuildPhase;
+ buildActionMask = 2147483647;
+ files = (
+ );
+ runOnlyForDeploymentPostprocessing = 0;
+ };
/* End PBXFrameworksBuildPhase section */
/* Begin PBXGroup section */
@@ -137,6 +171,7 @@
97C146F01CF9000F007C117D /* Runner */,
97C146EF1CF9000F007C117D /* Products */,
331C8082294A63A400263BE5 /* RunnerTests */,
+ AB10030000000000000E0001 /* NowPlayingWidget */,
68DBC8C4DE879C9AB608B650 /* Pods */,
384CE161EB9F7A4FAC01FEA8 /* Frameworks */,
);
@@ -147,6 +182,7 @@
children = (
97C146EE1CF9000F007C117D /* Runner.app */,
331C8081294A63A400263BE5 /* RunnerTests.xctest */,
+ AB10010000000000000E0004 /* NowPlayingWidgetExtension.appex */,
);
name = Products;
sourceTree = "<group>";
@@ -154,6 +190,7 @@
97C146F01CF9000F007C117D /* Runner */ = {
isa = PBXGroup;
children = (
+ AB10010000000000000E0005 /* Runner.entitlements */,
97C146FA1CF9000F007C117D /* Main.storyboard */,
97C146FD1CF9000F007C117D /* Assets.xcassets */,
97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */,
@@ -167,6 +204,17 @@
path = Runner;
sourceTree = "<group>";
};
+ AB10030000000000000E0001 /* NowPlayingWidget */ = {
+ isa = PBXGroup;
+ children = (
+ AB10010000000000000E0001 /* NowPlayingWidget.swift */,
+ AB10010000000000000E0002 /* Assets.xcassets */,
+ AB10010000000000000E0006 /* Info.plist */,
+ AB10010000000000000E0003 /* NowPlayingWidgetExtension.entitlements */,
+ );
+ path = NowPlayingWidget;
+ sourceTree = "<group>";
+ };
/* End PBXGroup section */
/* Begin PBXNativeTarget section */
@@ -202,16 +250,35 @@
3B06AD1E1E4923F5004D2608 /* Thin Binary */,
D8387A83FBC162DF1320F57B /* [CP] Embed Pods Frameworks */,
97B5C8B79FAFA4FE453F7574 /* [CP] Copy Pods Resources */,
+ AB100A0000000000000E0001 /* Embed App Extensions */,
);
buildRules = (
);
dependencies = (
+ AB10070000000000000E0001 /* PBXTargetDependency */,
);
name = Runner;
productName = Runner;
productReference = 97C146EE1CF9000F007C117D /* Runner.app */;
productType = "com.apple.product-type.application";
};
+ AB10050000000000000E0001 /* NowPlayingWidgetExtension */ = {
+ isa = PBXNativeTarget;
+ buildConfigurationList = AB10090000000000000E0001 /* Build configuration list for PBXNativeTarget "NowPlayingWidgetExtension" */;
+ buildPhases = (
+ AB10040000000000000E0001 /* Sources */,
+ AB10040000000000000E0002 /* Frameworks */,
+ AB10040000000000000E0003 /* Resources */,
+ );
+ buildRules = (
+ );
+ dependencies = (
+ );
+ name = NowPlayingWidgetExtension;
+ productName = NowPlayingWidgetExtension;
+ productReference = AB10010000000000000E0004 /* NowPlayingWidgetExtension.appex */;
+ productType = "com.apple.product-type.app-extension";
+ };
/* End PBXNativeTarget section */
/* Begin PBXProject section */
@@ -230,6 +297,9 @@
CreatedOnToolsVersion = 7.3.1;
LastSwiftMigration = 1100;
};
+ AB10050000000000000E0001 = {
+ CreatedOnToolsVersion = 15.0;
+ };
};
};
buildConfigurationList = 97C146E91CF9000F007C117D /* Build configuration list for PBXProject "Runner" */;
@@ -247,6 +317,7 @@
targets = (
97C146ED1CF9000F007C117D /* Runner */,
331C8080294A63A400263BE5 /* RunnerTests */,
+ AB10050000000000000E0001 /* NowPlayingWidgetExtension */,
);
};
/* End PBXProject section */
@@ -270,6 +341,14 @@
);
runOnlyForDeploymentPostprocessing = 0;
};
+ AB10040000000000000E0003 /* Resources */ = {
+ isa = PBXResourcesBuildPhase;
+ buildActionMask = 2147483647;
+ files = (
+ AB10020000000000000E0002 /* Assets.xcassets in Resources */,
+ );
+ runOnlyForDeploymentPostprocessing = 0;
+ };
/* End PBXResourcesBuildPhase section */
/* Begin PBXShellScriptBuildPhase section */
@@ -403,6 +482,14 @@
);
runOnlyForDeploymentPostprocessing = 0;
};
+ AB10040000000000000E0001 /* Sources */ = {
+ isa = PBXSourcesBuildPhase;
+ buildActionMask = 2147483647;
+ files = (
+ AB10020000000000000E0001 /* NowPlayingWidget.swift in Sources */,
+ );
+ runOnlyForDeploymentPostprocessing = 0;
+ };
/* End PBXSourcesBuildPhase section */
/* Begin PBXTargetDependency section */
@@ -411,6 +498,11 @@
target = 97C146ED1CF9000F007C117D /* Runner */;
targetProxy = 331C8085294A63A400263BE5 /* PBXContainerItemProxy */;
};
+ AB10070000000000000E0001 /* PBXTargetDependency */ = {
+ isa = PBXTargetDependency;
+ target = AB10050000000000000E0001 /* NowPlayingWidgetExtension */;
+ targetProxy = AB10060000000000000E0001 /* PBXContainerItemProxy */;
+ };
/* End PBXTargetDependency section */
/* Begin PBXVariantGroup section */
@@ -491,6 +583,7 @@
buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
CLANG_ENABLE_MODULES = YES;
+ CODE_SIGN_ENTITLEMENTS = Runner/Runner.entitlements;
CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)";
DEVELOPMENT_TEAM = 3W9C9PWP64;
ENABLE_BITCODE = NO;
@@ -674,6 +767,7 @@
buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
CLANG_ENABLE_MODULES = YES;
+ CODE_SIGN_ENTITLEMENTS = Runner/Runner.entitlements;
CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)";
DEVELOPMENT_TEAM = 3W9C9PWP64;
ENABLE_BITCODE = NO;
@@ -697,6 +791,7 @@
buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
CLANG_ENABLE_MODULES = YES;
+ CODE_SIGN_ENTITLEMENTS = Runner/Runner.entitlements;
CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)";
DEVELOPMENT_TEAM = 3W9C9PWP64;
ENABLE_BITCODE = NO;
@@ -713,6 +808,95 @@
};
name = Release;
};
+ AB10080000000000000E0001 /* Debug */ = {
+ isa = XCBuildConfiguration;
+ buildSettings = {
+ ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor;
+ ASSETCATALOG_COMPILER_WIDGET_BACKGROUND_COLOR_NAME = WidgetBackground;
+ CODE_SIGN_ENTITLEMENTS = NowPlayingWidget/NowPlayingWidgetExtension.entitlements;
+ CODE_SIGN_STYLE = Automatic;
+ CURRENT_PROJECT_VERSION = 1;
+ DEVELOPMENT_TEAM = 3W9C9PWP64;
+ GENERATE_INFOPLIST_FILE = YES;
+ INFOPLIST_FILE = NowPlayingWidget/Info.plist;
+ INFOPLIST_KEY_CFBundleDisplayName = "Now Playing";
+ INFOPLIST_KEY_NSHumanReadableCopyright = "";
+ IPHONEOS_DEPLOYMENT_TARGET = 17.0;
+ LD_RUNPATH_SEARCH_PATHS = (
+ "$(inherited)",
+ "@executable_path/Frameworks",
+ "@executable_path/../../Frameworks",
+ );
+ MARKETING_VERSION = 1.0;
+ PRODUCT_BUNDLE_IDENTIFIER = com.barnabas.absorb.NowPlayingWidget;
+ PRODUCT_NAME = "$(TARGET_NAME)";
+ SKIP_INSTALL = YES;
+ SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG;
+ SWIFT_EMIT_LOC_STRINGS = YES;
+ SWIFT_OPTIMIZATION_LEVEL = "-Onone";
+ SWIFT_VERSION = 5.0;
+ TARGETED_DEVICE_FAMILY = "1,2";
+ };
+ name = Debug;
+ };
+ AB10080000000000000E0002 /* Release */ = {
+ isa = XCBuildConfiguration;
+ buildSettings = {
+ ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor;
+ ASSETCATALOG_COMPILER_WIDGET_BACKGROUND_COLOR_NAME = WidgetBackground;
+ CODE_SIGN_ENTITLEMENTS = NowPlayingWidget/NowPlayingWidgetExtension.entitlements;
+ CODE_SIGN_STYLE = Automatic;
+ CURRENT_PROJECT_VERSION = 1;
+ DEVELOPMENT_TEAM = 3W9C9PWP64;
+ GENERATE_INFOPLIST_FILE = YES;
+ INFOPLIST_FILE = NowPlayingWidget/Info.plist;
+ INFOPLIST_KEY_CFBundleDisplayName = "Now Playing";
+ INFOPLIST_KEY_NSHumanReadableCopyright = "";
+ IPHONEOS_DEPLOYMENT_TARGET = 17.0;
+ LD_RUNPATH_SEARCH_PATHS = (
+ "$(inherited)",
+ "@executable_path/Frameworks",
+ "@executable_path/../../Frameworks",
+ );
+ MARKETING_VERSION = 1.0;
+ PRODUCT_BUNDLE_IDENTIFIER = com.barnabas.absorb.NowPlayingWidget;
+ PRODUCT_NAME = "$(TARGET_NAME)";
+ SKIP_INSTALL = YES;
+ SWIFT_EMIT_LOC_STRINGS = YES;
+ SWIFT_VERSION = 5.0;
+ TARGETED_DEVICE_FAMILY = "1,2";
+ };
+ name = Release;
+ };
+ AB10080000000000000E0003 /* Profile */ = {
+ isa = XCBuildConfiguration;
+ buildSettings = {
+ ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor;
+ ASSETCATALOG_COMPILER_WIDGET_BACKGROUND_COLOR_NAME = WidgetBackground;
+ CODE_SIGN_ENTITLEMENTS = NowPlayingWidget/NowPlayingWidgetExtension.entitlements;
+ CODE_SIGN_STYLE = Automatic;
+ CURRENT_PROJECT_VERSION = 1;
+ DEVELOPMENT_TEAM = 3W9C9PWP64;
+ GENERATE_INFOPLIST_FILE = YES;
+ INFOPLIST_FILE = NowPlayingWidget/Info.plist;
+ INFOPLIST_KEY_CFBundleDisplayName = "Now Playing";
+ INFOPLIST_KEY_NSHumanReadableCopyright = "";
+ IPHONEOS_DEPLOYMENT_TARGET = 17.0;
+ LD_RUNPATH_SEARCH_PATHS = (
+ "$(inherited)",
+ "@executable_path/Frameworks",
+ "@executable_path/../../Frameworks",
+ );
+ MARKETING_VERSION = 1.0;
+ PRODUCT_BUNDLE_IDENTIFIER = com.barnabas.absorb.NowPlayingWidget;
+ PRODUCT_NAME = "$(TARGET_NAME)";
+ SKIP_INSTALL = YES;
+ SWIFT_EMIT_LOC_STRINGS = YES;
+ SWIFT_VERSION = 5.0;
+ TARGETED_DEVICE_FAMILY = "1,2";
+ };
+ name = Profile;
+ };
/* End XCBuildConfiguration section */
/* Begin XCConfigurationList section */
@@ -746,6 +930,16 @@
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
+ AB10090000000000000E0001 /* Build configuration list for PBXNativeTarget "NowPlayingWidgetExtension" */ = {
+ isa = XCConfigurationList;
+ buildConfigurations = (
+ AB10080000000000000E0001 /* Debug */,
+ AB10080000000000000E0002 /* Release */,
+ AB10080000000000000E0003 /* Profile */,
+ );
+ defaultConfigurationIsVisible = 0;
+ defaultConfigurationName = Release;
+ };
/* End XCConfigurationList section */
};
rootObject = 97C146E61CF9000F007C117D /* Project object */;
diff --git a/ios/Runner/AppDelegate.swift b/ios/Runner/AppDelegate.swift
index 42771fac..35d8e102 100644
--- a/ios/Runner/AppDelegate.swift
+++ b/ios/Runner/AppDelegate.swift
@@ -1,6 +1,7 @@
import Flutter
import UIKit
import AVFoundation
+import MediaPlayer
@main
@objc class AppDelegate: FlutterAppDelegate, FlutterImplicitEngineDelegate {
@@ -24,9 +25,48 @@ import AVFoundation
print("[AppDelegate] Audio session setup failed: \(error)")
}
+ // Listen for Darwin notifications from the widget extension so controls
+ // work without opening the app.
+ registerWidgetNotifications()
+
return super.application(application, didFinishLaunchingWithOptions: launchOptions)
}
+ private func registerWidgetNotifications() {
+ let center = CFNotificationCenterGetDarwinNotifyCenter()
+ let observer = Unmanaged.passUnretained(self).toOpaque()
+
+ let names = [
+ "com.barnabas.absorb.widget.playPause",
+ "com.barnabas.absorb.widget.skipBack",
+ "com.barnabas.absorb.widget.skipForward",
+ ]
+ for name in names {
+ CFNotificationCenterAddObserver(
+ center, observer,
+ { (_, observer, name, _, _) in
+ guard let name = name?.rawValue as String? else { return }
+ DispatchQueue.main.async {
+ let cmd = MPRemoteCommandCenter.shared()
+ switch name {
+ case "com.barnabas.absorb.widget.playPause":
+ cmd.togglePlayPauseCommand.send()
+ case "com.barnabas.absorb.widget.skipBack":
+ cmd.skipBackwardCommand.send()
+ case "com.barnabas.absorb.widget.skipForward":
+ cmd.skipForwardCommand.send()
+ default:
+ break
+ }
+ }
+ },
+ CFNotificationName(name as CFString),
+ nil,
+ .deliverImmediately
+ )
+ }
+ }
+
func didInitializeImplicitFlutterEngine(_ engineBridge: FlutterImplicitEngineBridge) {
GeneratedPluginRegistrant.register(with: engineBridge.pluginRegistry)
@@ -49,6 +89,21 @@ import AVFoundation
}
}
+ let widgetChannel = FlutterMethodChannel(name: "com.absorb.widget",
+ binaryMessenger: controller.binaryMessenger)
+ widgetChannel.setMethodCallHandler { (call, result) in
+ switch call.method {
+ case "getGroupContainerPath":
+ if let url = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "group.com.barnabas.absorb") {
+ result(url.path)
+ } else {
+ result(nil)
+ }
+ default:
+ result(FlutterMethodNotImplemented)
+ }
+ }
+
let eqChannel = FlutterMethodChannel(name: "com.absorb.equalizer",
binaryMessenger: controller.binaryMessenger)
eqChannel.setMethodCallHandler { [weak self] (call, result) in
diff --git a/ios/Runner/Runner.entitlements b/ios/Runner/Runner.entitlements
new file mode 100644
index 00000000..416ca0e8
--- /dev/null
+++ b/ios/Runner/Runner.entitlements
@@ -0,0 +1,10 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0">
+<dict>
+ <key>com.apple.security.application-groups</key>
+ <array>
+ <string>group.com.barnabas.absorb</string>
+ </array>
+</dict>
+</plist>
diff --git a/lib/main.dart b/lib/main.dart
index 5834e05a..c95d9214 100644
--- a/lib/main.dart
+++ b/lib/main.dart
@@ -492,6 +492,8 @@ class _AuthGateState extends State<AuthGate> {
if (Platform.isAndroid) {
// Pre-populate Android Auto browse tree in background.
Future.microtask(() => AndroidAutoService().refresh());
+ }
+ if (Platform.isAndroid || Platform.isIOS) {
// Initialize homescreen widget
await HomeWidgetService().init();
}
diff --git a/lib/services/home_widget_service.dart b/lib/services/home_widget_service.dart
index 630a792b..170069c4 100644
--- a/lib/services/home_widget_service.dart
+++ b/lib/services/home_widget_service.dart
@@ -3,6 +3,7 @@ import 'dart:convert';
import 'dart:io';
import 'package:flutter/foundation.dart';
+import 'package:flutter/services.dart';
import 'package:home_widget/home_widget.dart';
import 'package:http/http.dart' as http;
import 'package:path_provider/path_provider.dart';
@@ -14,6 +15,8 @@ import 'download_service.dart';
const String _androidWidgetName = 'NowPlayingWidget';
const String _androidWidgetCompactName = 'NowPlayingWidgetCompact';
+const String _iOSWidgetName = 'NowPlayingWidget';
+const String _appGroupId = 'group.com.barnabas.absorb';
class HomeWidgetService {
static final HomeWidgetService _instance = HomeWidgetService._();
@@ -27,12 +30,26 @@ class HomeWidgetService {
bool _initialized = false;
bool _updating = false;
StreamSubscription? _clickSub;
+ String? _groupContainerPath;
+
+ static const _widgetChannel = MethodChannel('com.absorb.widget');
/// Call after AudioPlayerService is initialized to start pushing state.
Future<void> init() async {
if (_initialized) return;
_initialized = true;
+ // Set up App Group for iOS widget data sharing.
+ if (Platform.isIOS) {
+ await HomeWidget.setAppGroupId(_appGroupId);
+ try {
+ _groupContainerPath =
+ await _widgetChannel.invokeMethod<String>('getGroupContainerPath');
+ } catch (e) {
+ debugPrint('[HomeWidget] Failed to get group container path: $e');
+ }
+ }
+
final player = AudioPlayerService();
player.addListener(_onPlayerChanged);
@@ -59,8 +76,18 @@ class HomeWidgetService {
void _onWidgetClicked(Uri? uri) {
debugPrint('[HomeWidget] widgetClicked: $uri');
if (uri == null) return;
- if (uri.host == 'widget' && uri.path == '/play_pause') {
- _handlePlayPause();
+ if (uri.host == 'widget') {
+ switch (uri.path) {
+ case '/play_pause':
+ _handlePlayPause();
+ break;
+ case '/skip_back':
+ _handleSkipBack();
+ break;
+ case '/skip_forward':
+ _handleSkipForward();
+ break;
+ }
}
}
@@ -72,12 +99,34 @@ class HomeWidgetService {
/// the current item).
Future<void> resumeLastPlayedIfAvailable() => _handlePlayPause();
+ void _handleSkipBack() {
+ final player = AudioPlayerService();
+ if (!player.hasBook) return;
+ player.skipBackward();
+ }
+
+ void _handleSkipForward() {
+ final player = AudioPlayerService();
+ if (!player.hasBook) return;
+ player.skipForward();
+ }
+
Future<void> _handlePlayPause() async {
final player = AudioPlayerService();
// When there's an active session the widget uses a MediaSession media button
// instead of launching the app, so this path is only hit for cold resume.
- if (player.hasBook) return;
+ if (player.hasBook) {
+ // On iOS, widget links always come through here (no MediaSession shortcut).
+ if (Platform.isIOS) {
+ if (player.isPlaying) {
+ player.pause();
+ } else {
+ player.play();
+ }
+ }
+ return;
+ }
// No active session — cold resume (app stays open for initial setup)
final prefs = await SharedPreferences.getInstance();
@@ -250,8 +299,16 @@ class HomeWidgetService {
_stopProgressTimer();
}
- await HomeWidget.updateWidget(name: _androidWidgetName);
- await HomeWidget.updateWidget(name: _androidWidgetCompactName);
+ await _updateAllWidgets();
+ }
+
+ Future<void> _updateAllWidgets() async {
+ if (Platform.isAndroid) {
+ await HomeWidget.updateWidget(name: _androidWidgetName);
+ await HomeWidget.updateWidget(name: _androidWidgetCompactName);
+ } else if (Platform.isIOS) {
+ await HomeWidget.updateWidget(iOSName: _iOSWidgetName);
+ }
}
Future<void> _updateCoverArt(String itemId) async {
@@ -270,15 +327,11 @@ class HomeWidgetService {
coverPath = await downloadService.getLocalCoverPath(itemId);
}
- // If no local cover, download from server to a temp file.
+ // If no local cover, download from server to a temp/shared file.
if (coverPath == null) {
if (coverUrl != null && coverUrl.isNotEmpty) {
- final cacheDir = await getTemporaryDirectory();
- final widgetCoverDir = Directory('${cacheDir.path}/widget_covers');
- if (!widgetCoverDir.existsSync()) {
- widgetCoverDir.createSync(recursive: true);
- }
- final coverFile = File('${widgetCoverDir.path}/$itemId.jpg');
+ final coverDir = await _getCoverDirectory();
+ final coverFile = File('${coverDir.path}/$itemId.jpg');
final response = await http
.get(Uri.parse(coverUrl))
@@ -288,6 +341,14 @@ class HomeWidgetService {
coverPath = coverFile.path;
}
}
+ } else if (Platform.isIOS && _groupContainerPath != null) {
+ // On iOS, local cover is in the app sandbox - copy to shared container.
+ final sharedDir = await _getCoverDirectory();
+ final sharedFile = File('${sharedDir.path}/$itemId.jpg');
+ if (!sharedFile.existsSync()) {
+ await File(coverPath).copy(sharedFile.path);
+ }
+ coverPath = sharedFile.path;
}
} catch (e) {
debugPrint('[HomeWidget] Cover update failed: $e');
@@ -295,13 +356,27 @@ class HomeWidgetService {
try {
await HomeWidget.saveWidgetData<String?>('widget_cover_path', coverPath);
- await HomeWidget.updateWidget(name: _androidWidgetName);
- await HomeWidget.updateWidget(name: _androidWidgetCompactName);
+ await _updateAllWidgets();
} catch (e) {
debugPrint('[HomeWidget] Cover save failed: $e');
}
}
+ /// Returns the directory for widget cover art.
+ /// On iOS, uses the App Group shared container so the widget extension can
+ /// read the files. On Android, uses the app's temp directory.
+ Future<Directory> _getCoverDirectory() async {
+ if (Platform.isIOS && _groupContainerPath != null) {
+ final dir = Directory('$_groupContainerPath/widget_covers');
+ if (!dir.existsSync()) dir.createSync(recursive: true);
+ return dir;
+ }
+ final cacheDir = await getTemporaryDirectory();
+ final dir = Directory('${cacheDir.path}/widget_covers');
+ if (!dir.existsSync()) dir.createSync(recursive: true);
+ return dir;
+ }
+
void _startProgressTimer() {
if (_progressTimer?.isActive == true) return;
_progressTimer = Timer.periodic(const Duration(seconds: 120), (_) {