[RN] 🪅Deep Link 공유하기

TATA·2024년 9월 14일
0

React-Native

목록 보기
12/12

Deep Link 공식문서

공식문서 보고 기본적인 설정 해주기

🪅 IOS

# 생성
npx uri-scheme add fromnow --ios

🪅 Android

# 생성
npx uri-scheme add fromnow --android

# 기본 경로
fromnow://

# npx uri-scheme open [your deep link] --[ios|android]
npx uri-scheme open "fromnow://profile" --ios

npx uri-scheme open "fromnow://team-setting/8" --android

npx uri-scheme open "fromnow://team-detail/8/123" --android

🪅 deeplinkConfig.ts

/* deeplinkConfig.ts */
import { Linking } from 'react-native';
import { LinkingOptions } from '@react-navigation/native';

export const linking: LinkingOptions<RootStackParamList> = {
  prefixes: ['fromnow://'],
  config: {
    screens: {
      Home: 'home',
      Profile: 'profile',
      Team: 'team/:id',
      TeamCalendar: 'team-calendar/:id',
      TeamSetting: 'team-setting/:id',
      TeamEdit: 'team-edit/:id',
      TeamDetail: 'team-detail/:teamId/:date',
    },
  },
  async getInitialURL() {
    const url = await Linking.getInitialURL();
    if (url != null) return url;
  },
};

type RootStackParamList = {
  Home: string;
  Profile: string;
  Team: { id: string };
  TeamCalendar: { id: string };
  TeamSetting: { id: string };
  TeamEdit: { id: string };
  TeamFriendAdd: { id: string };
  TeamDetail: { teamId: string; date: string };
};
/* App.tsx */
import { linking } from './deeplinkConfig';

<NavigationContainer linking={linking}>
  ...
</NavigationContainer>

Linking.openURL

Linking.openURL("fromnow://profile");

앱 설정 열기

Linking.openSettings();

🗑️ deeplinkConfig 있는지 모르고 만들었던 코드(버림..)

# 프로필 경로
fromnow://Profile
# 팀세팅 경로
fromnow://TeamSetting?id=3256
npx uri-scheme open "fromnow://TeamSetting?id=8" --android

npx uri-scheme open "fromnow://TeamDetail?postId=8&teamId=123" --android
import { Linking } from 'react-native';
import useNavi from '@hooks/useNavi';

...
const { navigation } = useNavi();

const parseQueryParams = (query: string) => {
  const paramsObj = {};
  const paramsArray = query.split('&');
  paramsArray.forEach(param => {
    const [key, value] = param.split('=');
    if (key && value) {
      paramsObj[key] = decodeURIComponent(value);
    }
  });
  return paramsObj;
};

const navigateByDeepLink = (e: { url: string }) => {
  let { url } = e;
  if (!url) return;
  const [path, query] = url.replace(/.*?:\/\//g, '').split('?');
  let paramsObj = {};
  if (query) {
    paramsObj = parseQueryParams(query);
  }
  navigation.navigate(path, paramsObj);
};

useEffect(() => {
  // 앱이 처음 시작됐을 때
  Linking.getInitialURL().then(url => {
    navigateByDeepLink({ url });
  });
  // 이미 앱이 실행중일 때
  const linking = Linking.addEventListener('url', navigateByDeepLink);

  return () => {
    linking.remove();
  };
}, []);
...
profile
🌿 https://www.tatahyeonv.com

0개의 댓글