Catch up on highlights from Firebase at Google I/O 2023. Learn more

在 iOS 上接收動態鏈接

要接收您創建的Firebase 動態鏈接,您必須在您的應用中包含動態鏈接 SDK,並在您的應用加載時調用handleUniversalLink:dynamicLinkFromCustomSchemeURL:方法以獲取動態鏈接中傳遞的數據。

先決條件

在開始之前,請確保將Firebase 添加到您的 iOS 項目中

使用 Swift Package Manager 安裝和管理 Firebase 依賴項。

  1. 在 Xcode 中,打開您的應用程序項目,導航至File > Add Packages
  2. 出現提示時,添加 Firebase Apple 平台 SDK 存儲庫:
  3.   https://github.com/firebase/firebase-ios-sdk
  4. 選擇動態鏈接庫。
  5. 為了獲得動態鏈接的最佳體驗,我們建議在您的 Firebase 項目中啟用 Google Analytics ,並將適用於 Google Analytics 的 Firebase SDK 添加到您的應用程序中。您可以選擇沒有 IDFA 集合或有 IDFA 集合的庫。
  6. 完成後,Xcode 將自動開始在後台解析和下載您的依賴項。

現在,執行一些配置步驟:

  1. Firebase 控制台中,打開動態鏈接部分。如果系統提示您接受服務條款,請接受。
  2. 確保您的應用程序的 App Store ID 和您的應用程序 ID 前綴已在您的應用程序設置中指定。要查看和編輯您應用的設置,請轉到您的 Firebase 項目的設置頁面並選擇您的 iOS 應用。

    您可以打開以下網址,確認您的 Firebase 項目已正確配置為在您的 iOS 應用程序中使用動態鏈接:

    https://your_dynamic_links_domain/apple-app-site-association

    如果您的應用程序已連接, apple-app-site-association文件將包含對您應用程序的應用程序 ID 前綴和包 ID 的引用。例如:

    {"applinks":{"apps":[],"details":[{"appID":"1234567890.com.example.ios","paths":["NOT /_/*","/*"]}]}}

    如果details字段為空,請仔細檢查您是否指定了 App ID 前綴。請注意,您的 App ID 前綴可能與您的團隊 ID 不同。

  3. 可選:禁用動態鏈接 SDK 對 iOS 粘貼板的使用。

    默認情況下,動態鏈接 SDK 使用粘貼板來提高安裝後深層鏈接的可靠性。通過使用粘貼板,動態鏈接可以確保當用戶打開動態鏈接但需要先安裝您的應用時,用戶在安裝後首次打開應用時可以立即轉到原始鏈接內容。

    這樣做的缺點是使用粘貼板會在 iOS 14 及更高版本上觸發通知。因此,用戶第一次打開您的應用程序時,如果粘貼板包含 URL,他們將看到一條通知,表明您的應用程序訪問了粘貼板,這可能會造成混淆。

    要禁用此行為,請編輯 Xcode 項目的Info.plist文件並將FirebaseDeepLinkPasteboardRetrievalEnabled鍵設置為NO

  1. 在您應用的 Xcode 項目的信息選項卡中,創建一個新的 URL 類型以用於動態鏈接。將標識符字段設置為唯一值,並將URL 方案字段設置為您的包標識符,這是動態鏈接使用的默認 URL 方案。
  2. 在應用的 Xcode 項目的功能選項卡中,啟用關聯域並將以下內容添加到關聯域列表:
    applinks:your_dynamic_links_domain
  3. 如果您想接收具有完全自定義域的動態鏈接,請在您的 Xcode 項目的Info.plist文件中創建一個名為FirebaseDynamicLinksCustomDomains的鍵並將其設置為您應用的動態鏈接 URL 前綴。例如:
    FirebaseDynamicLinksCustomDomains
    
      https://example.com/promos
      https://example.com/links/share
    
    
  4. 在您的UIApplicationDelegate中導入FirebaseCore模塊,以及您的應用委託使用的任何其他Firebase 模塊。例如,要使用 Cloud Firestore 和身份驗證:

    斯威夫特用戶界面

    import SwiftUI
    import FirebaseCore
    import FirebaseFirestore
    import FirebaseAuth
    // ...
          

    迅速

    import FirebaseCore
    import FirebaseFirestore
    import FirebaseAuth
    // ...
          

    目標-C

    @import FirebaseCore;
    @import FirebaseFirestore;
    @import FirebaseAuth;
    // ...
          
  5. 在您的應用委託的application(_:didFinishLaunchingWithOptions:)方法中配置一個FirebaseApp共享實例:

    斯威夫特用戶界面

    // Use Firebase library to configure APIs
    FirebaseApp.configure()

    迅速

    // Use Firebase library to configure APIs
    FirebaseApp.configure()

    目標-C

    // Use Firebase library to configure APIs
    [FIRApp configure];
  6. 如果您使用的是 SwiftUI,則必須創建一個應用程序委託並通過UIApplicationDelegateAdaptorNSApplicationDelegateAdaptor將其附加到您的App結構。您還必須禁用應用委託調配。有關詳細信息,請參閱SwiftUI 說明

    斯威夫特用戶界面

    @main
    struct YourApp: App {
      // register app delegate for Firebase setup
      @UIApplicationDelegateAdaptor(AppDelegate.self) var delegate
    
      var body: some Scene {
        WindowGroup {
          NavigationView {
            ContentView()
          }
        }
      }
    }
          
  7. 接下來,在application:continueUserActivity:restorationHandler:方法中,處理已安裝應用程序時收到的作為通用鏈接的鏈接:

    迅速

    注意:此產品不適用於 macOS、Mac Catalyst、tvOS 或 watchOS 目標。
    func application(_ application: UIApplication, continue userActivity: NSUserActivity,
                     restorationHandler: @escaping ([UIUserActivityRestoring]?) -> Void) -> Bool {
      let handled = DynamicLinks.dynamicLinks()
        .handleUniversalLink(userActivity.webpageURL!) { dynamiclink, error in
          // ...
        }
    
      return handled
    }
    

    目標-C

    注意:此產品不適用於 macOS、Mac Catalyst、tvOS 或 watchOS 目標。
    - (BOOL)application:(UIApplication *)application
    continueUserActivity:(nonnull NSUserActivity *)userActivity
     restorationHandler:
    #if defined(__IPHONE_12_0) && (__IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_12_0)
    (nonnull void (^)(NSArray<id<UIUserActivityRestoring>> *_Nullable))restorationHandler {
    #else
        (nonnull void (^)(NSArray *_Nullable))restorationHandler {
    #endif  // __IPHONE_12_0
      BOOL handled = [[FIRDynamicLinks dynamicLinks] handleUniversalLink:userActivity.webpageURL
                                                              completion:^(FIRDynamicLink * _Nullable dynamicLink,
                                                                           NSError * _Nullable error) {
                                                                // ...
                                                              }];
      return handled;
    }
  8. 最後,在application:openURL:options:處理通過應用的自定義 URL 方案接收的鏈接。當您的應用程序在安裝後首次打開時調用此方法。

    如果在您的應用首次啟動時未找到動態鏈接,將調用此方法並將DynamicLinkurl設置為nil ,表明 SDK 未能找到匹配的待處理動態鏈接。

    迅速

    注意:此產品不適用於 macOS、Mac Catalyst、tvOS 或 watchOS 目標。
    @available(iOS 9.0, *)
    func application(_ app: UIApplication, open url: URL,
                     options: [UIApplication.OpenURLOptionsKey: Any]) -> Bool {
      return application(app, open: url,
                         sourceApplication: options[UIApplication.OpenURLOptionsKey
                           .sourceApplication] as? String,
                         annotation: "")
    }
    
    func application(_ application: UIApplication, open url: URL, sourceApplication: String?,
                     annotation: Any) -> Bool {
      if let dynamicLink = DynamicLinks.dynamicLinks().dynamicLink(fromCustomSchemeURL: url) {
        // Handle the deep link. For example, show the deep-linked content or
        // apply a promotional offer to the user's account.
        // ...
        return true
      }
      return false
    }
    

    目標-C

    注意:此產品不適用於 macOS、Mac Catalyst、tvOS 或 watchOS 目標。
    - (BOOL)application:(UIApplication *)app
                openURL:(NSURL *)url
                options:(NSDictionary<NSString *, id> *)options {
      return [self application:app
                       openURL:url
             sourceApplication:options[UIApplicationOpenURLOptionsSourceApplicationKey]
                    annotation:options[UIApplicationOpenURLOptionsAnnotationKey]];
    }
    
    - (BOOL)application:(UIApplication *)application
                openURL:(NSURL *)url
      sourceApplication:(NSString *)sourceApplication
             annotation:(id)annotation {
      FIRDynamicLink *dynamicLink = [[FIRDynamicLinks dynamicLinks] dynamicLinkFromCustomSchemeURL:url];
    
      if (dynamicLink) {
        if (dynamicLink.url) {
          // Handle the deep link. For example, show the deep-linked content,
          // apply a promotional offer to the user's account or show customized onboarding view.
          // ...
        } else {
          // Dynamic link has empty deep link. This situation will happens if
          // Firebase Dynamic Links iOS SDK tried to retrieve pending dynamic link,
          // but pending link is not available for this device/App combination.
          // At this point you may display default onboarding view.
        }
        return YES;
      }
      return NO;
    }