通过swift中的url方案在两个Apps之间传递数据?

时间:2016-04-18 08:24:52

标签: ios swift url-scheme pass-data

有两个测试应用程序称为Sender&接收器

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

有关字符串的详细信息:

我都在Sender和Receiver中创建Textfields,我会在Sender Textfield上发一些字符串。单击按钮时,字符串将显示在Receiver Textfield上。

It seems that I have to implement NSNotificationCenter.defaultCenter().postNotificationName in my Apps Receiver

这是我的App Receiver代码:

在Appdelegate中

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

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

在viewController中

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

现在,我只能显示有关网址like this

的信息

image2

希望得到一些建议!

2 个答案:

答案 0 :(得分:8)

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

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 = value1& key2 = value2。我正在编写代码来解析它,但请确保根据您的情况进行测试:

    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附加到scheme。例如:iOSTest://?textSent =“Hello World”

答案 1 :(得分:2)

当然可以。您只需撰写应用启动网址并传递此类参数

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

然后在UIApplicationDelegate中解析它