From a5b3dbc00d6b82f1784333968f8e6c7ba4d7a89a Mon Sep 17 00:00:00 2001 From: Tom Brow Date: Wed, 18 Nov 2026 07:17:27 -0800 Subject: [PATCH] fix(mobile): stop reporting saved images as failed on iOS (#9599) On iOS, **Save image** in the image viewer reported a failure for a save that worked. It asks only for permission to add photos. With that permission the image landed in Photos, but the app showed "Could not save image" and iOS then asked for full library access. After choosing **Keep Add Only**, every later save did the same: saved, and reported as failed. Now the save reports what actually happened, and add-only permission is all it needs, so iOS never asks for full access. | Before | After | | --- | --- | | Before: full access prompt over a "Could not save image"
message | After: "Saved to Photos" message | Before: https://github.com/user-attachments/assets/e4f88b29-cabc-4c43-9967-d8481e434551 After: https://github.com/user-attachments/assets/ca3631a5-c988-4082-898a-426867788051 ### Cause `photo_manager`'s `saveImage` returns the saved asset, so its iOS code fetches the new asset back after writing it. PhotoKit does not let an add-only app fetch assets: the fetch makes iOS show the full-access prompt and comes back empty, and the plugin reports an error for a write that succeeded. The latest release (3.12.0) has the same code. On iOS the image is now written by a small native saver (`PhotoLibrarySaver`) that creates the asset and reports the result of that write, without reading the library. Android keeps using `photo_manager`, and the permission request is unchanged on both platforms. ### Regressions None expected. - The write is the same PhotoKit creation request the plugin made, with the same original filename, so saved images are unchanged. - Real failures still show "Could not save image": a denied permission, a failed download and a failed write all still surface. - Android and the rest of the app's photo library use (the composer's photo picker) are untouched. ### Validation - Added test: the image actions journey saves on iOS with a photo library that grants add-only access and rejects every read, and expects "Saved to Photos", one write with the downloaded bytes and filename, and an add-only permission request. A failed write then shows "Could not save image". It fails without the fix. - Full mobile suite and the iOS Runner unit tests pass. - Full-app run on an iOS 27 simulator, on a fresh install with no photo permission, comparing this branch with unmodified `main`: - `main`: first save adds the image, shows "Could not save image" and the full-access prompt; a second save after **Keep Add Only** adds another copy and shows the error again. - This branch: first and second saves each add one image and show "Saved to Photos", with no full-access prompt, and only add permission is granted afterwards. - This branch, other paths: **Don't Allow** shows "Could not save image" and saves nothing; saving with full access already granted works; **Share image** still opens the share sheet. - Not covered: a physical device, and Android (its code path is unchanged). --------- Signed-off-by: Tom Brow Co-authored-by: judge <7615ec4b7ddf99f0bb48e913297f99f8f772d289a1c9ef54e1d906dd55a93ba8@buzz.block.builderlab.xyz> --- mobile/ios/Runner.xcodeproj/project.pbxproj | 4 + mobile/ios/Runner/AppDelegate.swift | 2 + mobile/ios/Runner/PhotoLibrarySaver.swift | 43 ++++++++++ .../features/channels/message_actions.dart | 14 +++- .../channels/message_actions_test.dart | 81 +++++++++++++++++++ 5 files changed, 143 insertions(+), 1 deletion(-) create mode 100644 mobile/ios/Runner/PhotoLibrarySaver.swift diff --git a/mobile/ios/Runner.xcodeproj/project.pbxproj b/mobile/ios/Runner.xcodeproj/project.pbxproj index 54f7e73189..e193686465 100644 --- a/mobile/ios/Runner.xcodeproj/project.pbxproj +++ b/mobile/ios/Runner.xcodeproj/project.pbxproj @@ -12,6 +12,7 @@ BC0010000000000000000001 /* BuzzBrowserAuthBridge.swift in Sources */ = {isa = PBXBuildFile; fileRef = BC0010000000000000000002 /* BuzzBrowserAuthBridge.swift */; }; F84380010000000000000001 /* ProfileSetupRecoveryTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = F84380010000000000000002 /* ProfileSetupRecoveryTests.swift */; }; BBAA00000000000000000011 /* IdentityFilePlugin.swift in Sources */ = {isa = PBXBuildFile; fileRef = BBAA00000000000000000012 /* IdentityFilePlugin.swift */; }; + BBAA00000000000000000021 /* PhotoLibrarySaver.swift in Sources */ = {isa = PBXBuildFile; fileRef = BBAA00000000000000000022 /* PhotoLibrarySaver.swift */; }; BBAA00000000000000000001 /* HostedHpkeBackup.swift in Sources */ = {isa = PBXBuildFile; fileRef = BBAA00000000000000000002 /* HostedHpkeBackup.swift */; }; DAAB00000000000000000001 /* NativeTabler.swift in Sources */ = {isa = PBXBuildFile; fileRef = DAAB00000000000000000002; }; DAAC00000000000000000001 /* HomeScreenShortcuts.swift in Sources */ = {isa = PBXBuildFile; fileRef = DAAC00000000000000000002 /* HomeScreenShortcuts.swift */; }; @@ -115,6 +116,7 @@ BC0010000000000000000002 /* BuzzBrowserAuthBridge.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BuzzBrowserAuthBridge.swift; sourceTree = ""; }; F84380010000000000000002 /* ProfileSetupRecoveryTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ProfileSetupRecoveryTests.swift; sourceTree = ""; }; BBAA00000000000000000012 /* IdentityFilePlugin.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = IdentityFilePlugin.swift; sourceTree = ""; }; + BBAA00000000000000000022 /* PhotoLibrarySaver.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PhotoLibrarySaver.swift; sourceTree = ""; }; BBAA00000000000000000002 /* HostedHpkeBackup.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HostedHpkeBackup.swift; sourceTree = ""; }; DAAC00000000000000000002 /* HomeScreenShortcuts.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HomeScreenShortcuts.swift; sourceTree = ""; }; 5AAE00000000000000000002 /* ShareSuggestions.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ShareSuggestions.swift; sourceTree = ""; }; @@ -311,6 +313,7 @@ BC0010000000000000000002 /* BuzzBrowserAuthBridge.swift */, BBAA00000000000000000002 /* HostedHpkeBackup.swift */, BBAA00000000000000000012 /* IdentityFilePlugin.swift */, + BBAA00000000000000000022 /* PhotoLibrarySaver.swift */, BZZ00000000000000000024 /* PushNativeState.swift */, BZZ00000000000000000027 /* PushEndpointGrantStore.swift */, BZZ0000000000000000002A /* PushSnapshotBridge.swift */, @@ -666,6 +669,7 @@ BC0010000000000000000001 /* BuzzBrowserAuthBridge.swift in Sources */, BBAA00000000000000000001 /* HostedHpkeBackup.swift in Sources */, BBAA00000000000000000011 /* IdentityFilePlugin.swift in Sources */, + BBAA00000000000000000021 /* PhotoLibrarySaver.swift in Sources */, BZZ00000000000000000023 /* PushNativeState.swift in Sources */, BZZ00000000000000000026 /* PushEndpointGrantStore.swift in Sources */, BZZ00000000000000000029 /* PushSnapshotBridge.swift in Sources */, diff --git a/mobile/ios/Runner/AppDelegate.swift b/mobile/ios/Runner/AppDelegate.swift index 332d65a482..edbff6547e 100644 --- a/mobile/ios/Runner/AppDelegate.swift +++ b/mobile/ios/Runner/AppDelegate.swift @@ -55,6 +55,7 @@ import os.log private var nativeCommunityEntryCoordinator: NativeCommunityEntryCoordinator? private var nativeProfileTextEditorCoordinator: NativeProfileTextEditorCoordinator? private var identityFilePlugin: IdentityFilePlugin? + private var photoLibrarySaver: PhotoLibrarySaver? private var hostedHpkeChannel: FlutterMethodChannel? private var browserAuthBridge: BuzzBrowserAuthBridge? private var huddleMediaPlugin: HuddleMediaPlugin? @@ -93,6 +94,7 @@ import os.log } } identityFilePlugin = IdentityFilePlugin(messenger: messenger) + photoLibrarySaver = PhotoLibrarySaver(messenger: messenger) HomeScreenShortcuts.shared.attach(messenger: messenger) shareSuggestions = ShareSuggestions { [weak self] in self?.appGroupIdentifier.flatMap { diff --git a/mobile/ios/Runner/PhotoLibrarySaver.swift b/mobile/ios/Runner/PhotoLibrarySaver.swift new file mode 100644 index 0000000000..8b00e00cf1 --- /dev/null +++ b/mobile/ios/Runner/PhotoLibrarySaver.swift @@ -0,0 +1,43 @@ +import Flutter +import Photos + +/// Adds an image to Photos with add-only access. +/// +/// PhotoKit lets an add-only app create an asset but never fetch one, so this +/// reports the result of the write itself and never reads the new asset back. +final class PhotoLibrarySaver { + private let channel: FlutterMethodChannel + + init(messenger: FlutterBinaryMessenger) { + channel = FlutterMethodChannel(name: "buzz/photo_library_saver", binaryMessenger: messenger) + channel.setMethodCallHandler { call, result in + guard call.method == "saveImage" else { + result(FlutterMethodNotImplemented) + return + } + guard let arguments = call.arguments as? [String: Any], + let bytes = arguments["bytes"] as? FlutterStandardTypedData, + let filename = arguments["filename"] as? String + else { + result(FlutterError(code: "invalid_arguments", message: nil, details: nil)) + return + } + PHPhotoLibrary.shared().performChanges { + let options = PHAssetResourceCreationOptions() + options.originalFilename = filename + PHAssetCreationRequest.forAsset().addResource( + with: .photo, data: bytes.data, options: options) + } completionHandler: { saved, error in + DispatchQueue.main.async { + if saved { + result(nil) + } else { + result( + FlutterError( + code: "save_failed", message: error?.localizedDescription, details: nil)) + } + } + } + } + } +} diff --git a/mobile/lib/features/channels/message_actions.dart b/mobile/lib/features/channels/message_actions.dart index 36535b5ffb..0755bc0394 100644 --- a/mobile/lib/features/channels/message_actions.dart +++ b/mobile/lib/features/channels/message_actions.dart @@ -403,6 +403,8 @@ String downloadedImageFilename(String imageUrl, String? contentType) { return 'buzz-${DateTime.now().millisecondsSinceEpoch}$extension'; } +const _photoLibrarySaver = MethodChannel('buzz/photo_library_saver'); + Future _saveImageToPhotos(WidgetRef ref, String imageUrl) async { final needsPhotoLibraryPermission = defaultTargetPlatform == TargetPlatform.iOS || @@ -424,7 +426,17 @@ Future _saveImageToPhotos(WidgetRef ref, String imageUrl) async { } } final image = await _downloadImage(ref, imageUrl); - await PhotoManager.editor.saveImage(image.bytes, filename: image.filename); + if (defaultTargetPlatform == TargetPlatform.iOS) { + // photo_manager reads the new asset back after writing it. Add-only access + // forbids that read, so iOS asks for full access and a completed save is + // reported as a failure. The native saver only writes. + await _photoLibrarySaver.invokeMethod('saveImage', { + 'bytes': image.bytes, + 'filename': image.filename, + }); + } else { + await PhotoManager.editor.saveImage(image.bytes, filename: image.filename); + } } Future _saveImage( diff --git a/mobile/test/features/channels/message_actions_test.dart b/mobile/test/features/channels/message_actions_test.dart index af1b4e1105..2c99a656be 100644 --- a/mobile/test/features/channels/message_actions_test.dart +++ b/mobile/test/features/channels/message_actions_test.dart @@ -18,7 +18,10 @@ import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:hooks_riverpod/hooks_riverpod.dart'; +import 'package:http/http.dart' as http; +import 'package:http/testing.dart'; import 'package:nostr/nostr.dart' as nostr; +import 'package:photo_manager/photo_manager.dart'; import 'package:shared_preferences/shared_preferences.dart'; import '../../helpers/thread_ids.dart'; @@ -230,9 +233,14 @@ Future _pumpImageSheet( WidgetTester tester, { required TimelineMessage message, bool canManageMessage = false, + http.Client? mediaClient, }) async { await tester.pumpWidget( ProviderScope( + overrides: [ + if (mediaClient != null) + mediaHttpClientProvider.overrideWithValue(mediaClient), + ], child: MaterialApp( theme: AppTheme.light(), home: Scaffold( @@ -1205,6 +1213,79 @@ void main() { findsNWidgets(4), ); }); + + testWidgets('saving on iOS reports the result of the add-only write', ( + tester, + ) async { + debugDefaultTargetPlatformOverride = TargetPlatform.iOS; + try { + final messenger = + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger; + final permissionRequests = []; + // Only the permission request is answered: add-only access cannot read + // the library, so any other photo_manager call fails as it would there. + const photoManager = MethodChannel('com.fluttercandies/photo_manager'); + const saver = MethodChannel('buzz/photo_library_saver'); + addTearDown(() { + messenger.setMockMethodCallHandler(photoManager, null); + messenger.setMockMethodCallHandler(saver, null); + }); + messenger.setMockMethodCallHandler(photoManager, (call) async { + if (call.method != 'requestPermissionExtend') { + throw PlatformException(code: 'add_only_cannot_read'); + } + permissionRequests.add(call.arguments); + return PermissionState.authorized.index; + }); + final saves = >[]; + PlatformException? saveFailure; + messenger.setMockMethodCallHandler(saver, (call) async { + expect(call.method, 'saveImage'); + saves.add(call.arguments as Map); + if (saveFailure case final failure?) throw failure; + return null; + }); + + await _pumpImageSheet( + tester, + message: _message(), + mediaClient: MockClient( + (_) async => http.Response.bytes( + [1, 2, 3], + 200, + headers: {'content-type': 'image/png'}, + ), + ), + ); + await tester.tap(find.text('Save image')); + await tester.pumpAndSettle(); + + expect(find.text('Saved to Photos'), findsOneWidget); + expect(saves.single, { + 'bytes': Uint8List.fromList([1, 2, 3]), + 'filename': 'photo.png', + }); + expect( + (permissionRequests.single + as Map)['iosAccessLevel'], + IosAccessLevel.addOnly.index + 1, + ); + + saveFailure = PlatformException(code: 'save_failed'); + tester + .state(find.byType(ScaffoldMessenger)) + .removeCurrentSnackBar(); + await tester.tap(find.text('open image actions')); + await tester.pumpAndSettle(); + await tester.tap(find.text('Save image')); + await tester.pumpAndSettle(); + + expect(find.text('Could not save image'), findsOneWidget); + expect(saves, hasLength(2)); + } finally { + debugDefaultTargetPlatformOverride = null; + } + }); }); testWidgets('image sheet omits message deletion without permission', (