iOS应用程序之间的几种跳转情况详解

2020-01-18 16:09:11王冬梅

前言

在iOS开发的过程中,我们经常会遇到比如需要从一个应用程序A跳转到另一个应用程序B的场景。这就需要我们掌握iOS应用程序之间的相互跳转知识。下面我们就常用到的几种跳转情况进行介绍。

一、跳转到另一个程序的主界面

每个程序都该有一个对应的Scheme,以确定对应的url

ios应用程序跳转,ios,应用程序间跳转,ios应用间跳转

一个程序要跳转到(打开)另外一个程序,需要将另外一个程序的Scheme添加到自己的应用程序白名单中(在info.plist中配置:LSApplicationQueriesSchemes,类型为数组,在数组中添加相应的Scheme)->ios9.0开始

ios应用程序跳转,ios,应用程序间跳转,ios应用间跳转

跳转代码


extension ViewController {

 @IBAction func jumpToXinWen(sender: AnyObject) {
  openURL("xinWen://")

 }
 private func openURL (urlString : String) {
  let url = NSURL(string: urlString)!
  if UIApplication.sharedApplication().canOpenURL(url) {
   UIApplication.sharedApplication().openURL(url)
  }

 }
}

二、跳转到另一个程序的指定界面

完成上面程序间跳转的相应设置

实现跳转代码(与跳转到主页相比,url多了参数,?前面参数是目标程序想要跳转界面的segu标签,?后面是当前程序的scheme)


 // MARK: - 跳转微信朋友圈
 @IBAction func jumpToWeChatTimeLine(sender: AnyObject) {
  openURL("WeChat://TimeLine?xinWen")

 }
 // MARK: - 跳转微信好友
 @IBAction func jumpToWeChatSession(sender: AnyObject) {
  openURL("WeChat://Session?xinWen")

 }
 private func openURL (urlString : String) {
  let url = NSURL(string: urlString)!
  if UIApplication.sharedApplication().canOpenURL(url) {
   UIApplication.sharedApplication().openURL(url)
  }

在目标程序AppDelegate中监听用来跳转的相应信息,根据这些信息让目标程序自己实现页面切换


extension AppDelegate {
 //监听当前程序被其他程序通过什么样的Url打开
 func application(application: UIApplication, openURL url: NSURL, sourceApplication: String?, annotation: AnyObject) -> Bool {
  //根据url跳转对应页面
  //1.url转化成字符串
  let urlString = url.absoluteString
  //2.获取首页控制器
  let rootVc = application.keyWindow?.rootViewController
  let mainVc = rootVc?.childViewControllers[0] as! ViewController
   //将url传递给mianVc
  mainVc.urlString = urlString
  //3.根据字符串内容完成对应跳转
  if urlString.containsString("Session") {//跳转好友
   mainVc.performSegueWithIdentifier("Session", sender: nil)
  }else if urlString.containsString("TimeLine") {//跳转朋友圈
   mainVc.performSegueWithIdentifier("TimeLine", sender: nil)
  }
  return true
 }
}