功能實現:A跳到B並打開B中指定頁面
步驟:
1.首先創建兩個項目(項目A,項目B),在項目B中的info.plist文件中添加URL Types,如下圖所示:其中URL idenifier是項目B的bundle id ,URL Schemes 中添加一個命令前綴,我這里使用“projectB”,這個名字可以自己取,運行一下項目B。
2.在項目A中添加跳轉代碼
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"projectB://"]];
- 1
- 1
這里的URL的命令前綴必須和之前自己定義的一致,我把這行代碼加到了一個button的點擊方法里,現在點擊button就可以跳到項目B了。
3.現在說下app之間跳轉的通信,其實跟傳值差不多。項目A中第二個button的點擊方法添加代碼
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"projectB://openBSecondPage"]];
- 1
- 1
4 . 項目B中在appDelegate中添加一個NSURL的屬性,實現一個代理方法接收從項目A傳過來的URL
-(BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url { self.url = url; return YES; }
- 1
- 2
- 3
- 4
- 5
- 1
- 2
- 3
- 4
- 5
然后在B中第一個界面加上代碼
- (void)viewDidLoad { [super viewDidLoad]; NSURL * url = ((AppDelegate *)[UIApplication sharedApplication].delegate).url; ; if(url){ //顯示一下從A獲取的url,url = projectB://openBSecondPage,host = openBSecondPage self.label.text = [NSString stringWithFormat:@"url = %@,host = %@",[url absoluteString],[url host]]; //根據傳過來的url的host進行一些操作 if ([[url host]isEqualToString:@"openBSecondPage"]) { //跳轉到第二個界面 [self performSegueWithIdentifier:@"second" sender:nil]; } } }
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
簡而言之,就是根據從A中傳過來的URL打開項目B后進行一些自定義操作
b的具體解析過程為: NSURL * url = ((AppDelegate *)[UIApplication sharedApplication].delegate).url;
;
if(url){
NSArray *arr = [url.host componentsSeparatedByString:@"&"];
NSLog(@"%@",arr);
UILabel *lab = [[UILabel alloc]initWithFrame:CGRectMake(10, 200, 300, 300)];
lab.text = [NSString stringWithFormat:@"%@",arr];
lab.numberOfLines = 0;
[self.view addSubview:lab];
//根據傳過來的url的host進行一些操作
if ([arr.lastObject isEqualToString:@"openurl=openBSecondPage"]) {
//跳轉到第二個界面
secondViewController *sec = [[secondViewController alloc]init];
[self.navigationController pushViewController:sec animated:YES];
}
}