12

有两个测试应用程序称为 Sender & Receiver

它们通过 Url Scheme 相互通信。我想从 Sender 向 Receiver 发送一个字符串,这可能吗?

关于字符串的详细信息:

我都在发件人和收件人中创建文本字段,我会在发件人文本字段上发送一些字符串。当我单击按钮时,字符串将显示在接收方文本字段上。

看来我必须在我的 Apps Receiver 中实现 NSNotificationCenter.defaultCenter().postNotificationName

这是我的应用程序接收器代码:

在 Appdelegate 中

func application(application: UIApplication, openURL url: NSURL, sourceApplication: String?, annotation: AnyObject) -> Bool {

    calledBy = sourceApplication
    fullUrl = url.absoluteString
    scheme = url.scheme
    query = url.query
}

在视图控制器中

override func viewDidLoad() {
    super.viewDidLoad()

    NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(ViewController.displayLaunchDetails), name: UIApplicationDidBecomeActiveNotification, object: nil)
    // Do any additional setup after loading the view, typically from a nib.
}

func displayLaunchDetails() {
    let receiveAppdelegate = UIApplication.sharedApplication().delegate as! AppDelegate
    if receiveAppdelegate.calledBy != nil {
        self.calledByText.text = receiveAppdelegate.calledBy
    }
    if receiveAppdelegate.fullUrl != nil {
        self.fullUrlText.text = receiveAppdelegate.fullUrl
    }
    if receiveAppdelegate.scheme != nil {
        self.schemeText.text = receiveAppdelegate.scheme
    }
    if receiveAppdelegate.query != nil {
        self.queryText.text = receiveAppdelegate.query
    }
}

现在,我只能像这样显示有关 url 的信息

图2

希望能得到一些建议!

4

2 回答 2

11

是的,您可以使用查询字符串。

url.query 包含查询字符串。例如,在 URL iOSTest://www.example.com/screen1?textSent="Hello World"中,查询字符串为textSent="Hello World"

通常我们也使用 URLSchemes 进行深度链接,因此 URLScheme 指定要打开哪个应用程序,并且 url 中的路径指定要打开哪个屏幕,并且查询字符串具有我们要发送到应用程序的附加参数。

url.query是一个字符串,因此您必须对其进行解析以获得所需的值:例如,在 URL iOSTest://www.example.com/screen1?key1=value1&key2=value2 中,查询字符串为 key1 =值1&键2=值2。我正在编写代码来解析它,但请确保您针对您的情况对其进行测试:

    let params = NSMutableDictionary()
    let kvPairs : [String] = (url.query?.componentsSeparatedByString("&"))!
    for param in  kvPairs{
        let keyValuePair : Array = param.componentsSeparatedByString("=")
        if keyValuePair.count == 2{
            params.setObject(keyValuePair.last!, forKey: keyValuePair.first!)
        }
    }

params 将包含查询字符串中的所有键值对。希望能帮助到你 :]

如果您不想进行深度链接,可以直接将 queryString 附加到方案中。例如:iOSTest://?textSent="Hello World"

于 2016-04-18T09:06:07.677 回答
3

当然可以。您只需编写您的应用启动 URL 并像这样传递参数

iOSTest://?param1=Value1&param2=Valuew

然后在 UIApplicationDelegate 中解析它

于 2016-04-18T08:51:25.643 回答