打開其他應用,需要給被打開應用設置schemes:自定義的協議頭。
跳轉的代碼如下:
- (IBAction)skipToWechat {
[self openURLWithString:@"mywechat://"];
}
- (IBAction)skipToTimeline {
[self openURLWithString:@"mywechat://timeline?news"];
}
- (IBAction)skipToSession {
[self openURLWithString:@"mywechat://session?news"];
}
- (void)openURLWithString:(NSString *)urlString
{
// 1.獲取到對應應用程序的URL
NSURL *wechatURL = [NSURL URLWithString:urlString];
// 2.判斷手機中是否安裝了對應的應用程序
if ([[UIApplication sharedApplication] canOpenURL:wechatURL]) {
// 3.打開應用程序
[[UIApplication sharedApplication] openURL:wechatURL];
}
}
注:@”@”mywechat://timeline?news”中的?前邊的mywechat://timeline是要跳轉到協議頭爲myweichat的應用中的timeline頁面,後邊的news是當前應用的協議頭。
跳轉後,到目的應用中的AppDelegate類中獲取協議,並且半段跳轉到什麼頁面,代碼如下:
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
// self.url = url.absoluteString;
// 1.將URL轉成字符串
NSString *urlString = url.absoluteString;
// 獲取到主頁控制器
UINavigationController *rootNav = (UINavigationController *)self.window.rootViewController;
[rootNav popToRootViewControllerAnimated:NO];
ViewController *homeVc = [rootNav.childViewControllers firstObject];
homeVc.urlString = urlString;
// 2.判斷是通過朋友圈還是微信好友跳轉過來
if ([urlString containsString:@"timeline"]) {
[homeVc performSegueWithIdentifier:@"homeToTimeline" sender:nil];
} else if ([urlString containsString:@"session"]){
[homeVc performSegueWithIdentifier:@"homeToSession" sender:nil];
}
return YES;
}
從目的應用,跳回到原應用,就用到了收到的協議?後的參數,需要注意的是拼接完整協議頭,代碼如下:
- (IBAction)backToApp {
// 0.拿到對應應用程序的urlScheme(wechat://session?news)
/*
NSRange range = [self.urlString rangeOfString:@"?"];
range.location;
self.urlString substringFromIndex:range.location
*/
NSString *urlSchemeString = [[self.urlString componentsSeparatedByString:@"?"] lastObject];
NSString *urlString = [urlSchemeString stringByAppendingString:@"://"];
// 1.獲取對應應用程序的URL
NSURL *url = [NSURL URLWithString:urlString];
// 2.判斷是否可以打開
if ([[UIApplication sharedApplication] canOpenURL:url]) {
[[UIApplication sharedApplication] openURL:url];
}
}
轉載請註明出處,萬分感謝!