2016-07-15 36 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 ?? "")