Open iOS app from URL AND Pass Parameters

后端 未结 2 1426
暖寄归人
暖寄归人 2020-12-15 04:30

A link should open the app. I\'ve got that to work. I just want to know how to pass a parameter. Let\'s say the url is \"addappt://?code=abc\". When a view controller pops u

相关标签:
2条回答
  • 2020-12-15 05:07

    Here is a nice tutorial on Using Custom URL Scheme in iOS

    As in the tutorial, you should parse the URL parameters and store them to use in the app in this method:

    - (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url {
      // Do something with the url here
    }
    
    0 讨论(0)
  • 2020-12-15 05:10

    On Xcode 12 this code works perfectly. You can imagine that this is also a URL as regular. In Source app you can call and open destination url with parameter like

        let url = URL(string: "DestinationApp:PATH?PARAMETER=11111")
               
        UIApplication.shared.open(url!) { (result) in
            if result {
                print(result)
               // The URL was delivered successfully!
            }
        }
    

    Destination app can handle metod in AppDelegate with this method. Alert is for double check.

        func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
                // Determine who sent the URL.
                let sendingAppID = options[.sourceApplication]
                print("source application = \(sendingAppID ?? "Unknown")")
        
                // Process the URL.
                guard let components = NSURLComponents(url: url, resolvingAgainstBaseURL: true),
                    let path = components.path,
                    let params = components.queryItems else {
                        print("Invalid URL or path missing")
                        return false
                }
        
                if let parameter = params.first(where: { $0.name == "PARAMETER" })?.value {
                    print("path = \(path)")
                    print("parameter = \(parameter)")
        
                    let alert = UIAlertController(title: "Path = \(path)", message: "Parameter = \(parameter)", preferredStyle: .alert)
        
                    let keyWindow = UIApplication.shared.windows.filter {$0.isKeyWindow}.first
        
                    if var topController = keyWindow?.rootViewController {
                        while let presentedViewController = topController.presentedViewController {
                            topController = presentedViewController
                        }
        
                        topController.present(alert, animated: true, completion: nil)
                    }
                    return true
                } else {
                    print("parameter is missing")
                    return false
                }
    }
    
    0 讨论(0)
提交回复
热议问题