需要先认识几个概念:
从我们的应用跳转到别人的应用
其实,通过 application 发短信也是应用间跳转,从我们的应用打开系统自带的发短信应用。因此,想要打开一个应用,我们只需要知道该应用的协议头(scheme)即可。
当我们点击分享微信好友圈的时候,此时其实一共会有三种情况:
- 我们的手机并没有安装微信
- 我们的手机上的微信程序并没有运行
- 我们的手机上的微信 app 已经运行但是在某个特定的页面
[UIApplication sharedApplication] canOpenURL:wechatURL]
可以检测出是否安装微信,如果安装直接跳转即可,系统会自动打开微信 app。
代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
|
NSURL *wechatURL = [NSURL URLWithString:@"wechat://timeline?we"];
if ([[UIApplication sharedApplication] canOpenURL:wechatURL]) { [[UIApplication sharedApplication] openURL:wechatURL]; }
|
从别人的应用跳转到我们的应用
当别人的应用要跳转到你的应用时,application 代理会执行如下方法:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
| - (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<NSString *,id> *)options {
NSString *urlString = url.absoluteString; UINavigationController *rootNav = (UINavigationController *)self.window.rootViewController; [rootNav popToRootViewControllerAnimated:YES]; UIViewController *homeVc = [rootNav.childViewControllers firstObject]; if ([urlString containsString:@"timeline"]) { [rootNav pushViewController:@"朋友圈控制器" animated:YES]; } else if ([urlString containsString:@"session"]) { [rootNav pushViewController:@"微信好友控制器" animated: YES]; } return YES; }
|
如果跳转结束以后,此时需要返回原来的 app。我们需要拿到原来 app 的协议头 scheme。
如何拿呢?所以就需要跳转之前的 path,路径了,通过特殊符号拼接参数,将应用协议头拼接到参数中传递给我们。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
|
- (void)backToApp { NSString *urlSchemeString = [[self.urlString componentsSeparatedByString:@"?"] lastObject]; NSString *urlString = [urlSchemeString stringByAppendingString:@"://"]; NSURL *url = [NSURL URLWithString:urlString]; if ([[UIApplication sharedApplication] canOpenURL:url]) { [[UIApplication sharedApplication] openURL:url]; } }
|