본문 바로가기
플러터

앱링크를 이용해 카카오톡 초대하기, 공유하기 기능

by s2jinny 2024. 10. 15.

이런 화면과 같이 카카오톡 공유하기, 초대장 만들기 기능을 만들기 위해서 가장 많이 쓰이는 파이어베이스의 다이나믹링크를 사용한다.  

하지만 파베 다이나믹링크가 25년 8월 종료 된다는 점 ...!! 예전에 메리미 어플(초대장을 보내서 일정 공유 캘린더 어플) 만들 때 파이어베이스 다이나믹링크를 활용했었는데, 종료 되니까 이번엔 앱 링크를 활용해 만들어 보겠따 !! 

일단, 앱 링크 와 딥 링크 차이점 : 

앱링크는 URL을 사용하고, 딥링크는 URI를 사용한다. 뭔 차이? URI는 리소스를 식별하는 데 사용되고, URL은 리소스의 위치를 나타내는 데 사용된다. 딥링크는 앱이 설치되어 있지 않은 경우에도 작동할 수 있지만, 앱링크는 앱이 설치되어 있지 않은 경우 웹 페이지로 이동한다.

지금부터 앱링크를 셋팅하겠다. 

앱링크는 HTTP 또는 HTTPS 기반의 링크를 사용하며 일종의 딥링크이다. 보안과 검증을 위해 앱과 연결된 웹 도메인이 필요하다. github.io를 활용하여 개인 웹 도메인을 셋팅한다. 

- https://pages.github.com/ 셋팅은 이걸로 하슈~~ 

 

0000github.io/.well-known/assetlinks.json 

을 클릭했을 때 404에러만 아니면 됨. 

            <intent-filter android:autoVerify="true">
                <action android:name="android.intent.action.VIEW" />

                <category android:name="android.intent.category.DEFAULT" />
                <category android:name="android.intent.category.BROWSABLE" />

                <data android:scheme="inklink" />
            </intent-filter>

            <intent-filter android:autoVerify="true">
                <action android:name="android.intent.action.VIEW" />

                <category android:name="android.intent.category.DEFAULT" />
                <category android:name="android.intent.category.BROWSABLE" />

                <data android:scheme="http" />
                <data android:scheme="https" />
                <data android:host="본안의 웹사이트.github.io" />

 

여기서 본인의 웹사이트. github.io를 추가하고 앱링크의 스키마도 추가한다! 

 

info.plist 에는     <string>kakaolink</string> 추가 해주고, 

 

xcode => info => URL Type 추가해서 Url Schemes 를 추가해줍니다 ! 저는 inklink로 추가했어요.

ios 는 이거만 추가해준 듯.

 

코드는 카카오톡이 설치되어있는지 확인하고, 카카오톡 저 텍스트,사진, 버튼이 있는 피드를 설정해줍니다. 

if (isKakaoTalkSharingAvailable) {
        try {
          Uri uri =
              await ShareClient.instance.shareDefault(template: feedTemplate);
          await ShareClient.instance.launchKakaoTalk(uri);
          print('카카오톡 공유 완료');
        } catch (error) {
          print('카카오톡 공유 실패: $error');
        }
      }
    }
FeedTemplate toDefaultFeed(String imagePath) {
    return FeedTemplate(
      content: Content(
        title: '츄즈미',
        description: '다양한 얼룩이를 만나보세요!',
        imageUrl: Uri.parse(
            'https://inklink-bucke(...)4_%ED%91%9C%EC%A7%802.png'),
        link: Link(
          webUrl: Uri.parse('https://developers.kakao.com'),
          mobileWebUrl: Uri.parse('https://developers.kakao.com'),
        ),
      ),
      buttons: [
        Button(
          title: '더 많은 얼룩이 보러가기',
          link: Link(
            webUrl: Uri.parse('https://developers.kakao.com'),
            mobileWebUrl: Uri.parse('https://developers.kakao.com'),
          ),
        ),
      ],
    );

이런식으로 저 사진처럼 피드가 나옵니다!! 


전 이 피드를 클릭해도 아무 반응 없는 형식이었어요...

삼일 간 모든 코드 동원해서 찾아낸 것이 github.io에서 작동을 하게 만들어야했어요.... 

따라서 그 안에서 

<!DOCTYPE html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>App Link Redirect</title>
    <script>
        function getDeviceType() {
            const userAgent = navigator.userAgent;
            if (/android/i.test(userAgent)) {
                return 'android';
            } else if (/iphone|ipad|ipod/i.test(userAgent)) {
                return 'ios';
            } else {
                return 'unknown';
            }
        }

        function redirectToStore() {
            const androidPackageName = 'android예시';
            const androidStoreLink = 'https://play.google.com/store/apps/details?id=' + androidPackageName;
            const iosAppStoreLink = 'https://apps.apple.com/app/앱 ID예시';
            const appUrlScheme = '예시'; 
            const deviceType = getDeviceType();
            let storeRedirectTimeout;

            // 앱 설치 확인을 위해 URL 스킴으로 리다이렉트 시도
            window.location.href = appUrlScheme;

            storeRedirectTimeout = setTimeout(() => {
                if (deviceType === 'android') {
                    window.location.href = androidStoreLink;
                } else if (deviceType === 'ios') {
                    window.location.href = iosAppStoreLink;
                }
            }, 1500); 
            window.addEventListener('visibilitychange', function() {
                if (document.hidden) {
                    clearTimeout(storeRedirectTimeout);
                }
            });
        }
    </script>
</head>
<body onload="redirectToStore()">
    <h1>Redirecting...</h1>
</body>
</html>

 

android, ios 이동 동작과 앱링크 동작하게

요롷게 해야 작동이 아주아주 잘 됩니다  ♡ ..^^.. ♡ 

파베의 다이나믹링크를 이용한 예시도 많고, 저도 다이나믹링크는 경험해본 적 있는데 앱 링크로 하는 블로그나 자료는 얼마 없더라구요 ..... 삼일동안 아주 밤새서 고생햇는데 성공해서 행복해요. 

앱링크로 카카오 공유 열심히 하세요