【问题标题】:Share image/text through WhatsApp in an iOS app在 iOS 应用程序中通过 WhatsApp 共享图像/文本
【发布时间】:2012-01-11 08:52:15
【问题描述】:

是否可以通过 iOS 应用程序中的 Whatsapp 共享图像、文本或任何您想要的内容?我在谷歌上搜索,但我只找到了关于 Android 实现的结果。

【问题讨论】:

    标签: iphone ios


    【解决方案1】:

    现在可以通过这种方式:

    发送文本 - 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

    【讨论】:

    • whatsapp 可以与安卓应用集成
    • @vaiden,你是对的“if ([self.delegate respondsToSelector: @ selector (imageCompartilhar)]) {”因为我得到了我的代表的形象。类似“UIImage * iconImage = [_delegate imageCompartilhar];”
    • 消息发送后是否可以返回应用
    • 我们可以同时发送(文本和图像)吗?
    • 谢谢。但同时分享图片和文字?以及如何返回之前的申请。
    【解决方案2】:

    现在可以了。不过还没试过。

    最新release notes for whatsapp表示可以通过分享扩展:

    WhatsApp 接受以下类型的内容:

    • 文本(UTI:public.plain-text)
    • 照片(UTI:public.image)
    • 视频(UTI:public.movi​​e)
    • 音频笔记和音乐文件 (UTI: public.audio)
    • PDF 文档 (UTI: com.adobe.pdf)
    • 联系人卡片(UTI:public.vcard)
    • 网址(UTI:public.url)

    【讨论】:

    • 不可能,它只打开应用程序但不分享图像等...:)
    • 上面的链接不错。现在这是可能的。这应该成为最佳答案。
    • 以上链接不允许在不显示菜单的情况下将媒体共享到 Whatsapp。在访问 Whatsapp 之前,您必须始终显示文档控制器的菜单,这很麻烦。
    • PDF 文档 (UTI: com.adobe.pdf) -> 共享时出现问题。如果我在代码上创建 pdf,将其存储在 documentdirectory 上并尝试在 whatsapp 上共享它,它会失败。我认为whatsapp想要一个具有Adobe pdf类型的pdf文件,即只有UTI com.adobe.pdf
    • @Adel:我们如何在 UIActivityViewController 中设置这个 UTI????
    【解决方案3】:

    不,这是不可能的,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];
    }
    

    【讨论】:

    • 现在有这方面的 api,请帮帮我,我花了更多时间在这方面
    • 不,在 iOS 中仍然没有与 WhatsApp 交互的 API。
    • 您可以使用 url 方案与 whatsapp 应用程序交谈!请参阅@Wagner Sales 的答案。
    • @JHNeves 当我发布我的答案时,这是不可用的。
    • 考虑删除此答案或将其扩展为不止一个链接。
    【解决方案4】:

    这是与whats app用户分享链接的正确代码。

    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】:

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

      注意:- 你只能分享文字或图片,在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];
      

      【讨论】:

        【解决方案6】:

        Swift 3 版本的 Wagner Sales 的回答:

        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】:

          对于 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>
          

          享受!!!

          【讨论】:

            【解决方案8】:

            我向 ShareKit 添加了一个 Whatsapp 共享器。

            在这里查看: https://github.com/heringb/ShareKit

            【讨论】:

              【解决方案9】:

              WhatsApp 为您的 iPhone 应用程序与 WhatsApp 交互提供了两种方式:

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

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

              谢谢。

              【讨论】:

                【解决方案10】:

                是的,有可能:

                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];
                

                【讨论】:

                • 图片和文字是否共享?
                【解决方案11】:

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

                另外,您需要在Info.plist 中将whatsapp 添加到LSApplicationQueriesSchemes

                【讨论】:

                  【解决方案12】:

                  斯威夫特 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
                                  }
                              }
                          }
                  

                  【讨论】:

                    【解决方案13】:
                    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];
                    }
                    

                    【讨论】:

                    • 你需要添加一些解释。为什么你认为这段代码有效?与之前的答案有何不同?
                    猜你喜欢
                    • 1970-01-01
                    • 1970-01-01
                    • 1970-01-01
                    • 2018-01-05
                    • 2023-03-24
                    • 2013-12-23
                    • 1970-01-01
                    • 1970-01-01
                    • 1970-01-01
                    相关资源
                    最近更新 更多