当我们使用微信授权的时候,会从应用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。