2016-04-18 28 views
3

有两个测试应用程序称为发件人&接收器在swift中通过url方案在两个应用之间传递数据?

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

详细了解字符串:

我都在发件人创建文本框和接收器,我将文字发件人文本字段的一些字符串。当我点击按钮时,字符串将显示在Receiver Textfield上。

It seems that I have to implement NSNotificationCenter.defaultCenter().postNotificationName in my Apps 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 
    } 
} 

,我只可以显示有关的URL like this信息

image2

希望得到一些建议!

回答

4

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

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键1 =值& 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方案。例如:iOSTest://?textSent =“Hello World”

+0

完美答案!很酷,在计划之后添加一个查询。 – HungCLo

+0

很好的答案。如果你想传递字符串以外的数据,你应该添加关于base64的信息。 –

+0

很好的答案,很好的解释和一个明确的例子。 – Josh

0

当然可以。你只需撰写应用程序启动和URL参数传递这样

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

,然后分析它在UIApplicationDelegate

相关问题