」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > 掌握 React Native 中的深度連結和通用連結:OpenGraph Share 和 Node.js 集成

掌握 React Native 中的深度連結和通用連結:OpenGraph Share 和 Node.js 集成

發佈於2024-11-07
瀏覽:123

设想

假设您有一个名为 ShopEasy 的电子商务应用程序,并且您希望点击电子邮件、消息或社交媒体中的产品链接的用户被直接重定向到应用程序中的相关产品页面,而不是网站。


第1步:在nodejs服务器中进行Opengraph配置以进行链接预览:

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

Open Graph 是 Web 开发人员使用的一种协议,用于控制在 Facebook、Twitter、LinkedIn 等社交媒体平台上共享时 URL 的表示方式。通过在网页的 HTML 中使用 Open Graph 标签,您可以指定当用户共享链接时预览中将显示哪些内容。

要在 React Native 应用程序中使用这些 OpenGraph 标签,您需要使用深层链接或通用链接来处理服务器的链接(例如 https://ShopEasy.com/${type}/${id})。当用户分享这些链接时,Facebook、Twitter 或 iMessage 等平台将根据您定义的 OpenGraph 标签自动显示内容预览。

/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(`
        
        
        
            
            
            ${product.name}

            
            
            
            
            
            
            
            

            
            
            
            
            

        
        
            

${product.name}

${product.description}

${product.name}

Price: ${product.price}

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

第 2 步:iOS 设置和配置:

a) (用于生产) 准备 apple-app-site-association 文件

apple-app-site-association (AASA) 文件是一个 JSON 文件,它告诉 iOS 哪些 URL 应打开您的应用程序。以下是您为电子商务应用程序进行设置的方法:

{
    "applinks": {
        "apps": [],
        "details": [
            {
                "appIDs": ["ABCDE12345.com.shopeasy.app"],
                "paths": [
                    "/product/*",
                    "/category/*",
                    "/cart",
                    "/checkout"
                ]
            }
        ]
    }
}
  • appID: 您的应用程序的标识符,将您的 Apple 团队 ID (ABCDE12345) 与应用程序的捆绑包标识符 (com.shopeasy.app) 相结合。
  • paths:您网站上应在应用程序中打开的路径。
  • /product/*:任何产品页面(例如 https://www.shopeasy.com/product/123)都应在应用程序中打开。
  • /category/*:任何类别页面(例如 https://www.shopeasy.com/category/shoes)。
  • /cart 和 /checkout:用户的购物车和结帐页面也应该在应用程序中打开。

b) (用于生产) 托管 apple-app-site-association 文件

构建关联文件后,将其放置在站点的 .well-known 目录中。文件的 URL 应符合以下格式:

https:///.well-known/apple-app-site-association(例如:https://www.shopeasy.com/.well-known/apple-app-site-association )
您必须使用带有有效证书且不带重定向的 https:// 托管文件。

c) 在 Xcode 中启用关联域

i) 打开 Xcode:
在 Xcode 中打开您的 ShopEasy 项目。

ii) 添加关联域功能:
转到“签名和功能”选项卡。
单击“ ”按钮并添加“关联域”。

iii) 添加您的域名:
在“关联域”部分下,添加前缀为 applinks:.
的域 例如:
:
i) 服务应用链接:用于深层链接和应用程序到 Web 的交互,允许您的应用程序直接处理特定的 URL。
ii) 服务网络凭证:用于启用自动填充凭证,允许用户在您的应用程序和网站上无缝使用保存的密码。
Mastering Deep Linking and Universal Links in React Native: OpenGraph Share & Node.js Integration

对于开发人员:

applinks:shopeasy
webcredentials:shopeasy

用于生产:

applinks:shopeasy.com
webcredentials:shopeasy.com

d)(ref) 在 Info.plist 中配置 URL 方案:(当您想通过不一定是 Web URL 的链接打开应用程序时,URL 方案非常有用,允许在应用程序内进行深层链接或从另一个应用程序启动它。)

在哪里:
CFBundleURLName:URL 方案的人类可读名称。这可以是任何描述性字符串。
CFBundleURLSchemes:您的应用程序支持的实际 URL 方案。它应该是一个唯一的字符串,如 shopeasy/showeasy.com(如果是生产集)。

    
...
        
            CFBundleTypeRole
            Editor
            CFBundleURLName
            shopeasy
            CFBundleURLSchemes
            
                shopeasy
            
        
    

d) 在 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) 测试深度链接设备:

这应该打开应用程序。

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

或者

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

第 3 步:Android 设置和配置:

i) 在 AndroidManifest.xml 中:

    

    

   
        
        
        
        
    

        
        
          
          
          
          
          
          
        
   

/>

ii) 检查 android:
adb shell am start -W -a android.intent.action.VIEW -d "shopeasy://product/apple" com.shopeasy
或者
如果路由有效,请在模拟器中单击此链接:
http://localhost:3000/share/product/iphone


第 3 步:在 React Native 应用程序中使用:

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 是可选的,并根据要求传递句柄。

版本聲明 本文轉載於:https://dev.to/ajmal_hasan/mastering-deep-linking-and-universal-links-in-react-native-opengraph-share-nodejs-integration-4ppa?1如有侵犯,請聯絡study_golang @163.com刪除
最新教學 更多>

免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。

Copyright© 2022 湘ICP备2022001581号-3