一、跳转的原理
在iOS中,两个app之间的交互和通信,使用UIApplication来管理。我们要打开另一个应用程序,如何实现呢?
其实就是UIApplication的这个API
/**
通过应用程序打开一个资源路径
@param url 资源路径的地址
@return 返回成功失败
*/
- (BOOL)openURL:(NSURL*)url;
我们平时用过的一些案例如下:
//拨打系统电话
NSURL *url = [NSURL URLWithString:@"tel://10010"];
[[UIApplication sharedApplication] openURL:url];
//发送系统短信
NSURL *url = [NSURL URLWithString:@"sms://15524637410"];
[[UIApplication sharedApplication] openURL:url];
一个应用能打开另一个应用的必然条件是,另一个应用必须配置一个scheme(协议),这样应用程序才能根据协议找到需要打开的应用
二、实现两个app间的跳转
创建两个示例Demo,Test1和Test2,现在需要实现从Test2跳转到Test1中
- 在被跳转的Test1配置一个协议scheme,这里命名为com.htmitech.test(名字可随意配置,当然最好是域名反写)
targets -> info -> URL Types ->URL Scheme ->填写协议名称
- 配置协议白名单
在Test2的info.plist文件中增加一个LSApplicationQueriesSchemes,把它设置为数组类型,并配置需要跳转的协议名单
三、跳转到指定界面
1、在"com.htmitech.test://"协议后面的域名加上一些字段用来标记需要跳转的界面
//进入其他界面
- (IBAction)gotoOther:(id)sender {
NSURL *url = [NSURL URLWithString:@"com.htmitech.test://other"];
if ([[UIApplication sharedApplication] canOpenURL:url]) {
[[UIApplication sharedApplication] openURL:url];
}else{
NSLog(@"没有安装应用");
}
}
2、在被跳转的应用Test1的AppDelegate类的.m文件中,监听其代理方法application:handleOpenURL:
//当应用程序将要被其他程序打开时,会先执行此方法,并传递url过来 //注:下面这个方法9.0后就过期了,请注意适配,9.0后用这个方法:application:openURL:options:
-(BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
{
NSLog(@"url:%@",url.absoluteString);
NSLog(@"host:%@",url.host);
if ([url.host isEqualToString:@"other"]) {
NSLog(@"进入其他界面");
//在此做界面的跳转
}
return YES;
}