在Swift中通过URL方案在两个应用程序之间传递数据?

13

有两个名为Sender和Receiver的测试应用程序

它们通过URL方案相互通信。我想从Sender发送一个字符串到Receiver,这可行吗?

关于该字符串的详细信息:

我在Sender和Receiver中都创建了文本字段,我会在Sender文本字段上输入一些字符串。当我单击按钮时,字符串将显示在Receiver文本字段上。

似乎我必须在我的应用程序Receiver中实现NSNotificationCenter.defaultCenter().postNotificationName

这是我的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
}

在视图控制器中

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的信息像这样

image2

希望得到一些建议!
2个回答

阿里云服务器只需要99元/年,新老用户同享,点击查看详情
12

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

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

通常我们也使用URLScheme进行深度链接,因此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!)
        }
    }

参数将包含查询字符串中的所有键值对。

希望这有所帮助:]

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


不错的回答。如果你想传递一些除字符串以外的数据,你应该添加关于base64的信息。 - Michaël Azevedo
很棒的答案,解释得非常清楚,并且有一个明确的例子。 - Josh
3
可以将对象(数组/字典)传递给另一个应用程序吗? - user3752049

3
当然可以。您只需要编写应用启动URL并像这样传递参数即可。
iOSTest://?param1=Value1&param2=Valuew

然后在UIApplicationDelegate中解析它


但是这个链接无法点击。当我试图将此URL分享到另一个应用程序,例如WhatsApp时。那么它就无法点击。如何使其可点击? - Amanpreet
在这种情况下,可能通用链接会对您有所帮助。https://dev59.com/d1sV5IYBdhLWcg3w8imr - heximal

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,