當我們使用微信授權的時候,會從應用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。