2016-07-15 63 views
0

我想在我的應用程序中打開一個WhatsApp URL,這是我在Swift中創建的。對於WhatsApp的URL模式是Swift encode WhatsApp URL

whatsapp://send?text= 

和我的代碼如下所示:

 let originalMessage = NSLocalizedString("Open following url ", comment: "") + " " + "http://<url>.<com>/?=test" 
     let escapedMessage = originalMessage.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLHostAllowedCharacterSet())! 

     // Check if url will be opened 
     guard let whatsAppUrl = NSURL(string: "whatsapp://send?text=" + escapedMessage) else { 
      print("error") 
      return 

     } 

     // Open whatsapp url 
     if UIApplication.sharedApplication().canOpenURL(whatsAppUrl) { 
      print("ok") 
     } 

我的問題是,我在我的字符串,我用了WhatsApp打開一個問號「?」。我試圖逃避這樣的字符:

"whatsapp://send?text=\"" + escapedMessage + "\"" 

但是,如果我在WhatsApp中打開URL,我會得到一個空字符串。有人可以幫助我或爲我提示嗎?

+0

''whatsapp:// send?text = \「」+ escapedMessage +「\」「'永遠不要這樣做。像這樣手工構建URL字符串總是錯誤的。使用NSURLComponents和NSURLQuery;這就是他們的目標。 – matt

回答

0

嘗試發送靜態的URL是這樣的:

Objective-C的調用打開其中一個網址如下:

NSURL *whatsappURL = [NSURL URLWithString:@"whatsapp://send?text=Hello%2C%20World!"]; 
if ([[UIApplication sharedApplication] canOpenURL: whatsappURL]) { 
    [[UIApplication sharedApplication] openURL: whatsappURL]; 
} 

在斯威夫特:

let whatsappURL = NSURL(string:"whatsapp://send?text=Hello%2C%20World!") 
if (UIApplication.sharedApplication().canOpenURL(whatsappURL!)) { 
    UIApplication.sharedApplication().openURL(whatsappURL!); 
} 

從鏈接:

I integrate WhatsApp into my app

0

我認爲URLComponent是解決它的最好方法。

let whatsAppHookup = "whatsapp://send" 
let address = "https://www.swift.org/?page=1" 
var urlComponent = URLComponents(string: whatsAppHookup) 
let queryItem = URLQueryItem(name: "text", value: address) 
urlComponent?.queryItems = [queryItem] 

let url = urlComponent?.url 
print(url?.absoluteString ?? "")