摘要:简单实现iOS应用之间的跳转,其中一些参数设置和逻辑处理不是太正规(相对标准化的参考文档:自定义 URL Scheme 完全指南)。本文以App1和App2之间跳转为例,实现从App1跳转至App2目标界面,然后从App2回到App1。
实现步骤:
1.获取/注册自定义的URL Scheme
获取:去对应App官方开发者网站获取接口
注册自定义:
默认情况下应用程序是没有自己的URL Scheme的,如果想要拥有自己的URL Scheme,需要设置:
项目-->info-->URL Types-->URL Scheme
Snip20161109_9.png
2.App1中进行跳转
/** URL : @"App2://App2VC1?App1"
--> App2:// : App2定义的协议头,用于跳转并打开app2
--> App2VC1 : 告知App2 App1需要跳转的目标控制器
--> App1 : App1定义的协议头,用于从App2跳转会App1(需要转换成App1:// 格式) */
// 跳转到App2主页
- (IBAction)jumpToApp2 {
[self skipToURL:@"App2://?App1"];
}
// 跳转到App2控制器1
- (IBAction)skipToApp2VC1 {
[self skipToURL:@"App2://App2VC1?App1"];
}
// 跳转到App2控制器2
- (IBAction)skipToApp2VC2 {
[self skipToURL:@"App2://App2VC2?App1"];
}
- (void)skipToURL:(NSString *)urlString
{
// 1.找到App2的URL
NSURL *url = [NSURL URLWithString:urlString];
// 2.判断是否可以正常打开URL
if ([[UIApplication sharedApplication] canOpenURL:url]) {
// 3.打开App2的URL
[[UIApplication sharedApplication] openURL:url];
} else {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"跳转错误"
message:@"用户还没有安装App2"
delegate:self cancelButtonTitle:@"Ok"
otherButtonTitles:nil];
[alert show];
}
}
3.打开App2并跳转到目标界面(App2的AppDelegate中)
@implementation AppDelegate// < ios 9.0 即将过期(很多应用程序都是多个方法同时实现)- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url { [self openURL:url]; return YES;}// < ios 9.0- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation { [self openURL:url]; return YES;}// >= ios9.0- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary*)options {
[self openURL:url];
return YES;
}
- (void)openURL:(NSURL *)url {
// 1.获取主控制器
UINavigationController *rootNav = (UINavigationController *)self.window.rootViewController;
ViewController *mainVc = [rootNav.childViewControllers firstObject];
[rootNav popToRootViewControllerAnimated:NO]; // 回到跟控制器
mainVc.urlString = url.absoluteString; // 逐级传值url
if ([url.absoluteString containsString:@"App2VC1"]) { // 跳转到目标控制器VC1
[mainVc performSegueWithIdentifier:@"App2VC1" sender:nil];
} else if ([url.absoluteString containsString:@"App2VC2"]) {
[mainVc performSegueWithIdentifier:@"App2VC2" sender:nil];
}
}
@end
- 从App2回到App1
- (IBAction)backToApp {
NSString *appURLString = [self.urlString componentsSeparatedByString:@"?"][1];
NSString *appURL = [NSString stringWithFormat:@"%@://", appURLString];
NSURL *url = [NSURL URLWithString:appURL];
[[UIApplication sharedApplication] openURL:url];
}
网友评论