(八十五)应用程序间的跳转与消息传递

应用程序的跳转识别的是URL的协议头,每一个应用都能够指定一个URL的协议头。以此作为跳转的根据。而URL的地址部分作为消息体。

【指定应用程序URL协议头的方法】

选择TARGETS->info->URL Types,加入URL Schemes:

【实现跳转的方法】

要实现应用级操作。须要借助UIApplication单例的openURL方法。

增加A要跳转到B。B的URL Schemes为app2,则实现跳转的URL应该为"app2://..."。...部分任意,为要传递的消息。

注意在跳转前先用canOpenURL推断是否有这个app,没有应该打开App Store推荐用户下载。

UIApplication *app = [UIApplication sharedApplication];
NSURL *url = [NSURL URLWithString:@"app2://"]; // 有协议头就可以打开app,后面的内容用于指示应该打开app的哪个功能。
if ([app canOpenURL:url]) {
    [app openURL:url];
}else{
    NSLog(@"依据App id打开App Store");
}

【接收跳转的方法】

在AppDelegate中有两个方法能够实如今跳转到自己后接收URL:

- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url{
    return YES; // 代表是否成功处理   
}


// 新方法会使得旧方法失效。建议两个都写
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation{
    return YES; 
}
第二个方法比較新。有sourceApplication參数来得到运行跳转的App的Bundle identifier,当中url就是运行跳转时打开的url,建议两个方法都实现。


【利用两个App演示应用跳转与消息传递】

App1:两个button。第一个点击后跳转到App2的主页,第二个点击后跳转到App2的还有一个页面page1。

App2:有主页和page1和page2两个页面,通过NavigationController跳转。

①App1中实现跳转到App2的page1的代码:

// 应用级操作利用UIApplication单例完毕
UIApplication *app = [UIApplication sharedApplication];
NSURL *url = [NSURL URLWithString:@"app2://page=1"]; // 有协议头就可以打开app,后面的内容用于指示应该打开app的哪个功能。
if ([app canOpenURL:url]) {
    [app openURL:url];
}else{
    NSLog(@"依据App id打开App Store");
}
②App2中实现接收与页面跳转的方法:

在App2中。界面的关系是NavigationController->Home(show方式连接的page1和page2,page1和page2的segue分别为page1和page2)。

假设要实现给控制器传值,能够在performSegueWithIdentifier方法传入sender,在跳转前还会调用prepareForSegue::方法拿到sender。利用segue的sourceViewController和destinationViewController来赋值。

- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation{
    
    NSLog(@"url = %@ id = %@",url.absoluteString,sourceApplication);
    
    // 为了实现跳转,应该拿到导航控制器,拿到首页的控制器。然后调用performSegueWithIdentifier::
    // 调用performSegueWithIdentifier跳转前会调用prepareForSegue,用来给要跳到的控制器传值。
    UINavigationController *nav = (UINavigationController *)self.window.rootViewController;
    
    ViewController *homeVc = (ViewController *)nav.topViewController;
    
    NSLog(@"%@",url);
    
    NSString *urlStr = url.absoluteString;
    if ([urlStr rangeOfString:@"page=1"].location != NSNotFound) {
        NSLog(@"跳转到页面1");
        if (![homeVc isKindOfClass:[ViewController class]]) return YES;
        [homeVc performSegueWithIdentifier:@"page1" sender:nil];
    }else{
        NSLog(@"跳转到页面2");
        if (![homeVc isKindOfClass:[ViewController class]]) return YES;
        [homeVc performSegueWithIdentifier:@"page2" sender:nil];
    }
    
    return YES;
    
}

原文地址:https://www.cnblogs.com/slgkaifa/p/7131718.html