iOS应用间相互跳转

当我们使用微信授权的时候,会从应用1跳转到微信,授权以后再跳转回应用1。这个跳转过程是怎么实现的呢?

1.新建两个工程,一个叫TestApp0,一个叫TestApp1。

2.在TestApp0中设置:
TARGETS->Info->URL Types
Identifier: com.test.app0
URL Schemes: app0
这里写图片描述
同样在TestApp1设置
TARGETS->Info->URL Types
Identifier: com.test.app1
URL Schemes: app1
这里写图片描述
URL Schemes相当于你App的标记。

3.在TestApp0中添加一个按钮,再在按钮事件中添加如下代码:

- (IBAction)clickAction:(id)sender {
    NSURL *url = [NSURL URLWithString:@"app1://app0"];
    if ([[UIApplication sharedApplication] canOpenURL:url]) {
        [[UIApplication sharedApplication] openURL:url];
    }
}

这样,点击click按钮,你就能从TestApp0,跳到TestApp1啦。(前提是你的设备已经安装了TestApp1)

其实url里面的字符串设置”app1://”就能跳转到TestApp1了。后面的字符串的是参数,我们把TestApp0的URL scheme一起带上,传给TestApp1。

4.在TestApp1中的AppDelegate.m中添加如下代码:

- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation {
    if (url) {
        NSLog(@"---url---%@", url);
        NSString *urlstr = [url absoluteString];
        NSArray *arr = [urlstr componentsSeparatedByString:@"://"];
        NSString *urlScheme = arr[1];

        [[NSUserDefaults standardUserDefaults] setObject:urlScheme forKey:@"schemes"];

        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"你看" message:urlScheme delegate:nil cancelButtonTitle:@"好的" otherButtonTitles:nil];
        [alert show];

        return YES;
    } else {
        return NO;
    }
    return NO;
}

这样当从TestApp0跳转过来的时候,就能收到来自TestApp0发来的信息啦。
得到的urlScheme ,就是TestApp0的URL scheme,不信你看alert都打出来了。
我们先把urlScheme保存下来,待会穿越回去的时候要用到。

5.在TestApp1添加一个按钮“返回”。在按钮事件中添加如下代码:

- (IBAction)returnAction:(id)sender {
    NSString *scheme = [[NSUserDefaults standardUserDefaults] stringForKey:@"schemes"];
    NSString *urlStr = [NSString stringWithFormat:@"%@://", value];
    NSURL *url = [NSURL URLWithString:urlStr];
    if ([[UIApplication sharedApplication] canOpenURL:url]) {
        [[UIApplication sharedApplication] openURL:url];
    }
}

好了,我们点击“返回”,从TestApp1,穿越回TestApp0了有木有。

这里写图片描述

6.xcode7/iOS9中有特殊设置。不设置的话可能会造成跳转失败。
你需要在TestApp0的 info.plist 中定义:

<key>LSApplicationQueriesSchemes</key>
<array>
    <string>app1</string>
</array>

这样你才可以顺利从TestApp0跳到TestApp1。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值