分享 WhatsApp 的官方文檔鏈接點(diǎn) 這里猎唁。
分享 WhatsApp 不需要添加任何的 SDK 缺前,正因?yàn)槿绱耍窒斫涌谑褂闷饋?lái)不那么的方便著摔。
一、Custom URL Scheme
WhatsApp 有自定義分享接口定续,可以直接跳進(jìn) WhatsApp 內(nèi)谍咆,但只限于分享文字。
將下面的代碼添加到你的分享方法中:
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
}
是不是發(fā)現(xiàn)還不能順利進(jìn)行分享私股,并且打印如下信息:
別著急摹察,那是因?yàn)槟愕捻?xiàng)目里面沒有添加允許訪問 WhatsApp 的名單,打開你的 info.plist 文件倡鲸,添加下面內(nèi)容:
** 或者 ** 將 info.plist 以 Source Code 方式打開供嚎,添加以下代碼:
<key>LSApplicationQueriesSchemes</key>
<array>
<string>whatsapp</string>
</array>
這下是不是完美分享出去啦,O(∩_∩)O哈哈哈峭状!
二克滴、Share Extension
其他類型的數(shù)據(jù)就只能通過(guò) 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)
下面我來(lái)以分享圖片為例:
直接上代碼:
** -- 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];
}
關(guān)于 WhatsApp 的分享就以上內(nèi)容宁炫,有錯(cuò)誤的地方偿曙,歡迎指正。