This documentation is available as Markdown for AI agents and LLMs. See the full Markdown index or append .md to any documentation URL.
Expo 媒体库(旧版)
提供对设备媒体库的访问的库。
重要 MediaLibrary API 的传统版本包含在
expo-media-library库中。它可以与基于类的expo-media-libraryAPI 一起使用,后者从根导入中导出。要使用传统 API,请从expo-media-library/legacy导入它。
expo-media-library 提供对用户媒体库的访问权限,允许他们从你的应用中访问现有的图片和视频,并保存新的媒体内容。你还可以订阅用户媒体库的任何更新。
警告 Android 仅允许需要广泛访问照片的应用完全访问媒体库(这是此软件包的目的)。请参阅Google Play 照片和视频权限政策详情。
安装
🌐 Installation
If you are installing this in an existing React Native app, make sure to install expo in your project.
应用配置中的配置
🌐 Configuration in app config
如果你在项目中使用配置插件(连续原生生成 (CNG)),可以使用其内置的 配置插件 来配置 expo-media-library。该插件允许你配置无法在运行时设置并且需要构建新的应用二进制文件才能生效的各种属性。如果你的应用不使用 CNG,则需要手动配置该库。
🌐 You can configure expo-media-library using its built-in config plugin if you use config plugins in your project (Continuous Native Generation (CNG)). The plugin allows you to configure various properties that cannot be set at runtime and require building a new app binary to take effect. If your app does not use CNG, then you'll need to manually configure the library.
Example app.json with config plugin
{ "expo": { "plugins": [ [ "expo-media-library", { "photosPermission": "Allow $(PRODUCT_NAME) to access your photos.", "savePhotosPermission": "Allow $(PRODUCT_NAME) to save photos.", "isAccessMediaLocationEnabled": true, "granularPermissions": ["audio", "photo"] } ] ] } }
Configurable properties
Are you using this library in an existing React Native app?
如果你没有使用连续原生生成(CNG),或者你是手动使用原生 android 和 ios 项目,那么你需要在你的原生项目中添加以下权限和配置:
🌐 If you're not using Continuous Native Generation (CNG) or you're using native android and ios projects manually, then you need to add following permissions and configuration to your native projects:
安卓
-
要访问资源位置(纬度和经度 EXIF 标签),请在项目的 android/app/src/main/AndroidManifest.xml 中添加
ACCESS_MEDIA_LOCATION权限:<uses-permission android:name="android.permission.ACCESS_MEDIA_LOCATION" /> -
Scoped storage 从 Android 10 开始可用。要使
expo-media-library能与 Scoped Storage 一起使用,你需要将以下配置添加到你的 android/app/src/main/AndroidManifest.xml 中:<manifest ... > <application android:requestLegacyExternalStorage="true" ...> </manifest>
iOS
-
将
NSPhotoLibraryUsageDescription和NSPhotoLibraryAddUsageDescription键添加到你项目的 ios/[app]/Info.plist 文件中:<key>NSPhotoLibraryUsageDescription</key> <string>Give $(PRODUCT_NAME) permission to access your photos</string> <key>NSPhotoLibraryAddUsageDescription</key> <string>Give $(PRODUCT_NAME) permission to save photos</string>
用法
🌐 Usage
已知的限制
🌐 Known limitations
清空相册
🌐 Empty albums
由于 Android 系统的限制,不可能创建空相册。必须传入一个现有的资源以添加到相册,或传入本地资源的 URI,这将用于在相册中创建一个新的资源。
🌐 Due to system limitations on Android, it is impossible to create empty albums. It is necessary to either pass an existing asset to add to the album or a URI of a local resource, which will be used to create a new asset inside the album.
在相册之间移动资源
🌐 Moving assets between albums
Android 11 引入了权限更改,使在相册之间移动资源的操作每次都需要用户确认。因此,在创建新资源时,建议在调用 createAssetAsync 方法时传入 album 参数,而不是先创建资源再将其移动到相册,这样可以自动将资源添加到相册,而无需用户确认。
🌐 Android 11 introduced permission changes that make the operation of moving assets between albums require confirmation from the user every time.
Therefore, when creating a new asset, instead of creating the asset and then moving it to the album, it is recommended to pass the album parameter to the createAssetAsync method, which will automatically add the asset to the album without the need for user confirmation.
图片方向错误
🌐 Wrong orientation of images
在 Android 上,如果使用 getAssetsAsync 而不使用 resolveWithFullInfo: true,图片方向可能会不正确,因为只有在启用该选项时才会读取包含方向信息的 EXIF 数据。
🌐 On Android, when using getAssetsAsync without resolveWithFullInfo: true, image orientation may be incorrect because EXIF data (which includes orientation) is only read when that option is enabled.
应用接口
🌐 API
import * as MediaLibrary from 'expo-media-library/legacy';
Component
Type: React.Element<AlbumsOptions>
Queries for user-created albums in media gallery.
Constants
Type: SortByObject
Supported keys that can be used to sort getAssetsAsync results.
Hooks
Check or request permissions to access the media library.
This uses both requestPermissionsAsync and getPermissionsAsync to interact with the permissions.
[PermissionResponse | null, RequestPermissionMethod<PermissionResponse>, GetPermissionMethod<PermissionResponse>]Example
const [permissionResponse, requestPermission] = MediaLibrary.usePermissions();
Methods
Adds array of assets to the album.
On Android, by default it copies assets from the current album to provided one, however it's also
possible to move them by passing false as copyAssets argument. In case they're copied you
should keep in mind that getAssetsAsync will return duplicated assets.
Promise<boolean>Returns promise which fulfils with true if the assets were successfully added to
the album.
Checks if the album should be migrated to a different location. In other words, it checks if the
application has the write permission to the album folder. If not, it returns true, otherwise false.
Note: For Android below R, web or iOS, this function always returns
false.
Promise<boolean>Returns a promise which fulfils with true if the album should be migrated.
Creates an album with given name and initial asset. The asset parameter is required on Android,
since it's not possible to create empty album on this platform. On Android, by default it copies
given asset from the current album to the new one, however it's also possible to move it by
passing false as copyAsset argument.
In case it's copied you should keep in mind that getAssetsAsync will return duplicated asset.
On Android, it's not possible to create an empty album. You must provide an existing asset to copy or move into the album or an uri of a local file, which will be used to create an initial asset for the album.
Newly created Album.
Creates an asset from existing file. The most common use case is to save a picture taken by Camera.
This method requires CAMERA_ROLL permission.
A promise which fulfils with an object representing an Asset.
Example
const { uri } = await Camera.takePictureAsync(); const asset = await MediaLibrary.createAssetAsync(uri);
Deletes given albums from the library. On Android by default it deletes assets belonging to given
albums from the library. On iOS it doesn't delete these assets, however it's possible to do by
passing true as deleteAssets.
Promise<boolean>Returns a promise which fulfils with true if the albums were successfully deleted from
the library.
Deletes assets from the library. On iOS it deletes assets from all albums they belong to, while on Android it keeps all copies of them (album is strictly connected to the asset). Also, there is additional dialog on iOS that requires user to confirm this action.
Promise<boolean>Returns promise which fulfils with true if the assets were successfully deleted.
Returns the content:// URI for the given legacy asset. Use this when migrating to the new
class-based API — pass the returned URI as the ID to new Asset(id).
Promise<string>A promise which fulfils with the content:// URI string for the asset.
Provides more information about an asset, including GPS location, local URI and EXIF metadata.
For better performance, prefer using individual getters such as asset.getLocation() or asset.getExif() to fetch only the data you need.
An AssetInfo object, which is an Asset extended by an additional fields.
Checks user's permissions for accessing media library.
Promise<PermissionResponse>A promise that fulfils with PermissionResponse object.
Returns whether the Media Library API is enabled on the current device.
Promise<boolean>A promise which fulfils with a boolean, indicating whether the Media Library API is
available on the current device.
Moves album content to the special media directories on Android R or above if needed.
Those new locations are in line with the Android scoped storage - so your application won't
lose write permission to those directories in future.
This method does nothing if:
- app is running on iOS, web or Android below R
- app has write permission to the album folder
The migration is possible when the album contains only compatible files types.
For instance, movies and pictures are compatible with each other, but music and pictures are not.
If automatic migration isn't possible, the function rejects.
In that case, you can use methods from the expo-file-system to migrate all your files manually.
Why do you need to migrate files?
Android R introduced a lot of changes in storage system. Now applications can't save
anything to the root directory. The only available locations are from the MediaStore API.
Unfortunately, the media library stored albums in folders for which, because of those changes,
the application doesn't have permissions anymore. However, it doesn't mean you need to migrate
all your albums. If your application doesn't add assets to albums, you don't have to migrate.
Everything will work as it used to. You can read more about scoped storage in the Android documentation.
Promise<void>A promise which fulfils to void.
Allows the user to update the assets that your app has access to.
The system modal is only displayed if the user originally allowed only limited access to their
media library, otherwise this method is a no-op.
Promise<void>A promise that either rejects if the method is unavailable, or resolves to void.
Note: This method doesn't inform you if the user changes which assets your app has access to. That information is only exposed by iOS, and to obtain it, you need to subscribe for updates to the user's media library using
addListener(). IfhasIncrementalChangesisfalse, the user changed their permissions.
Removes given assets from album.
On Android, album will be automatically deleted if there are no more assets inside.
Promise<boolean>Returns promise which fulfils with true if the assets were successfully removed from
the album.
Asks the user to grant permissions for accessing media in user's media library.
Promise<PermissionResponse>A promise that fulfils with PermissionResponse object.
Saves the file at given localUri to the user's media library. Unlike createAssetAsync(),
This method doesn't return created asset.
On iOS 11+, it's possible to use this method without asking for CAMERA_ROLL permission,
however then yours Info.plist should have NSPhotoLibraryAddUsageDescription key.
Promise<void>On iOS, this adds or removes the asset from the system "Favorites" smart album.
Promise<boolean>Returns a promise which fulfils with true if the operation was successful.
Event subscriptions
Subscribes for updates in user's media library.
EventSubscriptionAn Subscription object that you can call remove() on when you would
like to unsubscribe the listener.
Interfaces
A subscription object that allows to conveniently remove an event listener from the emitter.
Types
Literal type: string
Determines the type of media that the app will ask the OS to get access to.
Acceptable values are: 'audio' | 'photo' | 'video'
Literal type: string
Constants identifying specific variations of asset media, such as panorama or screenshot photos,
and time-lapse or high-frame-rate video. Maps to PHAssetMediaSubtype.
Acceptable values are: 'depthEffect' | 'hdr' | 'highFrameRate' | 'livePhoto' | 'panorama' | 'screenshot' | 'stream' | 'timelapse' | 'spatialMedia' | 'videoCinematic'
Literal type: string
Represents the possible types of media that the app will ask the OS to get access to when calling presentPermissionsPickerAsync().
Acceptable values are: 'photo' | 'video'
Literal type: string
Acceptable values are: 'audio' | 'photo' | 'video' | 'unknown' | 'pairedVideo'
Literal type: union
Permission expiration time. Currently, all permissions are granted permanently.
Acceptable values are: 'never' | number
Literal type: union
Acceptable values are: PermissionHookBehavior | Options
Literal type: string
Acceptable values are: 'default' | 'mediaType' | 'width' | 'height' | 'creationTime' | 'modificationTime' | 'duration'
Enums
权限
🌐 Permissions
安卓
🌐 Android
通过此库的 AndroidManifest.xml 会自动添加以下权限:
🌐 The following permissions are added automatically through this library's AndroidManifest.xml:
iOS
该库使用以下用法描述键:
🌐 The following usage description keys are used by this library: