兩個app: Test 和 BasicGrammar
目的:從Test app 中打開 BasicGrammar app內指定的某個頁面,并傳參數過去:
BasicGrammar:
配置info.plist
AppDelegate
func application(app: UIApplication, openURL url: NSURL, options: [String : AnyObject]) -> Bool {
//這里進行判斷是哪一個app在打開此app,然后分別進行操作
let scheme = url.scheme
//不分大小寫比較
if scheme.caseInsensitiveCompare("OpenAppTest") == .OrderedSame{
//執行跳轉,跳轉到你想要的頁面
let alert = UIAlertView(title: "\(scheme)", message: "\(url)", delegate: self, cancelButtonTitle: "確認")//iOS, introduced=2.0, deprecated=9.0
alert.show()
let vc = NextViewController()
if let navVC = self.window?.rootViewController as? UINavigationController{
navVC.pushViewController(vc, animated: true)
}
return true
}
return true
}
Test:
記得設置info.plist里面的LSApplicationQueriesSchemes,iOS9之后需要,iOS9之后提高了app的安全性,需要給出一個類似白名單的東西,在白名單里面的才能打開app。不然報錯: -canOpenURL: failed for URL: "OpenAppTest://mark?id=007" - error: "This app is not allowed to query for scheme OpenAppTest"
func openAppButton(){
let button = UIButton()
self.view.addSubview(button)//(必須要先把button加進來,才可以用去寫它的布局)erminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'couldn't find a common superview for <UIButton: 0x136682f20; frame = (0 0; 0 0); opaque = NO; layer = <CALayer: 0x136682e70>> and <UIView: 0x136683900; frame = (0 0; 414 736); autoresize = W+H; layer = <CALayer: 0x136682be0>>'*** First throw call stack:
button.mas_makeConstraints { (make) -> Void in
make.left.equalTo()(self.view).offset()(20)
make.right.equalTo()(self.view).offset()(-20)
make.centerY.equalTo()(self.view)
make.height.equalTo()(40)
}
button.setTitle("打開BasicGrammar", forState: .Normal)
button.setTitleColor(UIColor.cyanColor(), forState: .Normal)
button.setTitleColor(UIColor.greenColor(), forState: .Highlighted)
button.titleLabel?.font = UIFont.systemFontOfSize(18)
//設置button邊框
button.layer.borderColor = UIColor.greenColor().CGColor
button.layer.borderWidth = 2
button.layer.cornerRadius = 10
//button.layer.masksToBounds = true
button.addTarget(self, action: "openApp", forControlEvents: .TouchUpInside)//給button添加action
}
func openApp(){
//記得設置info.plist里面的LSApplicationQueriesSchemes,iOS9之后需要,iOS9之后提高了app的安全性,需要給出一個類似白名單的東西,在白名單里面的才能打開app。不然報錯: -canOpenURL: failed for URL: "OpenAppTest://mark?id=007" - error: "This app is not allowed to query for scheme OpenAppTest"
//OpenAppTest://mark?id=xxxx (調用BasicGrammar app 拼接參數字符串,拼接的時候就像url那樣子 OpenAppTest://標記名字?name=xiaomin&age=23)
let urlStr = "OpenAppTest://mark?id=" + "007"
let customUrl = NSURL(string: urlStr)
if UIApplication.sharedApplication().canOpenURL(customUrl!) {
UIApplication.sharedApplication().openURL(customUrl!)
}else{
//提示沒有安裝 BasicGrammar app
}
}
Test app
Test app
BasicGrammar app
BasicGrammar app