如何在Swift中使用URL方案获取发件人的ID

时间:2019-04-12 12:42:44

标签: objective-c swift

我正在将一些旧的Objective-C代码转换为Swift。在这里,我正在努力处理一些URL方案。

应用程序委托中的以下Objective-C代码将返回外部应用程序的ID,即通过URL方案发送消息:

- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url
  options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options {

      NSString *appName = [options valueForKey:@"UIApplicationOpenURLOptionsSourceApplicationKey"];
      NSString *urlVal = [url absoluteString];
      NSLog(@"external url scheme call from app %@: %@", appName, urlVal);
      return TRUE;

  }

在Swift中,存在相同的方法,但是在options字典中,不再有关于发送应用程序的信息。而且,我不能打印 外部应用程序的ID:

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

       let appName = options[.sourceApplication]
       let urlVal = url.absoluteString
       NSLog("external url scheme call from %@: %@", appName, urlVal)
       return true

}

所以问题是:如何在上述方法的Swifts实现中获取发送应用程序的ID?

2 个答案:

答案 0 :(得分:1)

下面是您问题的确切答案。选中此密钥options[.sourceApplication]

// --------- OPEN APP WITH URL -----------
func application(_ application: UIApplication,
                 open url: URL,
                 options: [UIApplication.OpenURLOptionsKey : Any] = [:] ) -> Bool {        

    // Determine who sent the URL.
    let sendingAppID = options[.sourceApplication]
    print("source application = \(sendingAppID ?? "Unknown")")

    if let string = sendingAppID as? String, string == "com.apple.springboard" {
        if let components = url.queryCryptoenterDict {
            qRcode(dictionary: components)
        }
        return true // just to quit from function
    }
}

其中qRcode(:)是我的QR码处理程序。

答案 1 :(得分:0)

问题出在Swift中的NSLog。 使用源应用程序的debugDescription属性解决了该问题:

func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
let appName = options[.sourceApplication].debugDescription
let urlVal = url.absoluteString
NSLog("external url scheme call from %@: %@", appName, urlVal)
return true

}