从URL和Pass Parameters打开iOS应用程序

时间:2013-01-09 02:14:12

标签: objective-c ios parameters url-scheme

链接应该会打开应用。我有这个工作。我只是想知道如何传递参数。假设网址是“addappt://?code = abc”。弹出视图控制器时,代码字段应填充文本 - 等于符号后的字母。我有部分工作要做。我使用以下(in app delegate.m)

NSArray *elements = [url.query componentsSeparatedByString:@"="];
NSString *key = [[elements objectAtIndex:0] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
          val = [[elements objectAtIndex:1] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

(顺便说一下:val在appdelegate.h中声明

我也可以将val传递给视图控制器。我唯一的问题是填充名为'code'的文本字段。一旦应用程序被链接打开,您如何填充代码?

帮助感谢。

2 个答案:

答案 0 :(得分:22)

这是关于Using Custom URL Scheme in iOS

的精彩教程

在教程中,您应解析URL参数并将其存储在此方法的应用程序中使用:

- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url {
  // Do something with the url here
}

答案 1 :(得分:0)

在Xcode 12上,此代码可以完美运行。您可以想象这也是常规的URL。在“源”应用中,您可以使用以下参数调用并打开目标网址

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

目标应用程序可以使用此方法处理AppDelegate中的方法。警报用于再次检查。

    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
            }
}