1.URL Scheme的作用 我们都知道苹果手机中的APP都有一个沙盒,APP就是一个信息孤岛,相互是不可以进行通信的。但是iOS的APP可以注册自己的URL Scheme,URL Scheme是为方便app之间互相调用而设计的。我们可以通过系统的OpenURL来打开该app,并可以传递一些参数。
例如:你在Safari里输入www.alipay.com,就可以直接打开你的支付宝app,前提是你的手机装了支付宝。如果你没有装支付宝,应该显示的是支付宝下载界面,点击会跳到AppStore的支付宝下载界面。
URL Scheme必须能唯一标识一个APP,如果你设置的URL Scheme与别的APP的URL Scheme冲突时,你的APP不一定会被启动起来。因为当你的APP在安装的时候,系统里面已经注册了你的URL Scheme。
一般情况下,是会调用先安装的app。但是iOS的系统app的URL Scheme肯定是最高的。所以我们定义URL Scheme的时候,尽量避开系统app已经定义过的URL Scheme。
下面就举例来实现一下,应用A跳转到应用B
2.如何 注册URL Scheme 1.在应用B工程的info.plist里添加URL types
2.添加URL Schemes
3.设置URL Schemes 和设置URL Identifier
URL Identifier是自定义的 URL scheme 的名字,一般采用反转域名的方法保证该名字的唯一性,比如 com.iOSStrongDemo.www,也可以不设置,或者随便设置一个,但必须保证唯一性
3.APP之间跳转测试 1.不带参数的方法(应用A里面)
-
(IBAction)click:(UIButton *)sender { NSString *url = @"isTony://tony"; [[UIApplication sharedApplication] openURL:[NSURL URLWithString:url] options:@{} completionHandler:^(BOOL success) { }]; } 2.带参数的方法
-
(IBAction)click:(UIButton *)sender { NSString *url = @"isTony://tony?name=tony&phone=18788888888"; [[UIApplication sharedApplication] openURL:[NSURL URLWithString:url] options:@{} completionHandler:^(BOOL success) { }]; } 3.应用B的AppDelegate.m里面监测是否跳转成功
//iOS9之前走这个方法
-
(BOOL)application:(UIApplication )application handleOpenURL:(NSURL)url { // 接受传过来的参数 NSString *text = [[url host] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"打开啦" message:text delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil]; [alertView show]; return YES; } //iOS9以后走的是这个方法 -(BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<NSString *,id> *)options{
NSLog(@"Calling Application Bundle ID: %@", options[UIApplicationOpenURLOptionsSourceApplicationKey]); NSLog(@"URL scheme: %@", [url scheme]); NSLog(@"URL query: %@", [url query]); NSString *text = [url query]; UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"跳转成功啦!" message:text preferredStyle:UIAlertControllerStyleAlert]; [alertVC addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction*action) { }]]; [self.window.rootViewController presentViewController:alertVC animated:YES completion:nil]; return YES;
} 4.跳转成功视频
- 通过Safari浏览器测试自定义的URL Schemes APP跳转 我们也可以在Safari浏览器地址栏里输入:isTony:// 也是可以跳转成功的