if let url = URL(string: "http://stackoverflow.com/questions/24728854/is-it-possible-to-launch-another-app-in-ios-8-using-swift/") // Change the URL with your URL Scheme
{
if UIApplication.shared.canOpenURL(url)
{
UIApplication.shared.openURL(url)
}
}
func launchTwitterApp() {
guard let url = URL(string: "twitter://user?id=12345") else {
preconditionFailure("There was something wrong with our url, this shouldn't happen")
}
UIApplication.shared.open(url, completion: { success in
if success {
print("We opened the Twitter app.")
}
else {
print("Something went wrong. We might not have the necessary app or the right url.")
}
})
}
let kCustomURLScheme = "DemoDriver://Daffomac.DemoDriver"
func openCustomApp() {
let Url = NSURL(string: kCustomURLScheme)
if UIApplication.shared.canOpenURL(Url! as URL)
{
UIApplication.shared.openURL(Url! as URL)
} else {
//redirect to safari because the user doesn't have Instagram
UIApplication.shared.openURL(NSURL(string: kCustomURLScheme)! as URL)
}
}
5 回答
无论您使用何种语言(Obj-C / Swift),您都可以使用
openURL
打开URL方案来启动应用程序(如果提供了URL) .唯一的方法是使用deep link,应用程序的开发人员必须创建它 .
iOS SDK不允许您的应用与其他应用互动,除非它使用iOS 8中引入的新Extensions framework . 但是,此扩展只允许您在另一个应用中提供自己应用的内容和功能:您无法强制打开其他应用 .
您所描述的内容只能通过非常罕见的深层链接实现,并且必须由您尝试打开的应用程序的开发人员定义 .
因此,例如,您的应用程序中的链接可以打开Pocket应用程序,它允许您保存文章以供以后阅读,使用
pocket://
链接(而不是http://
或https://
),同样,Pebble Smartwatch应用程序可以打开一个pebble://
链接 . 但是,这些是由这些应用程序的开发人员定义的链接,并且此技术不适用于所有应用程序 .我认为您正在寻找Apple URL Schemes . 如果第三方应用程序定义了任何URL Schemes,则可以使用以下代码打开它:
其他人已经在这里描述了正确的想法,但在处理URL和调用函数方面存在一些问题 . 不推荐使用
UIApplication.shared.open(_ url:)
,并将其替换为带有完成处理程序的新版本 .正如其他人所提到的,您需要收件人应用程序定义URL方案 . 如果他们有,你可以做这样的事情:
我们可以通过创建该应用程序的自定义URL来实现此目的,之后我们可以在按钮的单击事件上打开自定义URL .