如何从 Mobile Safari 重定向到原生 iOS 应用程序(如 Quora)?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9688319/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to redirect from Mobile Safari to Native iOS app (like Quora)?
提问by Callmeed
On my iPhone, I just noticed that if I do a Google Search (in Mobile Safari) and select a result on quora.com, the result page launches the native Quora app on my phone.
在我的 iPhone 上,我刚刚注意到,如果我进行 Google 搜索(在 Mobile Safari 中)并在 quora.com 上选择一个结果,结果页面会在我的手机上启动本地 Quora 应用程序。
How is this done? Specifically, is it a detection of the user agent and the use of an iOS URL scheme? Can it tell if the native app is installed and/or redirect to the app store?
这是怎么做的?具体来说,是不是对用户代理的检测和iOS URL方案的使用?它可以判断是否安装了本机应用程序和/或重定向到应用程序商店吗?
回答by padi
I'm reposting an answer to my own related (but was originally Ruby-on-Rails-specific) question from here: Rails: redirect_to 'myapp://' to call iOS app from mobile safari
我正在从这里重新发布我自己的相关(但最初是 Ruby-on-Rails 特定的)问题的答案:Rails: redirect_to 'myapp://' to call iOS app from mobile safari
You can redirect using javascript window.location
.
您可以使用 javascript 重定向window.location
。
Sample code:
示例代码:
<html><head>
<script type="text/javascript">
var userAgent = window.navigator.userAgent;
if (userAgent.match(/iPad/i) || userAgent.match(/iPhone/i)) {
window.location = "myiosapp://"
}
</script>
</head>
<body>
Some html page
</body>
</html>
回答by Loki
Just a small improvement of the JS code, if the app is not installed, it will send the user to itunes store ;)
只是对 JS 代码的一个小改进,如果未安装该应用程序,它会将用户发送到 iTunes 商店 ;)
<script type="text/javascript">
// detect if safari mobile
function isMobileSafari() {
return navigator.userAgent.match(/(iPod|iPhone|iPad)/) && navigator.userAgent.match(/AppleWebKit/)
}
//Launch the element in your app if it's already installed on the phone
function LaunchApp(){
window.open("Myapp://TheElementThatIWantToSend","_self");
};
if (isMobileSafari()){
// To avoid the "protocol not supported" alert, fail must open itunes store to dl the app, add a link to your app on the store
var appstorefail = "https://itunes.apple.com/app/Myapp";
var loadedAt = +new Date;
setTimeout(
function(){
if (+new Date - loadedAt < 2000){
window.location = appstorefail;
}
}
,100);
LaunchApp()
}
</script>
回答by Perception
You can do trigger your application to be launched using custom URL scheme, registered by your application with the iOS runtime. Then on your website, write code to detect the incoming User-Agent and if iOS is detected generate your custom URL's instead of regular http ones.
您可以使用自定义 URL scheme触发您的应用程序启动,由您的应用程序向 iOS 运行时注册。然后在您的网站上,编写代码来检测传入的 User-Agent,如果检测到 iOS,则生成您的自定义 URL,而不是常规的 http。