在iOS应用中通过WhatsApp共享图像/文本

时间:2011-12-02 09:46:14

标签: iphone ios

是否可以通过Whatsapp在iOS应用中分享图片,文字或其他任何内容?我正在谷歌上搜索,但我只发现了有关Android实现的结果。

13 个答案:

答案 0 :(得分:122)

现在可以这样:

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

有关网址的更多信息:https://developer.apple.com/videos/play/wwdc2015-703/

我没有找到两者的单一解决方案。 有关http://www.whatsapp.com/faq/en/iphone/23559013

的更多信息

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

答案 1 :(得分:24)

现在可以了。虽然还没试过。

最新release notes for whatsapp表示您可以通过共享扩展程序:

WhatsApp接受以下类型的内容:

  • text(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)

答案 2 :(得分:19)

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

请注意,当没有Wha​​tsApp的API时,2011年的答案是正确的。

现在有一个api可用于与WhatsApp交互: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];
}

答案 3 :(得分:8)

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

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
}

答案 4 :(得分:3)

我向ShareKit添加了Whatsapp Sharer。

点击这里: https://github.com/heringb/ShareKit

答案 5 :(得分:3)

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

答案 6 :(得分:3)

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

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

答案 7 :(得分:1)

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

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

有关详细信息,请访问this link

感谢。

答案 8 :(得分:1)

是的,可能:

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

答案 9 :(得分:1)

Swift 3 version for sending text:

?- cantNodos(arbol(3,arbol(2,nil,nil),arbol(6,nil,arbol(8,nil,nil))),R).
R=4.

Also, you need to add SFTP_VAR="JHGSYDDUIGUIGUIGUIG" to # Incorrect SFTP_VAR="*"; export SSHPASS=$SFTP_VAR; echo $SSHPASS # Correct SFTP_VAR="*"; export SSHPASS="$SFTP_VAR"; echo "$SSHPASS" in your 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 } } } }

答案 10 :(得分:1)

对于Swift 4-正常工作

delclare

--source_path

不要忘记用以下几行来编辑.plist

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

享受!!!

答案 11 :(得分:0)

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

答案 12 :(得分:0)

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