当前位置: 首页 > 科技观察

试试链接

时间:2023-03-20 20:41:54 科技观察

在iOS和Android上实现ReactNative应用我们生活在一个什么都可以分享的时代,分享的过程几乎最终都会分享某个链接。所以,作为开发者,最常见的问题应该包括如何通过URL地址快速打开App并导航到特定页面。什么是深度链接(DeepLink)深度链接是一种允许通过URL地址打开App,然后导航到特定页面或资源,或展示特定UI的技术。Deep表示打开的页面或资源不是App的首页。最常用的地方包括但不限于PushNotification、邮件、网页链接等,其实这个技术早就存在了。用鼠标点击mailto:pantao@parcmg.com等链接,系统会打开默认的邮件软件,然后在收件人输入栏填写pantao@parcmg.com的邮箱地址这里就是深度链接.本文将从头开始创建一个应用,支持通过deep-linking://articles/{ID}等URL打开文章详情页,加载{ID}指定的文章,如:deep-linking://articles/4会打开ID为4的文章详情页,deeplinking解决了什么问题?网页链接无法打开本机应用程序。如果用户在你的网页上访问了一个资源,而你的应用已经安装在他的手机上,那么我们如何让系统自动打开应用,然后在应用中显示用户访问的页面中的资源呢?这就是深度链接需要解决的问题。深度链接的不同实现方式深度链接的实现方式有两种:URLschemeUniversallinks前端是最常见的方式,后者是iOS提供的一种新方式,可以通过a链接到App的特定资源常用网页地址。本文将创建一个名为DeepLinkingExample的App,用户可以通过打开deep-linking://home和deep-linking://articles/4打开App的首页和ID为4的文章详情页分别。react-nativeinitDeepLinkingExamplecdDeepLinkingExampleInstallthenecessarylibraries跟上TypeScript的潮流,我们的App编写都会使用TypeScript开发。yarnaddreact-navigationreact-native-gesture-handlerreact-nativelinkreact-native-gesture-handler我们将使用react-navigation模块作为App的导航库。添加TypeScript相关的开发依赖:yarnaddtypescripttslinttslint-reacttslint-config-airbnbtslint-config-prettierts-jestreact-native-typescript-transformer-Dyarnadd@types/jest@types/node@types/react@types/react-native@types/react-navigation@types/react-test-renderer添加tsconfig.json:{"compilerOptions":{"target":"es2017",/*SpecifyECMAScripttargetversion:'ES3'(default),'ES5','ES2015','ES2016','ES2017',或'ESNEXT'.*/"module":"es2015",/*指定模块代码生成:'none','commonjs','amd','system','umd','es2015',or'ESNext'.*/"lib":[/*指定要包含在编译中的库文件:*/"es2017","dom"],"resolveJsonModule":true,"allowJs":false,/*允许编译javascript文件。*/"skipLibCheck":true,/*Skiptypecheckingofalldeclarationfiles.*/"jsx":"react-native",/*SpecifyJSXcodegeneration:'preserve','react-native',or'react'.*/"declaration":true,/*生成对应的'.d.ts'文件。*/"sourceMap":true,/*生成对应的'.map'文件.*/"outDir":"./lib",/*将输出结构重定向到目录。*/"removeComments":true,/*Donotemitcommentstooutput.*/"noEmit":true,/*Donotemitoutputs.*//*StrictType-CheckingOptions*/"strict":true,/*Enableallstricttype-checkingoptions.*/"noImplicitAny":true,/*Raiseerroronexpressionsanddeclarationswithanimplied'any'type.*/"strictNullChecks":true,/*Enablestrictnullchecks.*/"strictFunctionTypes":true,/*Enablestrictcheckingoffunctiontypes.*/"noImplicitThis":true,/*Raiseerroron'this'expressionswithanimplied'any'type.*/"alwaysStrict":true,/*Parseinstrictmodeandemit"usestrict"foreachsourcefile.*//*AdditionalChecks*/"noUnusedLocals":true,/*Reporterrorsonunusedlocals.*/"noUnusedParameters":true,/*Reporterrorsonunusedparameters.*/"noImplicitReturns":true,/*Reporterrorwhennotallcodepathsinfunctionreturnavalue.*/"noFallthroughCasesInSwitch":true,/*Reporterrorsforfallthroughcasesinsinswitchstatement.*//*ModuleResolutionOptions*/"moduleResolution":"node",/*指定模块分辨率策略:'node'(节点.js)or'classic'(TypeScriptpre-1.6).*/"baseUrl":"./",/*Basedirectorytoresolvenon-absolutemodulenames.*/"paths":{/*Aseriesofentrieswhichre-mapimportstolookuplocationsrelativetothe'baseUrl'.*/"*":["*.android","*.ios","*.native","*.web","*"]},"typeRoots":[/*Listoffolderstoincludetypedefinitionsfrom.*/"@types","../../@types"],//"types":[],/*Typedeclarationfilestobeincludedincompilation.*/"allowSyntheticDefaultImports":true,/*Allowdefaultimportsfrommoduleswithnodefaultexport.Thisdoesnotaffectcodeemit,justtype检查。*///"preserveSymlinks":true,/*不解析符号链接的实际路径。*//*ExperimentalOptions*/"experimentalDecorators":true,/*启用对ES7装饰器的实验性支持。*/"emitDecoratorMetadata":true/*启用对装饰器的发射类型元数据的实验性支持。*/},"排除":["node_modules","web"]}添加tslint.json文件{"defaultSeverity":"warning","extends":["tslint:recommended","tslint-react","tslint-config-airbnb","tslint-config-prettier"],"jsRules":{},"rules":{"curly":false,"function-name":false,"import-name":false,"interface-name":false,"jsx-boolean-value":false,"jsx-no-multiline-js":false,"member-access":false,"no-console":[true,"debug","dir","日志”,“跟踪”,“警告”],"no-empty-interface":false,"object-literal-sort-keys":false,"object-shorthand-properties-first":false,"semicolon":false,"strict-boolean-expressions":false“ter-arrow-parens”:false,“ter-indent”:false,“variable-name”:[true,“allow-leading-underscore”,“allow-pascal-case”,“ban-keywords”,"check-format"],"quotemark":false},"rulesDirectory":[]}添加.prettierrc文件:{"parser":"typescript","printWidth":100,"semi":false,"singleQuote":true,"trailingComma":"all"}编写我们的应用程序,在项目根目录下创建一个src目录,该目录将作为项目原始代码的目录添加src/App.tsx文件importReactfrom'react'import{createAppContainer,createStackNavigator}from'react-navigation'importAboutfrom'./screens/About'importArticlefrom'./screens/Article'importHomefrom'./screens/Home'constAppNavigator=createStackNavigator({Home:{screen:Home},About:{screen:About,path:'about'},Article:{screen:Article,path:'article/:id'},},{initialRouteName:'Home',},)constprefix='deep-linking://'constApp=createAppContainer(AppNavigator)constMainApp=()=>exportdefaultMainApp添加src/screens/Home.tsx文件importReactfrom'react';添加src/screens/About.tsximportReactfrom'react'import{StyleSheet,Text,View}from'react-native'import{NavigationScreenComponent}from'react-navigation'interfaceIProps{}interfaceIState{}constAboutScreen:NavigationScreenComponent=道具=>{return(AboutPage)}AboutScreen.navigationOptions={title:'About',}exportdefaultAboutScreenconststyles=StyleSheet.create({container:{},title:{},})添加src/screens/Article.tsximportReactfrom'react'import{StyleSheet,Text,View}from'react-native'import{NavigationScreenComponent}from'react-navigation'interfaceNavigationParams{id:string}constArticleScreen:NavigationScreenComponent=({navigation})=>{const{params}=navigation.statereturn(Article{params?params.id:'NoID'})}ArticleScreen.navigationOptions={title:'Article',}exportdefaultArticleScreenconststyles=StyleSheet.create({container:{},title:{},})ConfigureiOS打开ios/DeepLinkingExample.xcodeproj:openios/DeepLinkingExample.xcodeproj点击InfoTab页面,找到URLTypes配置,添加一项:identifier:deep-linkingURLSchemes:deep-linking其他两项留空打开工程和目录下的AppDelegate.m文件,新增导入:#import"React/RCTLinkingManager.h"和在@end之前添加以下代码:-(BOOL)application:(UIApplication*)applicationopenURL:(NSURL*)urlsourceApplication:(NSString*)sourceApplicationannotation:(id)annotation{return[RCTLinkingManagerapplication:applicationopenURL:urlsourceApplication:sourceApplicationannotation:annotation];}至此,我们完成了iOS配置,运行并测试react-nativerun-ios是否成功打开模拟器后,打开Safari浏览器,在地址栏输入:deep-linking://article/4,你的应用会自动打开,同时进入文章页面.同样,也可以在命令行工具中执行如下命令:xcrunsimctlopenurlbooteddeep-linking://article/4ConfigureAndroid为Android应用创建ExternalLinking,需要新建一个intent,打开android/app/src/main/AndroidManifest.xml,然后在MainActivity节点添加一个新的intent-filter:......Android只需要完成以上配置即可。执行:react-nativerun-android打开系统浏览器,输入:deep-linking://article/4系统会自动打开你的应用,进入文章页面。也可以在命令行工具中使用如下命令打开:adbshel??lamstart-W-aandroid.intent.action.VIEW-d"deep-linking://article/3"com.deeplinkingexample;