在iOS应用程序中通过WhatsApp分享图片/文本

58

在iOS应用中通过WhatsApp分享图片、文本或其他内容是否可行?我在谷歌上搜索,但只发现有关Android实现的结果。

13个回答

133

现在可以使用这种方式:

发送文本 - 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方案的更多信息:https://developer.apple.com/videos/play/wwdc2015-703/

我没有找到一个适用于两个问题的解决方案。 有关更多信息,请参见http://www.whatsapp.com/faq/en/iphone/23559013

我制作了一个小项目来帮助一些人。 https://github.com/salesawagner/SharingWhatsApp


整个 "if ([self.delegate respondsToSelector:@selector(imageCompartilhar)]) {" 似乎是多余的。除此之外,它可以正常工作。 - Vaiden
1
@vaiden,你说得对关于“if ([self.delegate respondsToSelector: @ selector (imageCompartilhar)]) {”,我是因为我从我的代理那里获取图像。就像“UIImage * iconImage = [_delegate imageCompartilhar];”这样的东西。 - Wagner Sales
1
发送消息后是否可以返回应用程序? - Imran
3
我们可以同时发送文字和图片吗? - Sudhakar
3
谢谢。但是同时分享图像和文本吗?如何返回先前的应用程序? - Bagusflyer
显示剩余11条评论

24

现在已经可能了。虽然还没有尝试过。

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)

2
不可能的,只是打开应用程序,但不能分享图片等等... :) - Rushabh
以上链接很好。现在这是可能的。这应该成为最佳答案。 - Yoav Shapira
2
以上链接不允许在不显示菜单的情况下分享媒体到Whatsapp。在前往Whatsapp之前,您必须始终显示文档控制器的菜单,这非常麻烦。 - user3344977
PDF文档(UTI:com.adobe.pdf)->在共享时存在问题。如果我在代码上创建PDF,将其存储在文档目录中并尝试在WhatsApp上共享它,则会失败。我认为WhatsApp想要一种具有Adobe pdf类型的pdf文件,即仅具有UTI com.adobe.pdf。 - Kaan Esin
1
@Adel:我们应该如何在UIActivityViewController中设置这个UTI? - Abhishek Thapliyal

21

不可能的,WhatsApp没有任何可以使用的公共API。

请注意,这个答案是针对2011年没有WhatsApp API时的情况。

现在有一个可用于与WhatsApp交互的API:http://www.whatsapp.com/faq/en/iphone/23559013

打开其中一个URL的Objective-C调用如下:

NSURL *whatsappURL = [NSURL URLWithString:@"whatsapp://send?text=Hello%2C%20World!"];
if ([[UIApplication sharedApplication] canOpenURL: whatsappURL]) {
    [[UIApplication sharedApplication] openURL: whatsappURL];
}

1
现在有没有适用于这个的API?请帮帮我,我已经花了很多时间在这上面。 - SampathKumar
1
不,iOS中仍然没有与WhatsApp交互的API。 - rckoenes
1
@JHNeves 当我发布我的答案时,这是不可用的。 - rckoenes
请考虑删除此答案或将其扩展为不止一个链接。 - Suragch
有字符限制吗? - Vaibhav Jhaveri
显示剩余4条评论

8
这是正确的分享链接到Whatsapp用户的代码。
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
}

7

简单代码和示例代码 ;-)

注意:您只能分享文本或图像,同时在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];

5

适用于Swift 4 - 完美运行

声明

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>

祝愉快!!!


1
这不会直接打开WhatsApp,而是会打开文档交互视图。有没有办法直接打开WhatsApp? - DanielZanchi

4

Wagner Sales的回答的Swift 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
    }
  }
}

3

2

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
                }
            }
        }

1

WhatsApp提供两种方式让你的iPhone应用与WhatsApp进行交互:

  • 通过自定义URL scheme
  • 通过iOS文档交互API

欲了解更多信息,请访问this link

谢谢。


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