React Native でディープ リンクとユニバーサル リンクをマスターする: OpenGraph Share と Node.js の統合

PHPz
リリース: 2024-09-01 21:05:31
オリジナル
702 人が閲覧しました

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(`   React Native でディープ リンクとユニバーサル リンクをマスターする: OpenGraph Share と Node.js の統合              

React Native でディープ リンクとユニバーサル リンクをマスターする: OpenGraph Share と Node.js の統合

${product.description}

React Native でディープ リンクとユニバーサル リンクをマスターする: OpenGraph Share と Node.js の統合

Price: ${product.price}

`); }); // 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).

 ...  CFBundleTypeRole Editor CFBundleURLName shopeasy CFBundleURLSchemes  shopeasy   
ログイン後にコピー

d) In AppDelegate.mm:

#import  // ... // Add Below Code for DeepLinks - (BOOL)application:(UIApplication *)application openURL:(NSURL *)url options:(NSDictionary *)options { return [RCTLinkingManager application:application openURL:url options:options]; } - (BOOL)application:(UIApplication *)application continueUserActivity:(nonnull NSUserActivity *)userActivity restorationHandler:(nonnull void (^)(NSArray> * _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 
ログイン後にコピー

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:

                  /> 
ログイン後にコピー

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 (    ); }; 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 中国語 Web サイトの他の関連記事を参照してください。

ソース:dev.to
このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
人気のチュートリアル
詳細>
最新のダウンロード
詳細>
ウェブエフェクト
公式サイト
サイト素材
フロントエンドテンプレート
私たちについて 免責事項 Sitemap
PHP中国語ウェブサイト:福祉オンライン PHP トレーニング,PHP 学習者の迅速な成長を支援します!