Swift编码WhatsApp URL

时间:2016-07-15 16:53:16

标签: swift

我想在我的应用程序中打开WhatsApp URL,我在Swift中创建。 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,我会得到一个空字符串。有人可以帮我或暗示一下吗?

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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 ?? "")
相关问题