2016-04-18 66 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

相關問題