且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

自定义网址方案到本机应用程序或网站

更新时间:2022-12-21 10:23:58

不幸的是,iOS上的自定义URL处理程序无法正常工作.

Unfortunately custom URL handlers on iOS don't work that way.

您可以定义将打开您的应用程序的自定义URL 方案,但是您不能将您的应用程序指定为某些域名的指定处理程序,因此在Safari中打开该域将自动启动您的应用程序.

You can define custom url schemes that will open your app, but you can't make your app the designated handler for certain domain names so that opening that domain in Safari will launch your app automatically.

要清楚一点,方案是域名前面的一位,例如 http:,因此您可以使您的应用成为以 myapp:开头的网址的处理程序例子.显然,除了您专门设计用于应用程序的URL以外,没有真正的URL以 myapp:开头.

To be clear, a scheme is the bit before the domain name, like http:, so you could make your app the handler for urls that start myapp: for example. Obviously no real URLs start with myapp: except for ones that you've designed specifically to be used with your app - that's the whole point.

不幸的是,这些URL仅适用于您的应用程序,如果未安装您的应用程序,则无法在Safari中打开它们. iTunes,Google地图,***等都可以在iPhone上以这种方式工作,因为Apple已将它们硬编码为特殊情况,但它们并未将此机制提供给第三方应用程序.

Unfortunately these URLs will only work with your app, they can't be opened in Safari if your app isn't installed. iTunes, Google maps, ***, etc all work that way on iPhone because Apple has hard-coded them as special cases, but they don't make this mechanism available to third party apps.

要为您的应用注册自定义方案,请遵循以下教程:

To register a custom scheme for your app, follow this tutorial: http://iosdevelopertips.com/cocoa/launching-your-own-application-via-a-custom-url-scheme.html

您可能可以做的是建立一个常规网页,该网页使用javascript检测设备的用户代理,如果是iPhone,则可以使用document.location ='myapp自动重定向到应用的自定义方案网址: ...'.我不确定如果未安装该应用程序时尝试重定向到自定义URL方案,会发生什么情况.它可能无能为力,这对您来说很理想,或者可能会引发错误或进入空白页,在这种情况下,***弹出一条消息,例如单击此处以启动应用程序或单击此处以从应用商店下载它",这似乎是大多数网站的做法.

What you may be able to do instead is set up a regular web page which uses javascript to detect the user agent of the device and if it's an iPhone redirect to the app's custom scheme url automatically using document.location = 'myapp:...'. I'm not sure what happens if you try to redirect to a custom url scheme if the app's not installed though. It may do nothing, which would be ideal for you, or it may throw up an error or go to a blank page in which case you'd be better off popping up a message like "click here to launch the app or click here to download it from the app store", which is what most sites seem to do.