2013-07-31 83 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 
}