URL Schemes通常用於分享和第三方登錄,但有時需要在html跳至APP,或者APP跳至另外一個APP.這時也需要使用URL Schemes.
一.html跳轉至APP
eg:html跳轉至test1
在APP中添加URL Schemes,這里的URL Schemes隨意寫均可,如圖:
2.在AppDelegate.swift中加入,func application(app: UIApplication, openURL url: NSURL, options: [String : AnyObject])
-> Bool這個方法:
1 //MARK: - 通過下面的方法實現點擊html可以打開app 2 func application(app: UIApplication, openURL url: NSURL, options: [String : AnyObject]) 3 -> Bool { 4 if url.host == nil 5 { 6 return true; 7 } 8 let urlString = url.absoluteString //url 的絕對字符串 9 let queryArray = urlString.componentsSeparatedByString("/") //通過/把URL切成數組 10 //傳參 11 // let alertController = UIAlertController(title: "參數如下", 12 // message: "\(queryArray[2]) \(queryArray[3])", preferredStyle: .Alert) 13 // let cancelAction = UIAlertAction(title: "取消", style: .Cancel, handler: nil) 14 // alertController.addAction(cancelAction) 15 // self.window!.rootViewController!.presentViewController(alertController, animated: true, completion: nil) 16 //打開相應界面 17 let tababarController = self.window!.rootViewController!.childViewControllers[0] as! UITabBarController 18 if queryArray[2] == "item1" { 19 tababarController.selectedIndex = 0 //使tabcarController選中第一個tabbaritem 20 }else if queryArray[2] == "item2"{ 21 tababarController.selectedIndex = 1 //使tabcarController選中第二個tabbaritem 22 } 23 //測試方法: 24 //先安裝test1 25 //打開瀏覽器地址欄輸入 26 // test1:// 打開test1 27 // test1://item1 打開test1的第一個item 28 // test1://item2 打開test1的第二個item 29 //上面的test1就是工程中配置的URL Schemes 30 return true 31 }
二.APP打開APP
eg:test1打開test2
先在test2中配置URl Schemes,然后在test1中寫代碼即可:
在點擊test1中的一個按鈕時,在其點擊方法中通過openURL打開即可.
1 @IBOutlet var btn: UIButton! 2 override func viewDidLoad() { 3 super.viewDidLoad() 4 btn.addTarget(self, action: #selector(Tab2ViewController.btnClick), forControlEvents: .TouchUpInside) 5 // Do any additional setup after loading the view. 6 } 7 func btnClick(){ 8 let urlString = "test2://" 9 let url = NSURL(string: urlString) 10 UIApplication.sharedApplication().openURL(url!) 11 }
同時,因為iOS9的安全因素,需要在test1中設置白名單.設置方法參考:http://www.cnblogs.com/shaoting/p/5148323.html
其余常見應用的URL Schemes:http://www.cnblogs.com/shaoting/p/5148323.html
demo下載:https://github.com/pheromone/URLSchemes
http://download.csdn.net/detail/shaoting19910730/9496841