”工欲善其事,必先利其器。“—孔子《论语.录灵公》
首页 > 编程 > 掌握 React Native 中的深度链接和通用链接:OpenGraph Share 和 Node.js 集成

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

发布于2024-11-07
浏览:196

设想

假设您有一个名为 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如有侵犯,请联系[email protected]删除
最新教程 更多>
  • 为什么尽管有效代码,为什么在PHP中捕获输入?
    为什么尽管有效代码,为什么在PHP中捕获输入?
    在php ;?>" method="post">The intention is to capture the input from the text box and display it when the submit button is clicked.但是,输出...
    编程 发布于2025-05-21
  • 为什么在我的Linux服务器上安装Archive_Zip后,我找不到“ class \” class \'ziparchive \'错误?
    为什么在我的Linux服务器上安装Archive_Zip后,我找不到“ class \” class \'ziparchive \'错误?
    Class 'ZipArchive' Not Found Error While Installing Archive_Zip on Linux ServerSymptom:When attempting to run a script that utilizes the ZipAr...
    编程 发布于2025-05-21
  • Go语言垃圾回收如何处理切片内存?
    Go语言垃圾回收如何处理切片内存?
    在Go Slices中的垃圾收集:详细的分析在GO中,Slice是一个动态数组,引用了基础阵列。使用切片时,了解垃圾收集行为至关重要,以避免潜在的内存泄漏。考虑使用slice使用slice的以下实现:字符串{ R:=(*Q)[0] *q =(*q)[1:len(*q)] 返回...
    编程 发布于2025-05-21
  • 在Python中如何创建动态变量?
    在Python中如何创建动态变量?
    在Python 中,动态创建变量的功能可以是一种强大的工具,尤其是在使用复杂的数据结构或算法时,Dynamic Variable Creation的动态变量创建。 Python提供了几种创造性的方法来实现这一目标。利用dictionaries 一种有效的方法是利用字典。字典允许您动态创建密钥并分...
    编程 发布于2025-05-21
  • 表单刷新后如何防止重复提交?
    表单刷新后如何防止重复提交?
    在Web开发中预防重复提交 在表格提交后刷新页面时,遇到重复提交的问题是常见的。要解决这个问题,请考虑以下方法: 想象一下具有这样的代码段,看起来像这样的代码段:)){ //数据库操作... 回声“操作完成”; 死(); } ?> ...
    编程 发布于2025-05-21
  • 如何使用Python的请求和假用户代理绕过网站块?
    如何使用Python的请求和假用户代理绕过网站块?
    如何使用Python的请求模拟浏览器行为,以及伪造的用户代理提供了一个用户 - 代理标头一个有效方法是提供有效的用户式header,以提供有效的用户 - 设置,该标题可以通过browser和Acterner Systems the equestersystermery和操作系统。通过模仿像Chro...
    编程 发布于2025-05-21
  • PHP SimpleXML解析带命名空间冒号的XML方法
    PHP SimpleXML解析带命名空间冒号的XML方法
    在php 很少,请使用该限制很大,很少有很高。例如:这种技术可确保可以通过遍历XML树和使用儿童()方法()方法的XML树和切换名称空间来访问名称空间内的元素。
    编程 发布于2025-05-21
  • 切换到MySQLi后CodeIgniter连接MySQL数据库失败原因
    切换到MySQLi后CodeIgniter连接MySQL数据库失败原因
    无法连接到mySQL数据库:故障排除错误消息要调试问题,建议将以下代码添加到文件的末尾.//config/database.php并查看输出: ... ... 回声'... echo '<pre>'; print_r($db['default']); echo '</pr...
    编程 发布于2025-05-21
  • 在程序退出之前,我需要在C ++中明确删除堆的堆分配吗?
    在程序退出之前,我需要在C ++中明确删除堆的堆分配吗?
    在C中的显式删除 在C中的动态内存分配时,开发人员通常会想知道是否有必要在heap-procal extrable exit exit上进行手动调用“ delete”操作员,但开发人员通常会想知道是否需要手动调用“ delete”操作员。本文深入研究了这个主题。 在C主函数中,使用了动态分配变量(H...
    编程 发布于2025-05-21
  • 如何使用Python理解有效地创建字典?
    如何使用Python理解有效地创建字典?
    在python中,词典综合提供了一种生成新词典的简洁方法。尽管它们与列表综合相似,但存在一些显着差异。与问题所暗示的不同,您无法为钥匙创建字典理解。您必须明确指定键和值。 For example:d = {n: n**2 for n in range(5)}This creates a dicti...
    编程 发布于2025-05-21
  • Python中何时用"try"而非"if"检测变量值?
    Python中何时用"try"而非"if"检测变量值?
    使用“ try“ vs.” if”来测试python 在python中的变量值,在某些情况下,您可能需要在处理之前检查变量是否具有值。在使用“如果”或“ try”构建体之间决定。“ if” constructs 结果= function() 如果结果: 对于结果: #处理项...
    编程 发布于2025-05-21
  • 在Java中使用for-to-loop和迭代器进行收集遍历之间是否存在性能差异?
    在Java中使用for-to-loop和迭代器进行收集遍历之间是否存在性能差异?
    For Each Loop vs. Iterator: Efficiency in Collection TraversalIntroductionWhen traversing a collection in Java, the choice arises between using a for-...
    编程 发布于2025-05-21
  • JavaScript计算两个日期之间天数的方法
    JavaScript计算两个日期之间天数的方法
    How to Calculate the Difference Between Dates in JavascriptAs you attempt to determine the difference between two dates in Javascript, consider this s...
    编程 发布于2025-05-21
  • 如何使用PHP从XML文件中有效地检索属性值?
    如何使用PHP从XML文件中有效地检索属性值?
    从php $xml = simplexml_load_file($file); foreach ($xml->Var[0]->attributes() as $attributeName => $attributeValue) { echo $attributeName,...
    编程 发布于2025-05-21
  • 在细胞编辑后,如何维护自定义的JTable细胞渲染?
    在细胞编辑后,如何维护自定义的JTable细胞渲染?
    在JTable中维护jtable单元格渲染后,在JTable中,在JTable中实现自定义单元格渲染和编辑功能可以增强用户体验。但是,至关重要的是要确保即使在编辑操作后也保留所需的格式。在设置用于格式化“价格”列的“价格”列,用户遇到的数字格式丢失的“价格”列的“价格”之后,问题在设置自定义单元格...
    编程 发布于2025-05-21

免责声明: 提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发到邮箱:[email protected] 我们会第一时间内为您处理。

Copyright© 2022 湘ICP备2022001581号-3