목차
React Native의 딥링킹과 유니버설링크 마스터하기: OpenGraph Share & Node.js 통합
웹 프론트엔드 JS 튜토리얼 React Native의 딥링킹과 유니버설링크 마스터하기: OpenGraph Share & Node.js 통합

React Native의 딥링킹과 유니버설링크 마스터하기: OpenGraph Share & Node.js 통합

Sep 01, 2024 pm 09:05 PM

Scenario

Imagine you have an eCommerce app named ShopEasy, and you want users who click on product links in emails, messages, or social media to be redirected directly to the relevant product page in the app, instead of the website.


Step 1: Opengraph Configuration in nodejs server for link preview:

Mastering Deep Linking and Universal Links in React Native: OpenGraph Share & Node.js Integration

Open Graph is a protocol used by web developers to control how URLs are represented when shared on social media platforms like Facebook, Twitter, LinkedIn, and others. By using Open Graph tags in the HTML of a webpage, you can dictate what content will be shown in the preview when a user shares the link.

To use these OpenGraph tags in a React Native app, you would handle the links to your server (such as https://ShopEasy.com/${type}/${id}) using deep linking or universal links. When users share these links, platforms like Facebook, Twitter, or iMessage will automatically display the content preview based on the OpenGraph tags you've defined.

/routes/share.js

const express = require('express');
const app = express();
const path = require('path');

// Serve static files (e.g., images, CSS, JavaScript)
app.use(express.static(path.join(__dirname, 'public')));

// Route to serve the OpenGraph meta tags
app.get('/:type/:id', (req, res) => { // type: product/category
    const productId = req.params.id;

    // Fetch product details from a database or API (placeholder data for this example)
    const product = {
        id: productId,
        name: 'Sample Product',
        description: "'This is a sample product description.',"
        imageUrl: 'https://ShopEasy.com/images/sample-product.jpg',
        price: '$19.99',
    };

    // Serve HTML with OpenGraph meta tags
    res.send(`
        
        
        
            <meta charset="UTF-8">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <title>React Native의 딥링킹과 유니버설링크 마스터하기: OpenGraph Share & Node.js 통합</title>

            <!-- OpenGraph Meta Tags -->
            <meta property="og:title" content="React Native의 딥링킹과 유니버설링크 마스터하기: OpenGraph Share & Node.js 통합">
            <meta property="og:description" content="${product.description}">
            <meta property="og:image" content="${product.imageUrl}">
            <meta property="og:url" content="https://example.com/product/${product.id}">
            <meta property="og:type" content="product">
            <meta property="og:price:amount" content="${product.price}">
            <meta property="og:price:currency" content="USD">

            <!-- Twitter Card Meta Tags (optional) -->
            <meta name="twitter:card" content="summary_large_image">
            <meta name="twitter:title" content="React Native의 딥링킹과 유니버설링크 마스터하기: OpenGraph Share & Node.js 통합">
            <meta name="twitter:description" content="${product.description}">
            <meta name="twitter:image" content="${product.imageUrl}">

        
        
            <h1 id="React-Native의-딥링킹과-유니버설링크-마스터하기-OpenGraph-Share-amp-Node-js-통합">React Native의 딥링킹과 유니버설링크 마스터하기: OpenGraph Share & Node.js 통합</h1>
            <p>${product.description}</p>
            <img src="/static/imghw/default1.png" data-src="${product.imageUrl}" class="lazy" alt="React Native의 딥링킹과 유니버설링크 마스터하기: OpenGraph Share & Node.js 통합">
            <p>Price: ${product.price}</p>
        
        
    `);
});

// Start the server
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
    console.log(`Server is running on http://localhost:${PORT}`);
});

로그인 후 복사

Step 2: iOS Setup and Configuration:

a) (For production) Prepare the apple-app-site-association File

The apple-app-site-association (AASA) file is a JSON file that tells iOS which URLs should open your app. Here's how you might set it up for your eCommerce app:

{
    "applinks": {
        "apps": [],
        "details": [
            {
                "appIDs": ["ABCDE12345.com.shopeasy.app"],
                "paths": [
                    "/product/*",
                    "/category/*",
                    "/cart",
                    "/checkout"
                ]
            }
        ]
    }
}
로그인 후 복사
  • appIDs: . Your app’s identifier, combining your Apple Team ID (ABCDE12345) with your app’s bundle identifier (com.shopeasy.app).
  • paths: The paths on your website that should open in your app.
  • /product/*: Any product page (like https://www.shopeasy.com/product/123) should open in the app.
  • /category/*: Any category page (like https://www.shopeasy.com/category/shoes).
  • /cart and /checkout: The user's cart and checkout pages should also open in the app.

b) (For production) Host the apple-app-site-association File

After you construct the association file, place it in your site’s .well-known directory. The file’s URL should match the following format:

https:///.well-known/apple-app-site-association(eg: https://www.shopeasy.com/.well-known/apple-app-site-association)
You must host the file using https:// with a valid certificate and with no redirects.

c) Enable Associated Domains in Xcode

i) Open Xcode:
Open your ShopEasy project in Xcode.

ii) Add Associated Domains Capability:
Go to the "Signing & Capabilities" tab.
Click the "+" button and add "Associated Domains."

iii) Add Your Domain:
Under the Associated Domains section, add your domain prefixed with applinks:.
For example:
:
i) Service applinks: Used for deep linking and app-to-web interaction, allowing your app to handle specific URLs directly.
ii) Service webcredentials: Used to enable AutoFill for credentials, allowing users to seamlessly use saved passwords across your app and website.
Mastering Deep Linking and Universal Links in React Native: OpenGraph Share & Node.js Integration

For dev:

applinks:shopeasy
webcredentials:shopeasy
로그인 후 복사

For production:

applinks:shopeasy.com
webcredentials:shopeasy.com
로그인 후 복사

d)(ref) In Info.plist configuring URL Schemes: (URL schemes are useful when you want to open your app via a link that’s not necessarily a web URL, allowing deep linking within your app or launching it from another app.)

where:
CFBundleURLName: A human-readable name for the URL scheme. This can be any descriptive string.
CFBundleURLSchemes: The actual URL scheme your app supports. It should be a unique string like shopeasy/showeasy.com(if production set).

    <array>
...
        <dict>
            <key>CFBundleTypeRole</key>
            <string>Editor</string>
            <key>CFBundleURLName</key>
            <string>shopeasy</string>
            <key>CFBundleURLSchemes</key>
            <array>
                <string>shopeasy</string>
            </array>
        </dict>
    </array>
로그인 후 복사

d) In AppDelegate.mm:

#import <react>

// ...
// Add Below Code for DeepLinks

- (BOOL)application:(UIApplication *)application
openURL:(NSURL *)url
options:(NSDictionary<uiapplicationopenurloptionskey> *)options
{
return [RCTLinkingManager application:application openURL:url options:options];
}


- (BOOL)application:(UIApplication *)application continueUserActivity:(nonnull NSUserActivity *)userActivity
restorationHandler:(nonnull void (^)(NSArray<id>> * _Nullable))restorationHandler
{
return [RCTLinkingManager application:application
continueUserActivity:userActivity
restorationHandler:restorationHandler];
}

- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url
sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
return [RCTLinkingManager application:application openURL:url
sourceApplication:sourceApplication annotation:annotation];
}

//DEEP LINKS TILL HERE

@end
</id></uiapplicationopenurloptionskey></react>
로그인 후 복사

e) Testing deeplink device:

This should open the app.

npx uri-scheme open "shopeasy://product/mobile" --ios

로그인 후 복사

or

xcrun simctl openurl booted "shopeasy://product/mobile"

로그인 후 복사

Step 3: Android Setup and Configuration:

i) In AndroidManifest.xml:

    <application... ... android:launchmode="singleTask">

    <!-- DEEP LINKS HERE -->

   <intent-filter>
        <action android:name="android.intent.action.VIEW"></action>
        <category android:name="android.intent.category.DEFAULT"></category>
        <category android:name="android.intent.category.BROWSABLE"></category>
        <data android:scheme="shopeasy"></data>
    </intent-filter>

        <intent-filter>
        <action android:name="android.intent.action.VIEW"></action>
          <category android:name="android.intent.category.DEFAULT"></category>
          <category android:name="android.intent.category.BROWSABLE"></category>
          <data android:scheme="http"></data>
          <data android:scheme="https"></data>
          <data android:host="localhost"></data>
          <!-- REPLACE the HOST with app domain like shopeasy.com -->
        </intent-filter>
   <!-- DEEP LINKS HERE -->

/>
</application...>
로그인 후 복사

ii) Check in android:
adb shell am start -W -a android.intent.action.VIEW -d "shopeasy://product/apple" com.shopeasy
or
Click on this link in emulator if route is working:
http://localhost:3000/share/product/iphone


Step 3: Usage in React Native App:

Navigation.jsx

import React from 'react';
import { NavigationContainer } from '@react-navigation/native';
import MainNavigator from './MainNavigator';
import { navigationRef } from '../utils/NavigationUtil';

const config = {
  screens: {
    ProductScreen: '/product/:id',
    CategoryScreen: '/category/:name',
  },
};

const linking = {
  prefixes: ['shopeasy://', 'https://shopeasy.com', 'http://localhost:3000'], 
  config,
};

const Navigation: React.FC = () => {
  return (
    <navigationcontainer linking="{linking}" ref="{navigationRef}">
      <mainnavigator></mainnavigator>
    </navigationcontainer>
  );
};

export default Navigation;

로그인 후 복사

App.jsx

  useEffect(() => {
    // Retrieve the initial URL that opened the app (if any) and handle it as a deep link.
    Linking.getInitialURL().then(url => {
      handleDeepLink({ url }, 'CLOSE'); // Pass the URL and an action ('CLOSE') to handleDeepLink function.
    });

    // Add an event listener to handle URLs opened while the app is already running.
    Linking.addEventListener('url', event => handleDeepLink(event, 'RESUME'));
    // When the app is resumed with a URL, handle it as a deep link with the action ('RESUME').

    // Cleanup function to remove the event listener when the component unmounts.
    return () => {
      Linking.removeEventListener('url', event => handleDeepLink(event, 'RESUME'));
    };
  }, []);
로그인 후 복사

CLOSE/RESUME is optional and is passed handle as per requirement.

위 내용은 React Native의 딥링킹과 유니버설링크 마스터하기: OpenGraph Share & Node.js 통합의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

Video Face Swap

Video Face Swap

완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

뜨거운 도구

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전

SublimeText3 중국어 버전

중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구

SublimeText3 Mac 버전

SublimeText3 Mac 버전

신 수준의 코드 편집 소프트웨어(SublimeText3)

프론트 엔드 열 용지 영수증에 대한 차량 코드 인쇄를 만나면 어떻게해야합니까? 프론트 엔드 열 용지 영수증에 대한 차량 코드 인쇄를 만나면 어떻게해야합니까? Apr 04, 2025 pm 02:42 PM

프론트 엔드 개발시 프론트 엔드 열지대 티켓 인쇄를위한 자주 묻는 질문과 솔루션, 티켓 인쇄는 일반적인 요구 사항입니다. 그러나 많은 개발자들이 구현하고 있습니다 ...

Demystifying JavaScript : 그것이하는 일과 중요한 이유 Demystifying JavaScript : 그것이하는 일과 중요한 이유 Apr 09, 2025 am 12:07 AM

JavaScript는 현대 웹 개발의 초석이며 주요 기능에는 이벤트 중심 프로그래밍, 동적 컨텐츠 생성 및 비동기 프로그래밍이 포함됩니다. 1) 이벤트 중심 프로그래밍을 사용하면 사용자 작업에 따라 웹 페이지가 동적으로 변경 될 수 있습니다. 2) 동적 컨텐츠 생성을 사용하면 조건에 따라 페이지 컨텐츠를 조정할 수 있습니다. 3) 비동기 프로그래밍은 사용자 인터페이스가 차단되지 않도록합니다. JavaScript는 웹 상호 작용, 단일 페이지 응용 프로그램 및 서버 측 개발에 널리 사용되며 사용자 경험 및 크로스 플랫폼 개발의 유연성을 크게 향상시킵니다.

누가 더 많은 파이썬이나 자바 스크립트를 지불합니까? 누가 더 많은 파이썬이나 자바 스크립트를 지불합니까? Apr 04, 2025 am 12:09 AM

기술 및 산업 요구에 따라 Python 및 JavaScript 개발자에 대한 절대 급여는 없습니다. 1. 파이썬은 데이터 과학 및 기계 학습에서 더 많은 비용을 지불 할 수 있습니다. 2. JavaScript는 프론트 엔드 및 풀 스택 개발에 큰 수요가 있으며 급여도 상당합니다. 3. 영향 요인에는 경험, 지리적 위치, 회사 규모 및 특정 기술이 포함됩니다.

Shiseido의 공식 웹 사이트와 같은 시차 스크롤 및 요소 애니메이션 효과를 달성하는 방법은 무엇입니까?
또는:
Shiseido의 공식 웹 사이트와 같은 페이지 스크롤과 함께 애니메이션 효과를 어떻게 달성 할 수 있습니까? Shiseido의 공식 웹 사이트와 같은 시차 스크롤 및 요소 애니메이션 효과를 달성하는 방법은 무엇입니까? 또는: Shiseido의 공식 웹 사이트와 같은 페이지 스크롤과 함께 애니메이션 효과를 어떻게 달성 할 수 있습니까? Apr 04, 2025 pm 05:36 PM

이 기사에서 시차 스크롤 및 요소 애니메이션 효과 실현에 대한 토론은 Shiseido 공식 웹 사이트 (https://www.shiseido.co.jp/sb/wonderland/)와 유사하게 달성하는 방법을 살펴볼 것입니다.

JavaScript는 배우기가 어렵습니까? JavaScript는 배우기가 어렵습니까? Apr 03, 2025 am 12:20 AM

JavaScript를 배우는 것은 어렵지 않지만 어려운 일입니다. 1) 변수, 데이터 유형, 기능 등과 같은 기본 개념을 이해합니다. 2) 마스터 비동기 프로그래밍 및 이벤트 루프를 통해이를 구현하십시오. 3) DOM 운영을 사용하고 비동기 요청을 처리합니다. 4) 일반적인 실수를 피하고 디버깅 기술을 사용하십시오. 5) 성능을 최적화하고 모범 사례를 따르십시오.

JavaScript의 진화 : 현재 동향과 미래 전망 JavaScript의 진화 : 현재 동향과 미래 전망 Apr 10, 2025 am 09:33 AM

JavaScript의 최신 트렌드에는 Typescript의 Rise, 현대 프레임 워크 및 라이브러리의 인기 및 WebAssembly의 적용이 포함됩니다. 향후 전망은보다 강력한 유형 시스템, 서버 측 JavaScript 개발, 인공 지능 및 기계 학습의 확장, IoT 및 Edge 컴퓨팅의 잠재력을 포함합니다.

JavaScript를 사용하여 동일한 ID와 동일한 ID로 배열 요소를 하나의 객체로 병합하는 방법은 무엇입니까? JavaScript를 사용하여 동일한 ID와 동일한 ID로 배열 요소를 하나의 객체로 병합하는 방법은 무엇입니까? Apr 04, 2025 pm 05:09 PM

동일한 ID로 배열 요소를 JavaScript의 하나의 객체로 병합하는 방법은 무엇입니까? 데이터를 처리 할 때 종종 동일한 ID를 가질 필요가 있습니다 ...

프론트 엔드 개발에서 VSCODE와 유사한 패널 드래그 앤 드롭 조정 기능을 구현하는 방법은 무엇입니까? 프론트 엔드 개발에서 VSCODE와 유사한 패널 드래그 앤 드롭 조정 기능을 구현하는 방법은 무엇입니까? Apr 04, 2025 pm 02:06 PM

프론트 엔드에서 VSCODE와 같은 패널 드래그 앤 드롭 조정 기능의 구현을 탐색하십시오. 프론트 엔드 개발에서 VSCODE와 같은 구현 방법 ...

See all articles