通过swift中的url方案在两个Apps之间传递数据?
有两个名为Sender&Receiver的测试应用程序
他们通过Url Scheme相互沟通。 我想从Sender发送一个字符串给Receiver,这可能吗?
关于字符串的细节:
我都在Sender和Receiver中创建Textfields,我会在Sender Textfield上发一些字符串。 单击按钮时,字符串将显示在Receiver Textfield上。
我似乎必须在我的应用程序接收器中实现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 }
在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的信息
希望得到一些建议!
是的,您可以使用查询字符串。
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 =值。 我正在编写代码来解析它,但请确保为您的案例测试它:
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”
当然可以。 您只需撰写应用启动url并传递此类参数即可
iOSTest://?param1=Value1¶m2=Valuew
然后在UIApplicationDelegate中解析它