Можно ли обмениваться изображениями, текстом или чем угодно через Whatsapp в приложении для iOS? Я ищу в Google, но я нашел только результаты, говорящие о реализации Android.
Доля изображения/текста через WhatsApp в приложении iOS
Ответ 1
Нет, это невозможно, у whatsapp нет публичного API, который вы можете использовать.
Обратите внимание, что этот ответ верен в 2011 году, когда API для WhatsApp не был.
Теперь есть api, доступный для взаимодействия с WhatsApp: http://www.whatsapp.com/faq/en/iphone/23559013
Вызов Objective-C для открытия одного из этих URL-адресов выглядит следующим образом:
NSURL *whatsappURL = [NSURL URLWithString:@"whatsapp://send?text=Hello%2C%20World!"];
if ([[UIApplication sharedApplication] canOpenURL: whatsappURL]) {
[[UIApplication sharedApplication] openURL: whatsappURL];
}
Ответ 2
Теперь это возможно:
Отправить текст - Obj-C
NSString * msg = @"YOUR MSG";
NSString * urlWhats = [NSString stringWithFormat:@"whatsapp://send?text=%@",msg];
NSURL * whatsappURL = [NSURL URLWithString:[urlWhats stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
if ([[UIApplication sharedApplication] canOpenURL: whatsappURL]) {
[[UIApplication sharedApplication] openURL: whatsappURL];
} else {
// Cannot open whatsapp
}
Отправить текст - Swift
let msg = "YOUR MSG"
let urlWhats = "whatsapp://send?text=\(msg)"
if let urlString = urlWhats.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet()) {
if let whatsappURL = NSURL(string: urlString) {
if UIApplication.sharedApplication().canOpenURL(whatsappURL) {
UIApplication.sharedApplication().openURL(whatsappURL)
} else {
// Cannot open whatsapp
}
}
}
Отправить изображение - Obj-C
- в .h файле
<UIDocumentInteractionControllerDelegate>
@property (retain) UIDocumentInteractionController * documentInteractionController;
- в .m файле
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];
}
Отправить изображение - Swift
let urlWhats = "whatsapp://app"
if let urlString = urlWhats.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet()) {
if let whatsappURL = NSURL(string: urlString) {
if UIApplication.sharedApplication().canOpenURL(whatsappURL) {
if let image = UIImage(named: "image") {
if let imageData = UIImageJPEGRepresentation(image, 1.0) {
let tempFile = NSURL(fileURLWithPath: NSHomeDirectory()).URLByAppendingPathComponent("Documents/whatsAppTmp.wai")
do {
try imageData.writeToURL(tempFile, options: .DataWritingAtomic)
self.documentInteractionController = UIDocumentInteractionController(URL: tempFile)
self.documentInteractionController.UTI = "net.whatsapp.image"
self.documentInteractionController.presentOpenInMenuFromRect(CGRectZero, inView: self.view, animated: true)
} catch {
print(error)
}
}
}
} else {
// Cannot open whatsapp
}
}
}
Поскольку новая функция безопасности iOS 9, вам нужно добавить эти строки в .plist:
<key>LSApplicationQueriesSchemes</key> <array> <string>whatsapp</string> </array>
Дополнительная информация о url sheme: https://developer.apple.com/videos/play/wwdc2015-703/
Я не нашел ни одного решения для обоих. Дополнительная информация о http://www.whatsapp.com/faq/en/iphone/23559013
Я сделал небольшой проект, чтобы помочь кому-то. https://github.com/salesawagner/SharingWhatsApp
Ответ 3
Теперь это возможно. Хотя еще не пробовал.
В последних примечаниях к выпуску WhatsApp указано, что вы можете использовать расширение общего доступа:
WhatsApp принимает следующие типы контента:
- текст (UTI: public.plain-text)
- фотографии (UTI: public.image)
- видео (UTI: public.movie)
- аудиозаписи и музыкальные файлы (UTI: public.audio)
- PDF документы (UTI: com.adobe.pdf)
- контактные карточки (UTI: public.vcard)
- веб-адреса (UTI: public.url)
Ответ 4
Это правильный код для доступа к ресурсам пользователей приложений.
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
}
Ответ 5
Я добавил Whatsash Sharer в ShareKit.
Отъезд здесь: https://github.com/heringb/ShareKit
Ответ 6
Свифт 3 версии ответа Вагнера:
let urlWhats = "whatsapp://app"
if let urlString = urlWhats.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed) {
if let whatsappURL = URL(string: urlString) {
if UIApplication.shared.canOpenURL(whatsappURL) {
if let image = UIImage(named: "image") {
if let imageData = UIImageJPEGRepresentation(image, 1.0) {
let tempFile = NSURL(fileURLWithPath: NSHomeDirectory()).appendingPathComponent("Documents/whatsAppTmp.wai")
do {
try imageData.write(to: tempFile!, options: .atomic)
self.documentIC = UIDocumentInteractionController(url: tempFile!)
self.documentIC.uti = "net.whatsapp.image"
self.documentIC.presentOpenInMenu(from: CGRect.zero, in: self.view, animated: true)
}
catch {
print(error)
}
}
}
} else {
// Cannot open whatsapp
}
}
}
Ответ 7
Простой код и пример кода; -)
Примечание. - Вы можете делиться только текстом или изображением, совместное использование в whatsApp не работает с стороны whatsApp
/*
//Share text
NSString *textToShare = @"Enter your text to be shared";
NSArray *objectsToShare = @[textToShare];
UIActivityViewController *activityVC = [[UIActivityViewController alloc] initWithActivityItems:objectsToShare applicationActivities:nil];
[self presentViewController:activityVC animated:YES completion:nil];
*/
//Share Image
UIImage * image = [UIImage imageNamed:@"images"];
NSArray *objectsToShare = @[image];
UIActivityViewController *activityVC = [[UIActivityViewController alloc] initWithActivityItems:objectsToShare applicationActivities:nil];
[self presentViewController:activityVC animated:YES completion:nil];
Ответ 8
WhatsApp предоставляет два способа взаимодействия вашего приложения iPhone с WhatsApp:
- Через схему пользовательских URL
- Через API взаимодействия с документами iOS
Для получения дополнительной информации посетите эту ссылку
Спасибо.
Ответ 9
Да, возможно:
NSMutableArray *arr = [[NSMutableArray alloc]init];
NSURL *URL = [NSURL fileURLWithPath:path];
NSString *textToShare = [NSString stringWithFormat:@"%@ \n",_model.title];
NSString *SchoolName= [[AppUtility sharedUtilityInstance]getAppConfigInfoByKey:@"SchoolName" SecondKeyorNil:Nil];
[arr addObject:textToShare];
[arr addObject:URL];
[arr addObject:_model.body];
[arr addObject:SchoolName];
TTOpenInAppActivity *openInAppActivity = [[TTOpenInAppActivity alloc] initWithView:_parentController.view andRect:((UIButton *)sender).frame];
UIActivityViewController *activityViewController = [[UIActivityViewController alloc] initWithActivityItems:arr applicationActivities:@[openInAppActivity]];
// Store reference to superview (UIActionSheet) to allow dismissal
openInAppActivity.superViewController = activityViewController;
// Show UIActivityViewController
[_parentController presentViewController:activityViewController animated:YES completion:NULL];
Ответ 10
версия Swift 3 для отправки текста:
func shareByWhatsapp(msg:String){
let urlWhats = "whatsapp://send?text=\(msg)"
if let urlString = urlWhats.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) {
if let whatsappURL = NSURL(string: urlString) {
if UIApplication.shared.canOpenURL(whatsappURL as URL) {
UIApplication.shared.openURL(whatsappURL as URL)
} else {
let alert = UIAlertController(title: NSLocalizedString("Whatsapp not found", comment: "Error message"),
message: NSLocalizedString("Could not found a installed app 'Whatsapp' to proceed with sharing.", comment: "Error description"),
preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: NSLocalizedString("Ok", comment: "Alert button"), style: UIAlertActionStyle.default, handler:{ (UIAlertAction)in
}))
self.present(alert, animated: true, completion:nil)
// Cannot open whatsapp
}
}
}
}
Кроме того, вам нужно добавить whatsapp
в LSApplicationQueriesSchemes
в Info.plist
Ответ 11
Для Swift 4 - отлично работает
delclare
var documentInteractionController:UIDocumentInteractionController!
func sharePicture() {
let urlWhats = "whatsapp://app"
if let urlString = urlWhats.addingPercentEncoding(withAllowedCharacters: NSCharacterSet.urlQueryAllowed) {
if let whatsappURL = NSURL(string: urlString) {
if UIApplication.shared.canOpenURL(whatsappURL as URL) {
let imgURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
let fileName = "yourImageName.jpg"
let fileURL = imgURL.appendingPathComponent(fileName)
if let image = UIImage(contentsOfFile: fileURL.path) {
if let imageData = image.jpegData(compressionQuality: 0.75) {
let tempFile = NSURL(fileURLWithPath: NSHomeDirectory()).appendingPathComponent("Documents/yourImageName.jpg")
do {
try imageData.write(to: tempFile!, options: .atomicWrite)
self.documentInteractionController = UIDocumentInteractionController(url: tempFile!)
self.documentInteractionController.uti = "net.whatsapp.image"
self.documentInteractionController.presentOpenInMenu(from: CGRect.zero, in: self.view, animated: true)
} catch {
print(error)
}
}
}
} else {
// Cannot open whatsapp
}
}
}
}
Не забудьте отредактировать .plist со следующими строками
<key>LSApplicationQueriesSchemes</key>
<array>
<string>whatsapp</string>
</array>
Наслаждаться!!!
Ответ 12
NSString *shareText = @"http:www.google.com";
NSArray *objectsToShare = @[shareText];
UIActivityViewController *activityVC = [[UIActivityViewController alloc] initWithActivityItems:objectsToShare applicationActivities:nil];
if (isIphone)
{
[self presentViewController:activityVC animated:YES completion:nil];
}
else {
UIPopoverController *popup = [[UIPopoverController alloc] initWithContentViewController:activityVC];
[popup presentPopoverFromRect:CGRectMake(self.view.frame.size.width/2, self.view.frame.size.height/4, 0, 0)inView:self.view permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
}
Ответ 13
Swift 4
let urlWhats = "whatsapp://app"
if let urlString = urlWhats.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlHostAllowed) {
if let whatsappURL = URL(string: urlString) {
if UIApplication.shared.canOpenURL(whatsappURL) {
if let imageData = UIImageJPEGRepresentation(image, 1.0) {
let tempFile = NSURL(fileURLWithPath: NSHomeDirectory()).appendingPathComponent("Documents/whatsAppTmp.wai")!
do {
try imageData.write(to: tempFile, options: .atomic)
self.documentController = UIDocumentInteractionController(url: tempFile)
self.documentController.uti = "net.whatsapp.image"
self.documentController.presentOpenInMenu(from: CGRect.zero, in: self.view, animated: true)
} catch {
print(error)
}
}
} else {
let ac = UIAlertController(title: "MessageAletTitleText".localized, message: "AppNotFoundToShare".localized, preferredStyle: .alert)
ac.addAction(UIAlertAction(title: "OKButtonText".localized, style: .default))
present(ac, animated: true)
print("Whatsapp isn't installed ")
// Cannot open whatsapp
}
}
}