01 APP之间的跳转
1. APP之间的跳转
1. 创建2个测试工程: test1 & test2
需求:我们要让点击test1的某个按钮,跳转到test2项目,并且带上test1的某个参数
2. 步骤
-
在test2中,配置URL Types
- 在URL Schemes中写上自己的标记:“test2” ,意思是别人可以通过这个标记找到我,跳转到我这里来
如下图
- 在URL Schemes中写上自己的标记:“test2” ,意思是别人可以通过这个标记找到我,跳转到我这里来
-
在test1中,配置test2的白名单,意思是我可以跳转到test2中去
- 在Info.plist文件中,添加LSApplicationQueriesSchemes字段(Array类型)
- 再添加配置白名单:“test2”
3. 代码部分
- test1中代码
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
@IBAction func btn1(_ sender: Any) { // 跳转到app
let url = URL(string: "test2://")!
print("btn1=\(url.path)\n query=\(String(describing: url.query))")
if !UIApplication.shared.canOpenURL(url) {
return
}
UIApplication.shared.open(url, options: [:]) { isOK in
print(isOK)
}
}
@IBAction func btn2(_ sender: Any) { // 跳转到特定页面
let url = URL(string: "test2://test1/vc2?name=lisi")!
print("btn2=\(url.path)\n query=\(String(describing: url.query))")
if !UIApplication.shared.canOpenURL(url) {
return
}
UIApplication.shared.open(url, options: [:]) { isOK in
print(isOK)
}
}
}
- test2代码
- 在AppDelegate中
import UIKit
@main
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
let vc = ViewController()
window = UIWindow(frame: UIScreen.main.bounds)
// window?.backgroundColor = .white
window?.rootViewController = UINavigationController(rootViewController: vc)
window?.makeKeyAndVisible()
return true
}
func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
dealUrl(url: url)
print("application2")
return true
}
func dealUrl(url: URL) {
if let nav = window?.rootViewController as? UINavigationController {
nav.popToRootViewController(animated: false)
let rootvc = nav.children[0]
print("url.path==\(url.path)")
if url.path == "/vc2" {
let vc2 = SecondViewController()
let str = url.query?.split(separator: "=").last
let name = String(str!)
vc2.name = name // 接收参数
rootvc.navigationController?.pushViewController(vc2, animated: true)
}
}
}
}
- 参数解析
let url = URL(string: "https://www.taobao.com/markets/bao/xiangbao?spm=a21bo.2017.201867-main.5.5af911d9blzLlJ")
print("协议=",url!.scheme ?? "","IP或者是域名=",url!.host ?? "","路径=",url!.path ,"参数=",url!.query ?? "")