在iOS開發中經常遇到需要分享的需求,分享功能的實現就涉及到應用中的跳轉,今天就來簡單介紹一下蘋果自帶的跳轉功能實現.
- 應用A跳轉到應用B
-
首先需要在B應用中做出相應的配置
- 在info下找到URL Types中的URL Schemes給你的B應用綁定一個URL標識
- 然后再在應用A中實現如下代碼
NSURL *urlString = [NSURL URLWithString:@"B://"];
if ([[UIApplication sharedApplication] canOpenURL:urlString]) {
[[UIApplication sharedApplication] openURL:urlString];
}
完成以上操作就可以從A應用跳轉到B應用了
- 應用A跳轉到應用B中的其他頁面
- 在A中實現如下代碼
NSURL *urlString = [NSURL URLWithString:@"B://Other"];
if ([[UIApplication sharedApplication] canOpenURL:urlString]) {
[[UIApplication sharedApplication] openURL:urlString];
}
注意:NSURL *urlString = [NSURL URLWithString:@"B://Other"];這行代碼中需要在B://后面加上一個用來跟B://進行區分的字符串
- 然后再在B的AppDelegate中實現如下方法
-(BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<NSString *,id> *)options
{
ViewController *rootVc = (ViewController *)self.window.rootViewController;
NSString *urlString = url.absoluteString;
ZDHomeViewController *homeVc = [rootVc.childViewControllers firstObject];
if ([urlString containsString:@"Other"]) {
[homeVc.navigationController pushViewController:[[ZDOtherController alloc] init] animated:YES];
}
return YES;
}
完成以上操作就可以從A跳轉到B中相應的界面了
`注意:NSURL *urlString = [NSURL URLWithString:@"B://Other"];中B://后面加的字符串并不會影響從A跳轉到B`
- 從應用B回到應用A
當我們從A跳轉到B做完我們想要進行的操作后,需要再從B回到A 那么需要就進行以下的操作- 首先在A中的項目文件里面進行相應配置(操作見文章最上面的圖片)
需要注意的是第三步中的URL標識需要進行改動 不能和B一樣 URL標識就以A為例
- 首先在A中的項目文件里面進行相應配置(操作見文章最上面的圖片)
- 還需要在A中注意一點 在
NSURL *urlString = [NSURL URLWithString:@"B://Other?A"];
if ([[UIApplication sharedApplication] canOpenURL:urlString]) {
[[UIApplication sharedApplication] openURL:urlString];
}
中[NSURL URLWithString:@"B://Other?A"]
傳入的字符串最好給定一些格式 比如在后面接上?A
以進行區分
- 再在B中實現如下代碼
NSString *urlSchemeString = [[self.urlString componentsSeparatedByString:@"?"] lastObject];
NSString *urlString = [urlSchemeString stringByAppendingString:@"://"];
NSURL *url = [NSURL URLWithString:urlString];
if ([[UIApplication sharedApplication] canOpenURL:url]) {
[[UIApplication sharedApplication] openURL:url];
}
}
注意:在B中如何獲取A中所傳入的urlString呢? 需要完成如下幾步操作
1.在B中相應的控制器.h文件中搞一個屬性保存
@property (nonatomic,copy)NSString *urlString;
2.在上述提到的AppDelegate所實現的方法中接受URLString
homeVc.urlString = urlString;
完成以上操作就可以從B回到A了
以上僅僅是簡單介紹了一下系統自帶的跳轉功能實現 想要更好的完成需求還需要深入的學習與研究...