使用WhatsApp URL方案在文本旁边发送URL

Sen*_*doa 7 cocoa objective-c ios whatsapp

我正在尝试使用WhatsApp的自定义URL方案发送一些带有URL的文本.为此目的,显然只有一个有效参数text:

NSURL *whatsappURL = [NSURL URLWithString:@"whatsapp://send?text=Hello%2C%20World!"];
Run Code Online (Sandbox Code Playgroud)

当我想将自己的URL附加到该文本时,就会出现问题.我选择使用它编码它:

NSString *encodedURLString = (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(
                                                                                  NULL,
                                                                                  (CFStringRef)urlAbsoluteString,
                                                                                  NULL,
                                                                                  (CFStringRef)@"!*'();:@&=+$,/?%#[]",
                                                                                  kCFStringEncodingUTF8 ));
Run Code Online (Sandbox Code Playgroud)

该URL与文本一起发送到WhatsApp,但不会在WhatsApp方面解码:

WhatsApp没有解码URL

有任何想法吗?谢谢!

小智 10

您正确地接近它,但似乎URL正在进行双重编码.确保消息和URL仅编码一次.

使用相同的编码方法,您可以执行以下操作:

NSString *urlAbsoluteString = @"Hello World! http://yayvisitmysiteplease.com?funky=parameter&stuff";
NSString *encodedURLString = ...
Run Code Online (Sandbox Code Playgroud)

这应该给你执行的URL:

whatsapp://send?text=Hello%20World%21%20http%3A%2F%2Fyayvisitmysiteplease.com%3Ffunky%3Dparameter%26stuff
Run Code Online (Sandbox Code Playgroud)

这就像你期望的那样进入WhatsApp.(我证实了双重确定.)


Jay*_*ani 10

这是在WhatsApp中发送文本和URL的完整代码

    NSString * msg = @"Application%20Name%20https://itunes.apple.com/YOUR-URL";

    msg = [msg stringByReplacingOccurrencesOfString:@":" withString:@"%3A"];
    msg = [msg stringByReplacingOccurrencesOfString:@"/" withString:@"%2F"];
    msg = [msg stringByReplacingOccurrencesOfString:@"?" withString:@"%3F"];
    msg = [msg stringByReplacingOccurrencesOfString:@"," withString:@"%2C"];
    msg = [msg stringByReplacingOccurrencesOfString:@"=" withString:@"%3D"];
    msg = [msg stringByReplacingOccurrencesOfString:@"&" withString:@"%26"];

    NSString * urlWhats = [NSString stringWithFormat:@"whatsapp://send?text=%@",msg];
    NSURL * whatsappURL = [NSURL URLWithString:urlWhats];
    if ([[UIApplication sharedApplication] canOpenURL: whatsappURL])
    {
        [[UIApplication sharedApplication] openURL: whatsappURL];
    }
    else
    {
        UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"WhatsApp not installed." message:@"Your device has no WhatsApp installed." delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [alert show];
    }
Run Code Online (Sandbox Code Playgroud)