在iOS 与Android上实现React Native应用的尝试链接

移动开发 Android
本文将从零开始创建一个应用,让它支持通过一个如 deep-linking://articles/{ID} 这样的 URL 打开 文章详情 页面,同时加载 {ID} 指定的文章,比如:deep-linking://articles/4 将打开 ID 为 4 的文章详情页面。

我们生活在一个万物兼可分享的年代,而分享的过程,几乎最终都会分享某一个链接,那么,作为开发者,最常遇到的问题中应该包括如何通过一个URL地址快速的打开App,并导航至特定的页面。

在iOS 与Android上实现React Native应用的尝试链接

什么是深度链接(Deep Link)

深度链接是一项可以让一个App通过一个URL地址打开,之后导航至特定页面或者资源,或者展示特定UI的技术,Deep 的意思是指被打开的页面或者资源并不是App的首页,最常使用到的地方包括但远远不限于 Push Notification、邮件、网页链接等。

其实这个技术在很久很久以前就已经存在了,鼠标点击一下 mailto:pantao@parcmg.com 这样的链接,系统会打开默认的邮件软件,然后将 pantao@parcmg.com 这个邮箱填写至收件人输入栏里,这就是深度链接。

本文将从零开始创建一个应用,让它支持通过一个如 deep-linking://articles/{ID} 这样的 URL 打开 文章详情 页面,同时加载 {ID} 指定的文章,比如:deep-linking://articles/4 将打开 ID 为 4 的文章详情页面。

深度链接解决了什么问题?

网页链接是无法打开原生应用的,如果一个用户访问你的网页中的某一个资源,他的手机上面也已经安装了你的应用,那么,我们要如何让系统自动的打开应用,然后在应用中展示用户所访问的那一个页面中的资源?这就是深度链接需要解决的问题。

实现深度链接的不同方式

有两种方式可以实现深度链接:

  • URL scheme
  • Universal links

前端是最常见的方式,后者是 iOS 新提供的方式,可以一个普通的网页地址链接至App的特定资源。

本文将创建一个名为 DeepLinkingExample 的应用,使得用户可以通过打开 deep-linking://home 以及 deep-linking://articles/4 分别打开 App 的首页以及 App 中 ID 为 4 的文章详情页面。

 

  1. react-native init DeepLinkingExample 
  2. cd DeepLinkingExample 

安装必要的库

紧跟 TypeScript 大潮流,我们的 App 写将使用 TypeScript 开发。

 

  1. yarn add react-navigation react-native-gesture-handler 
  2. react-native link react-native-gesture-handler 

我们将使用 react-navigation 模块作为 App 的导航库。

添加 TypeScript 相关的开发依赖:

 

  1. yarn add typescript tslint tslint-react tslint-config-airbnb tslint-config-prettier ts-jest react-native-typescript-transformer -D 
  2. yarn add @types/jest @types/node @types/react @types/react-native @types/react-navigation @types/react-test-renderer 

添加 tsconfig.json:

 

  1.   "compilerOptions": { 
  2.     "target""es2017",                       /* Specify ECMAScript target version: 'ES3' (default), 'ES5''ES2015''ES2016''ES2017'or 'ESNEXT'. */ 
  3.     "module""es2015",                       /* Specify module code generation: 'none''commonjs''amd''system''umd''es2015'or 'ESNext'. */ 
  4.     "lib": [                                  /* Specify library files to be included in the compilation:  */ 
  5.       "es2017"
  6.       "dom" 
  7.     ], 
  8.     "resolveJsonModule"true
  9.     "allowJs"false,                         /* Allow javascript files to be compiled. */ 
  10.     "skipLibCheck"true,                     /* Skip type checking of all declaration files. */ 
  11.     "jsx""react-native",                    /* Specify JSX code generation: 'preserve''react-native'or 'react'. */ 
  12.     "declaration"true,                      /* Generates corresponding '.d.ts' file. */ 
  13.     "sourceMap"true,                        /* Generates corresponding '.map' file. */ 
  14.     "outDir""./lib",                        /* Redirect output structure to the directory. */ 
  15.     "removeComments"true,                   /* Do not emit comments to output. */ 
  16.     "noEmit"true,                           /* Do not emit outputs. */ 
  17.  
  18.     /* Strict Type-Checking Options */ 
  19.     "strict"true,                           /* Enable all strict type-checking options. */ 
  20.     "noImplicitAny"true,                    /* Raise error on expressions and declarations with an implied 'any' type. */ 
  21.     "strictNullChecks"true,                 /* Enable strict null checks. */ 
  22.     "strictFunctionTypes"true,              /* Enable strict checking of function types. */ 
  23.     "noImplicitThis"true,                   /* Raise error on 'this' expressions with an implied 'any' type. */ 
  24.     "alwaysStrict"true,                     /* Parse in strict mode and emit "use strict" for each source file. */ 
  25.  
  26.     /* Additional Checks */ 
  27.     "noUnusedLocals"true,                   /* Report errors on unused locals. */ 
  28.     "noUnusedParameters"true,               /* Report errors on unused parameters. */ 
  29.     "noImplicitReturns"true,                /* Report error when not all code paths in function return a value. */ 
  30.     "noFallthroughCasesInSwitch"true,       /* Report errors for fallthrough cases in switch statement. */ 
  31.  
  32.     /* Module Resolution Options */ 
  33.     "moduleResolution""node",               /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */ 
  34.     "baseUrl""./",                          /* Base directory to resolve non-absolute module names. */ 
  35.     "paths": {                                /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */ 
  36.       "*": [ 
  37.         "*.android"
  38.         "*.ios"
  39.         "*.native"
  40.         "*.web"
  41.         "*" 
  42.       ] 
  43.     }, 
  44.     "typeRoots": [                            /* List of folders to include type definitions from. */ 
  45.       "@types"
  46.       "../../@types" 
  47.     ], 
  48.     // "types": [],                           /* Type declaration files to be included in compilation. */ 
  49.     "allowSyntheticDefaultImports"true,     /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */ 
  50.     // "preserveSymlinks"true,              /* Do not resolve the real path of symlinks. */ 
  51.  
  52.     /* Experimental Options */ 
  53.     "experimentalDecorators"true,           /* Enables experimental support for ES7 decorators. */ 
  54.     "emitDecoratorMetadata"true             /* Enables experimental support for emitting type metadata for decorators. */ 
  55.   }, 
  56.   "exclude": [ 
  57.     "node_modules"
  58.     "web" 
  59.   ] 

添加 tslint.json 文件

 

  1.   "defaultSeverity""warning"
  2.   "extends": [ 
  3.     "tslint:recommended",  
  4.     "tslint-react"
  5.     "tslint-config-airbnb"
  6.     "tslint-config-prettier" 
  7.   ], 
  8.   "jsRules": {}, 
  9.   "rules": { 
  10.     "curly"false
  11.     "function-name"false
  12.     "import-name"false
  13.     "interface-name"false
  14.     "jsx-boolean-value"false
  15.     "jsx-no-multiline-js"false
  16.     "member-access"false
  17.     "no-console": [true"debug""dir""log""trace""warn"], 
  18.     "no-empty-interface"false
  19.     "object-literal-sort-keys"false
  20.     "object-shorthand-properties-first"false
  21.     "semicolon"false
  22.     "strict-boolean-expressions"false
  23.     "ter-arrow-parens"false
  24.     "ter-indent"false
  25.     "variable-name": [ 
  26.       true
  27.       "allow-leading-underscore"
  28.       "allow-pascal-case"
  29.       "ban-keywords"
  30.       "check-format" 
  31.     ], 
  32.     "quotemark"false 
  33.   }, 
  34.   "rulesDirectory": [] 

添加 .prettierrc 文件:

 

  1.   "parser""typescript"
  2.   "printWidth": 100, 
  3.   "semi"false
  4.   "singleQuote"true
  5.   "trailingComma""all" 

编写我们的应用

在项目根目录下创建一个 src 目录,这个将是项目原代码的目录。

添加 src/App.tsx 文件

  1. import React from 'react' 
  2.  
  3. import { createAppContainer, createStackNavigator } from 'react-navigation' 
  4.  
  5. import About from './screens/About' 
  6. import Article from './screens/Article' 
  7. import Home from './screens/Home' 
  8.  
  9. const AppNavigator = createStackNavigator( 
  10.   { 
  11.     Home: { screen: Home }, 
  12.     About: { screen: About, path: 'about' }, 
  13.     Article: { screen: Article, path: 'article/:id' }, 
  14.   }, 
  15.   { 
  16.     initialRouteName: 'Home'
  17.   }, 
  18.  
  19. const prefix = 'deep-linking://' 
  20.  
  21. const App = createAppContainer(AppNavigator) 
  22.  
  23. const MainApp = () => <App uriPrefix={prefix} /> 
  24.  
  25. export default MainApp 

添加 src/screens/Home.tsx 文件

  1. import React from 'react'

添加 src/screens/About.tsx

 

  1. import React from 'react' 
  2.  
  3. import { StyleSheet, Text, View } from 'react-native' 
  4.  
  5. import { NavigationScreenComponent } from 'react-navigation' 
  6.  
  7. interface IProps {} 
  8.  
  9. interface IState {} 
  10.  
  11. const AboutScreen: NavigationScreenComponent<IProps, IState> = props => { 
  12.   return ( 
  13.     <View style={styles.container}> 
  14.       <Text style={styles.title}>About Page</Text> 
  15.     </View
  16.   ) 
  17.  
  18. AboutScreen.navigationOptions = { 
  19.   title: 'About'
  20.  
  21. export default AboutScreen 
  22.  
  23. const styles = StyleSheet.create({ 
  24.   container: {}, 
  25.   title: {}, 
  26. }) 

添加 src/screens/Article.tsx

 

  1. import React from 'react' 
  2.  
  3. import { StyleSheet, Text, View } from 'react-native' 
  4.  
  5. import { NavigationScreenComponent } from 'react-navigation' 
  6.  
  7. interface NavigationParams { 
  8.   id: string 
  9.  
  10. const ArticleScreen: NavigationScreenComponent<NavigationParams> = ({ navigation }) => { 
  11.   const { params } = navigation.state 
  12.  
  13.   return ( 
  14.     <View style={styles.container}> 
  15.       <Text style={styles.title}>Article {params ? params.id : 'No ID'}</Text> 
  16.     </View
  17.   ) 
  18.  
  19. ArticleScreen.navigationOptions = { 
  20.   title: 'Article'
  21.  
  22. export default ArticleScreen 
  23.  
  24. const styles = StyleSheet.create({ 
  25.   container: {}, 
  26.   title: {}, 
  27. }) 

配置 iOS

打开 ios/DeepLinkingExample.xcodeproj:

  1. open ios/DeepLinkingExample.xcodeproj 

点击 Info Tab 页,找到 URL Types 配置,添加一项:

  • identifier:deep-linking
  • URL Schemes:deep-linking
  • 其它两项留空

打开项目跟目录下的 AppDelegate.m 文件,添加一个新的 import:

  1. #import "React/RCTLinkingManager.h" 

然后在 @end 前面,添加以下代码:

 

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

至此,我们已经完成了 iOS 的配置,运行并测试是否成功。

  1. react-native run-ios 

打开 simulator 之后,打开 Safari 浏览器,在地址栏中输入:deep-linking://article/4 ,你的应用将会自动打开,并同时进入到 Article 页面。

同样的,你还可以在命令行工具中执行以下命令:

  1. xcrun simctl openurl booted deep-linking://article/4 

配置 Android

要为Android应用也创建 External Linking,需要创建一个新的 intent,打开 android/app/src/main/AndroidManifest.xml,然后在 MainActivity 节点添加一个新的 intent-filter:

 

  1. <application ...> 
  2.   <activity android:name=".MainActivity" ...> 
  3.     ... 
  4.     <intent-filter> 
  5.       <action android:name="android.intent.action.VIEW" /> 
  6.       <category android:name="android.intent.category.DEFAULT" /> 
  7.       <category android:name="android.intent.category.BROWSABLE" /> 
  8.       <data android:scheme="deep-linking" /> 
  9.     </intent-filter> 
  10.     ... 
  11.   </activity> 
  12. </application> 

Android 只需要完成上面的配置即可。

执行:

  1. react-native run-android 

打开系统浏览器,输入:

  1. deep-linking://article/4 

系统会自动打开你的应用,并进入 Article 页面

也可以在命令行工具中使用以下命令打开:

  1. adb shell am start -W -a android.intent.action.VIEW -d "deep-linking://article/3" com.deeplinkingexample; 

 

责任编辑:未丽燕 来源: 大胡子农民工潘半仙
相关推荐

2018-01-02 16:08:00

AndroidiOSReact Nativ

2015-03-30 12:13:23

React NativiOS

2015-09-22 09:50:36

FacebookAndroid

2016-08-12 08:49:46

React NativFacebookNative

2016-11-23 16:48:20

react-nativandroidjavascript

2011-11-02 13:56:13

2011-02-25 15:49:09

NecessitasQtAndroid

2016-08-15 13:34:37

React NativiOSjs入口

2015-10-10 16:02:36

React NativAndroid

2023-09-04 08:32:43

web开发图像

2023-11-21 10:25:28

LinuxFlathubFlatpak

2023-12-11 10:25:02

FlatpakLinux

2017-08-15 19:20:51

AndroidHttpServer

2012-03-08 22:29:41

Android

2017-10-18 12:22:43

NativeHybirdJavaScript

2019-08-29 09:00:55

开发Flutter框架

2017-05-03 15:00:59

PC树莓派PIXEL OS

2015-05-12 09:40:11

WindowsAndroidiOS

2023-03-07 16:12:32

2011-10-09 14:45:58

Alien DalviiOSAndroid
点赞
收藏

51CTO技术栈公众号