iOS 教學, iOS進階, 隨筆

Universal Link & URL Scheme

Universal Link & URL Scheme

如果你希望在 App A 按一個按鈕,立即切換至 App B
或是用手機瀏覽網頁時,按一個連結,自動打開 App

這個時候,需要使用的技術有二個,一個叫 URL Scheme, 一個叫 Universal Link,見下圖

這二種技術略有不同,分析如下:

程式範例

iOS URL Scheme (Objective C)
[application openURL:[NSURL URLWithString:@"iotecapp1://page/12"] options:@{}
completionHandler:^(BOOL success) {}];
Universal Link (HTML)
<a href="https://www.iotec.tw/page/12">Open IOTEC App </a>

設定方式

iOS URL Scheme

Xcode > TARGETS > your_app > Info > URL Types 下增加 URL Scheme 為 iotecapp1

Universal Link
  1. Xcode > TARGETS >your_app > Capabilities > Associated Domains 增加 applinks:www.iotec.tw
  2. www.iotec.tw 要支援 HTTPS
  3. 編寫 apple-app-site-association (詳見官方文件)
    註一: 文件類型需為 json且無副檔名
    註二:如果要支援 iOS 8, 還需要 sign 這個檔案,不過現在 iOS 8 (含)以下市佔率不足3%,還是算了吧~
  4. 將 apple-app-site-association 放至 https://www.iotec.tw/ 下 或是
    https://www.iotec.tw/.well-known/下
  5. 到 Apple Developer webpage 去將 App 的 Associated Domain 功能打開

可否接收完整 URL(也就是說,可否傳遞參數?)

iOS URL Scheme &Universal Link

二者皆可。可以取得完整的 URL,把後面的參數部份取出即可。

例: iotecapp1://page/12 後面的 page 與 12 等等即可傳遞參數

觸發方法 (iOS Objective C, AppDelegate.m)

URL Scheme
- (BOOL)application:(UIApplication *) application  openURL:(NSURL *)url
      options: (NSDictionary <UIApplicationOpenURLOptionsKey, id>*)options;
Universal Link
-(BOOL) application:(UIApplication *)application
          continueUserActivity:(NSUserActivity *)userActivity
          restorationHandler:(void (^)(NSArray * _Nullable))restorationHandler;

從網頁觸發時,如果沒有裝 App, 可否導向指定網頁?

URL Scheme

Partially YES
可以用 Timeout 方式處理,但不是 100% 成功

Universal Link

可以無縫接軌

可否從 APP 觸發?

URL Scheme

沒有問題,還可以判斷另一個 APP 是否有安裝


    [application openURL:URL options:@{} completionHandler:^(BOOL success) {
        if (success) {
            NSLog(@"Opened URL Scheme %@",scheme);
        }else{
            NSLog(@"Opened URL Scheme %@ FAILED",scheme);
        }
    }];
Universal Link

有些情況下可能有問題

用 UIWebview 或是用 SFSafariViewController 開啟 Universal Link
在官方文件上似乎是不建議的作法,
有文章提到 UIWebView 裡必需要在切換 domain 時才會觸發 Universal
Link。實際上會發生什麼事還需要有用過的人交流一下。

安全性?

URL Scheme

因為任何 APP 都可以註冊自己處理 iotecapp1的
prefix 的 URL Scheme,這會有潛在性的安全問題。
Ex: 如果您的官網透過 URL Scheme 來開啟您的 APP,使用的 URL Scheme prefix 為
“yellow://…”, 而很不巧的剛好有個限制級 APP 也使用 yellow 作為 URL Scheme prefix,
那麼就會有機率開錯了 App…
雖然手機上為何會裝該 APP 使用者本身也要負一點責任…. 不過這邊的行為與設計原意就不一致了

Universal Link

相對安全很多

參考官方文件
Support Universal Links

Communicating with Other Apps Using Custom URLs

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.