···114114 // as the starting image, or put it directly into the album
115115 const album = await MediaLibrary.getAlbumAsync(ALBUM_NAME)
116116 if (album) {
117117- // if album exists, put the image straight in there
118118- await MediaLibrary.createAssetAsync(imagePath, album)
117117+ // try and migrate if needed
118118+ try {
119119+ if (await MediaLibrary.albumNeedsMigrationAsync(album)) {
120120+ await MediaLibrary.migrateAlbumIfNeededAsync(album)
121121+ }
122122+ } catch (err) {
123123+ logger.info('Attempted and failed to migrate album', {
124124+ safeMessage: err,
125125+ })
126126+ }
127127+128128+ try {
129129+ // if album exists, put the image straight in there
130130+ await MediaLibrary.createAssetAsync(imagePath, album)
131131+ } catch (err) {
132132+ logger.info('Failed to create asset', {safeMessage: err})
133133+ // however, it's possible that we don't have write permission to the album
134134+ // try making a new one!
135135+ try {
136136+ await MediaLibrary.createAlbumAsync(
137137+ ALBUM_NAME,
138138+ undefined,
139139+ undefined,
140140+ imagePath,
141141+ )
142142+ } catch (err2) {
143143+ logger.info('Failed to create asset in a fresh album', {
144144+ safeMessage: err2,
145145+ })
146146+ // ... and if all else fails, just put it in DCIM
147147+ await MediaLibrary.createAssetAsync(imagePath)
148148+ }
149149+ }
119150 } else {
120151 // otherwise, create album with asset (albums must always have at least one asset)
121152 await MediaLibrary.createAlbumAsync(
···132163 logger.error(err instanceof Error ? err : String(err), {
133164 message: 'Failed to save image to media library',
134165 })
166166+ throw err
135167 } finally {
136168 safeDeleteAsync(imagePath)
137169 }