2013-07-31 45 views
7

我想用WhatsApp的自定义URL方案发送一些伴随URL的文本。有显然只有一个用于此目的的有效参数:text使用WhatsApp URL方案发送URL旁边的文字

NSURL *whatsappURL = [NSURL URLWithString:@"whatsapp://send?text=Hello%2C%20World!"]; 

问题是当我想要我自己的URL追加到该文本。我选择用编码它这样的:

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

的URL发送到WhatsApp的旁边的文字,但它没有得到解码上的W​​hatsApp的一面:

WhatsApp not decoding the URL

任何想法?谢谢!

回答

10

您正在接近它,但看起来URL是双重编码的。确保邮件和网址只能编码一次。

使用你的相同的编码方法,你可以做一些像这样:

NSString *urlAbsoluteString = @"Hello World! http://yayvisitmysiteplease.com?funky=parameter&stuff"; 
NSString *encodedURLString = ... 

这应该给你执行的网址:

whatsapp://send?text=Hello%20World%21%20http%3A%2F%2Fyayvisitmysiteplease.com%3Ffunky%3Dparameter%26stuff 

这使得它的方式进入了WhatsApp就像你” d期望。 (我验证,以双重肯定。)

+0

OMG发送文字和网址!就是这样!我在编码调用之后有一个“隐藏”的'stringByAddingPercentEscapesUsingEncoding:'调用... OMG ...谢谢! – Sendoa

10

这是完整的代码都在WhatsApp的

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]; 
    } 
+1

这对我不起作用 – Jitendra

+1

这对我有用,而接受的答案某种程度上没有。 –

+0

谢谢。 @MuratÖgat –

2

它将为分享链接上工作请告诉我应用

NSString * url = [NSString stringWithFormat:@"http://video...bla..bla.."]; 
url = (NSString*)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(NULL,(CFStringRef) url, NULL,CFSTR("!*'();:@&=+$,/?%#[]"),kCFStringEncodingUTF8)); 

NSString * urlWhats = [NSString stringWithFormat:@"whatsapp://send?text=%@",url]; 
NSURL * whatsappURL = [NSURL URLWithString:urlWhats]; 
if ([[UIApplication sharedApplication] canOpenURL: whatsappURL]) { 
[[UIApplication sharedApplication] openURL: whatsappURL]; 
} else { 
// can not share with whats app 
}