如何在Expo React Native应用中获取外部分享的视频链接?
Expo React Native 接收外部视频分享URL实现指南
1. 配置应用的分享接收权限
要让应用出现在其他平台的分享列表中,需先在app.json里配置对应平台的清单规则:
安卓配置:
在expo.android.intentFilters中添加接收分享的Intent规则,支持文本和视频类型的分享:"android": { "intentFilters": [ { "action": "android.intent.action.SEND", "data": [ { "mimeType": "text/plain" }, { "mimeType": "video/*" } ], "category": ["android.intent.category.DEFAULT"] } ] }iOS配置:
在expo.ios.infoPlist中添加支持分享的文档类型和查询Scheme:"ios": { "infoPlist": { "LSApplicationQueriesSchemes": ["youtube"], "CFBundleDocumentTypes": [ { "CFBundleTypeName": "Shared Content", "LSHandlerRank": "Alternate", "LSItemContentTypes": ["public.text", "public.video"] } ] } }
2. 代码实现:获取并显示分享的URL
结合Linking和SharingAPI,同时处理应用启动时的初始分享和前台运行时的分享事件:
import { useEffect, useState } from 'react'; import { View, Text, StyleSheet } from 'react-native'; import * as Linking from 'expo-linking'; import * as Sharing from 'expo-sharing'; export default function App() { const [sharedVideoUrl, setSharedVideoUrl] = useState(''); useEffect(() => { // 应用启动时检查是否有待处理的分享内容 const checkInitialContent = async () => { // 优先获取分享的文本(视频URL通常以文本形式传递) const sharedText = await Sharing.getSharedTextAsync(); if (sharedText?.startsWith('http')) { setSharedVideoUrl(sharedText); return; } // 备用:检查通过Linking传递的初始URL const initialUrl = await Linking.getInitialURL(); if (initialUrl?.startsWith('http')) { setSharedVideoUrl(initialUrl); } }; checkInitialContent(); // 监听前台运行时的URL跳转事件 const linkingListener = Linking.addEventListener('url', (event) => { if (event.url.startsWith('http')) { setSharedVideoUrl(event.url); } }); // 监听iOS端的实时分享文本事件 const sharingListener = Sharing.addSharedTextListener(({ text }) => { if (text?.startsWith('http')) { setSharedVideoUrl(text); } }); // 组件卸载时移除监听 return () => { linkingListener.remove(); sharingListener.remove(); }; }, []); return ( <View style={styles.container}> <Text style={styles.title}>分享的视频URL:</Text> <Text style={styles.urlText}>{sharedVideoUrl || '暂无分享内容'}</Text> </View> ); } const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', padding: 20, }, title: { fontSize: 18, marginBottom: 15, }, urlText: { fontSize: 16, color: '#2196F3', textAlign: 'center', }, });
3. 常见问题排查
- 配置修改后,安卓端需重新构建开发客户端(
expo run:android),Expo Go可能无法识别新的Intent规则;iOS端若使用自定义开发客户端,也需重新构建。 - 确保使用最新版Expo SDK,旧版本的
Sharing和LinkingAPI可能存在兼容性问题。 - 部分平台分享视频时,可能同时传递文件和URL,若仅需URL,优先取
Sharing.getSharedTextAsync返回的内容即可。
内容的提问来源于stack exchange,提问作者hand code 2
相关产品推荐
相关产品推荐

