简体   繁体   中英

Swift 5 handle Universal Links

I've implemented Universal Links in my app and it opens when specific links are clicked in emails, messages etc.

Now I'm trying to handle this events but with no success at this point.

Any ideas what am I doing wrong?

Here's a part of what I've tried so far in my AppDelegate :

import Firebase
import FirebaseMessaging
import UserNotificationsUI
import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, MessagingDelegate, NSUserActivityDelegate {
    
    // ... register for notifications

   func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([UIUserActivityRestoring]?) -> Void) -> Bool 
   {
       print("Test 1") // Doesn't print anything
       return true
   }

   func application(application: UIApplication, continueUserActivity userActivity: NSUserActivity, restorationHandler: ([AnyObject]?) -> Void) -> Bool
   {
       print("Test 2") // Doesn't print anything
       return true
   }
        
}

extension AppDelegate: UNUserNotificationCenterDelegate {
    
    // ... handle notifications
    
}

PS I'm using Swift 5 on xCode 14

I had the same problem, the problem is that you have a SceneDelegate, because of this the AppDelegate methods are not called.

Implement the following methods in your SceneDelegate to handle Universal Links when the app is already running and when it is not launched yet:

//This method is called when app is NOT running in the background.
//Easy to test with fatalError()
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
    guard let _ = (scene as? UIWindowScene) else { return }
    
    if let userActivity = connectionOptions.userActivities.first {
        debugPrint("userActivity: \(userActivity.webpageURL)")
        fatalError()
    }
}

//This method is called when app is running in the background.
//Easy to test with debugPrint
func scene(_ scene: UIScene, continue userActivity: NSUserActivity) {
    
    debugPrint("userActivity: \(userActivity.webpageURL)")
}

From there, do whatever you need to handle the links.

Hope it helps:)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM