分享 WhatsApp 的官方文档链接点 这里。
分享 WhatsApp 不需要添加任何的 SDK ,正因为如此,分享接口使用起来不那么的方便。
一、Custom URL Scheme
WhatsApp 有自定义分享接口,可以直接跳进 WhatsApp 内,但只限于分享文字。
将下面的代码添加到你的分享方法中:
NSString *msg = @"YOUR MSG";
NSString *url = [NSString stringWithFormat:@"whatsapp://send?text=%@", [msg stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLHostAllowedCharacterSet]]];
NSURL *whatsappURL = [NSURL URLWithString: url];
if ([[UIApplication sharedApplication] canOpenURL: whatsappURL]) {
[[UIApplication sharedApplication] openURL: whatsappURL];
} else {
// Cannot open whatsapp
}
是不是发现还不能顺利进行分享,并且打印如下信息:
别着急,那是因为你的项目里面没有添加允许访问 WhatsApp 的名单,打开你的 info.plist 文件,添加下面内容:
** 或者 ** 将 info.plist 以 Source Code 方式打开,添加以下代码:
<key>LSApplicationQueriesSchemes</key>
<array>
<string>whatsapp</string>
</array>
这下是不是完美分享出去啦,O(∩_∩)O哈哈哈!
二、Share Extension
其他类型的数据就只能通过 Share Extension 的方式分享了,各种分享方式分别为:
Introduced in iOS 8.0, Share Extension provides a convenient way for any app to share content with other applications installed on user's iPhone.
This is now the preferred way of sharing your content onto WhatsApp.
This is as simple as creating an instance of UIActivityViewController and presenting it in your app.
WhatsApp accepts the following types of content:
- text (UTI: public.plain-text)
- photos (UTI: public.image)
- videos (UTI: public.movie)
- audio notes and music files (UTI: public.audio)
- PDF documents (UTI: com.adobe.pdf)
- contact cards (UTI: public.vcard)
- web URLs (UTI: public.url)
下面我来以分享图片为例:
直接上代码:
** -- in .h file **
<UIDocumentInteractionControllerDelegate>
@property (retain) UIDocumentInteractionController * documentInteractionController;
-- in .m file
if ([[UIApplication sharedApplication] canOpenURL: [NSURL URLWithString:@"whatsapp://app"]]){
UIImage *iconImage = [UIImage imageNamed:@"discover_picture"];
NSString *savePath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/whatsAppTmp.wai"];
[UIImageJPEGRepresentation(iconImage, 1.0) writeToFile:savePath atomically:YES];
_documentInteractionController = [UIDocumentInteractionController interactionControllerWithURL:[NSURL fileURLWithPath:savePath]];
_documentInteractionController.UTI = @"net.whatsapp.image";
_documentInteractionController.delegate = self;
[_documentInteractionController presentOpenInMenuFromRect:CGRectZero inView:self.view animated: YES];
} else {
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:@"whatsapp not installed." preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel handler:nil];
[alertController addAction:cancelAction];
[self.navigationController presentViewController:alertController animated:YES completion:nil];
}
关于 WhatsApp 的分享就以上内容,有错误的地方,欢迎指正。