2

How does one handle custom URL schemes to allow one app to be directed to another? e.g. instagram://user?username=someusername which directs a user straight to the users profile via username. I need to create something similar.

I've checked out application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) -> Bool and application(_ application: UIApplication, handleOpen url: URL) -> Bool but they seem to have a red line through when attempting to implement so I assume they are deprecated. Also, they don't seem to get called when I open my app via url from a browser.

luke
  • 2,743
  • 4
  • 19
  • 43

2 Answers2

3

Using this url as an example: appName://?id=12345

You can do something in your app once launched using the url like so

func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool {
    let urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: false)
    if let items = urlComponents?.queryItems as [NSURLQueryItem]?,
        (url.scheme == "appName") {
        if items.first?.name == "id",
            let id = items.first?.value {
            print(id) // prints 12345 to console
            // do something with the id, possibly present/push a controller for the user
        }
    }
    return false
}
luke
  • 2,743
  • 4
  • 19
  • 43
2

From iOS 13 and above below function will no longer work.

func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool

Updated function from iOS 13 and above

 func scene(_ scene: UIScene, openURLContexts URLContexts: Set<UIOpenURLContext>)

Use this function in SceneDelegate class.
Credit: https://www.swiftdevcenter.com/custom-url-scheme-deep-link-ios-13-and-later-swift-5/
For more detail follow this tutorial

Ashish Chauhan
  • 1,316
  • 15
  • 22