Skip to content

Instantly share code, notes, and snippets.

@sohelsd
Last active January 21, 2023 23:13
Show Gist options
  • Save sohelsd/d7a391d9716255109e72 to your computer and use it in GitHub Desktop.
Save sohelsd/d7a391d9716255109e72 to your computer and use it in GitHub Desktop.
WhatsApp Swift UIActivityViewController Custom UIActivity
How to add WhatsApp to UIActivityViewController?
Drop the Whatsapp.swift file in your project.
Initialize the controller as described in ViewController.swift
//HOW TO USE THE WHATSAPP SHARE ACTION
@IBAction func shareAction(sender: UIButton) {
let objectsToShare = [message]
let wsActivity = WhatsAppActivity()
let activityVC = UIActivityViewController(activityItems: objectsToShare, applicationActivities: [wsActivity])
activityVC.excludedActivityTypes = [UIActivityTypeAirDrop, UIActivityTypeAddToReadingList,UIActivityTypeCopyToPasteboard,UIActivityTypeSaveToCameraRoll,UIActivityTypePrint]
self.presentViewController(activityVC, animated: true, completion: nil)
}
//
// Whatsapp.swift
// Send2Phone
//
// Created by Sohel Siddique on 3/27/15.
// Copyright (c) 2015 Zuzis. All rights reserved.
//
import UIKit
class WhatsAppActivity : UIActivity{
override init() {
self.text = ""
}
var text:String?
override func activityType()-> String {
return NSStringFromClass(self.classForCoder)
}
override func activityImage()-> UIImage
{
return UIImage(named: "whatsapp2")!;
}
override func activityTitle() -> String
{
return "WhatsApp";
}
override class func activityCategory() -> UIActivityCategory{
return UIActivityCategory.Share
}
func getURLFromMessage(message:String)-> NSURL
{
var url = "whatsapp://"
if (message != "")
{
url = "\(url)send?text=\(message)"
}
return NSURL(string: url)!
}
override func canPerformWithActivityItems(activityItems: [AnyObject]) -> Bool {
for activityItem in activityItems
{
if (activityItem.isKindOfClass(NSString))
{
self.text = activityItem as? String;
var whatsAppURL:NSURL = self.getURLFromMessage(self.text!)
return UIApplication.sharedApplication().canOpenURL(whatsAppURL)
}
}
return false;
}
override func prepareWithActivityItems(activityItems: [AnyObject]) {
for activityItem in activityItems{
if(activityItem.isKindOfClass(NSString)){
var whatsAppUrl:NSURL = self.getURLFromMessage(self.text!)
if(UIApplication.sharedApplication().canOpenURL(whatsAppUrl)){
UIApplication.sharedApplication().openURL(whatsAppUrl)
}
break;
}
}
}
}
@HowardTheDuck007
Copy link

Hi!
Thank you for the great tutorial. Really helped me in setting up my sharing option via whatsapp.

I have only a major problem I am not able to solve: I am trying to include my image in the post. With no luck.

I have an UIImage stored in CoreData. When I share with email no problem in adding it to the sharing. In Whatsapp I was trying to modify the code to include the image....but no way.

Can you please point me to the right direction eventually?

Thank you!

@simogerard
Copy link

Hi!

Thank you for your Gist.
In a real device the code always crash for fatal error found nil. After few hours of searching and understanding this error I think it is linked to line 45 of your Gist. If you see the official code for WhatsApp sharing:

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

In Swift:
var whatsappURL:NSURL?= NSURL(string: "whatsapp://send?text=Hello%2C%20World!")
if (UIApplication.sharedApplication().canOpenURL(whatsappURL)) {
UIApplication.sharedApplication().openURL(whatsappURL)
}

You can observe that after Hello - in the NSURL - there are %2C%20 the programmatically for comma and space.
In conclusion, if you try to use any of string you want the app crash but if you use a simple "Hello%2C%20World" instead of (message) - like the code above - the app will run with no problems but it is useless if you want to use a text in a label for example.

Could you please update your Gist to resolve this issue, or could you please help me to resolve?
Thank you!

@MBakhtiyor
Copy link

Thank you!

@ArturSkachkov
Copy link

When running in the simulator generates an error: fatal error: unexpectedly found nil while unwrapping an Optional value. And highlights the line of code: return NSURL(string: url)! . How to fix this error? The question that you have explained above, I do not understand where to enter your code. Thank you

@nikhilshekhawat
Copy link

nikhilshekhawat commented Apr 21, 2016

@artur that could be cuz of two reasons. Either the simulator does not contain whatsapp, or your code is not passing the expected message to the whatsapp share extension

Or that your canOpenUrl function is not working for which you would have to add this to you info.plist file:
"<''key''>LSApplicationQueriesSchemes<''/key>
<''array>
<''string>whatsapp<''/string>
<''/array>
<''/dict>"

@nicklee3333
Copy link

Hi, Sir,
I found few app now can share both image + text, do you have any idea how to implement. I can do only image (by UIdocumentInteractionController) or only text. Appreciate if you can teach me how to share photo + text to whatsapp.
Thanks in advanced.

@tzahola
Copy link

tzahola commented Mar 9, 2017

This is not how it's supposed to be done. You should only store the URL in prepareWithActivityItems and open it in performActivity.
See the docs on prepareWithActivityItems:

Subclasses should override this method and use it to store a reference to the data items in the activityItems parameter.

https://developer.apple.com/reference/uikit/uiactivity/1620668-preparewithactivityitems

@tejaskdubal
Copy link

its not working for swift 4

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment