使用WhatsApp分享链接

18

我尝试使用这些代码在WhatsApp中分享应用链接,但是没有任何内容显示在WhatsApp的文本框中。如果只是使用简单的文本,则可以正常工作。有人能建议最终结果吗?

NSString *theTempMessage = @"whatsapp://send?text=https://itunes.apple.com/in/app/myapp/id1054375332?ls=1&mt=8";
NSString *theFinalMessage;

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

NSString * stringToSend=theFinalMessage;
NSURL *whatsappURL = [NSURL URLWithString:stringToSend];

if ([[UIApplication sharedApplication] canOpenURL: whatsappURL])

{
    [[UIApplication sharedApplication] openURL: whatsappURL];
}

为什么要使用字符串替换? - satheesh
2个回答

10

将此内容添加到您的 Info.plist 文件中

<key>LSApplicationQueriesSchemes</key>
    <array>
        <string>whatsapp</string>
    </array>

在需要打开WhatsApp进行分享的ViewController中实现此代码(例如,一个按钮操作)。 Swift 3版本更新(Xcode 8.x):已更新弃用内容


Swift 3版本更新(Xcode 8.x):已更新弃用内容
var str = "This is the string which you want to share to WhatsApp"
str=str.addingPercentEncoding(withAllowedCharacters: (NSCharacterSet.urlQueryAllowed))!
let whatsappURL = URL(string: "whatsapp://send?text=\(str)")
if UIApplication.shared.canOpenURL(whatsappURL) {
   UIApplication.shared.open(whatsappURL!, options: [:], completionHandler: nil)
} else {
   showAlert(message: "Whatsapp is not installed on this device. Please install Whatsapp and try again.")
}

这里的showAlert()是用于显示警报的自定义函数。


2
由于在iOS 10中openURL已被弃用,您需要使用open代替:UIApplication.shared.open(whatsappURL!, options: [:], completionHandler: nil) - Felix
谢谢 :) 很好的分享 - Ankit Kumar Gupta
1
感谢您的回答。 - Nikhil Manapure

1
如果您在字符串替换后使用“[[UIApplication sharedApplication] openURL: whatsappURL];”,它将打开Safari浏览器而不是WhatsApp,
如果您想要打开WhatsApp,请不要替换字符串。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接