分享到WhatsApp
現在越來越多的APP支援國外使用者,所以常常會遇到國際化的問題,其中就包含分享至Facebook、Twitter、WhatsApp的需求。
但是國內的一些分享整合SDK,如友盟分享,並沒有經過大量資料的檢測驗證,也沒有資料支援可以適應國外不同的網路環境。所以最保守的做法,就是直接整合第三方的SDK。
下面列舉是幾個比較常見的整合文件:
但是有一些APP,如WhatsApp,是沒有官方的SDK,做起來會比較麻煩,也支援不了那麼多的情況,在這裡做一個補充分析:
1、新增白名單:
plist檔案中新增程式碼段:
<key>LSApplicationQueriesSchemes</key> <array> <string>whatsapp</string> </array>
2、分享文字(或者是分享連結,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 }
3、分享圖片:
WhatsApp沒有實現圖片或者其他多媒體的分享,所以只能通過UIDocumentInteractionController的方式,去到APP內開啟檔案的方式以實現分享。
具體實現文件請移至官方迴應 ,這裡我以圖片分享為例:
if ([[UIApplication sharedApplication] canOpenURL: [NSURL URLWithString:@"whatsapp://app"]]){ UIImage* iconImage = [UIImage imageNamed:@"YOUR IMAGE"]; 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:CGRectMake(0, 0, 0, 0) inView:self.view animated: YES]; } else { UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"WhatsApp not installed." message:@"Your device has no WhatsApp installed." delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil]; [alert show]; }