How to send message to contact in Whatsapp from iOS App - Swift - ios

I am trying to send a message from my iOS app developed in Swift to a Whatsapp contact. But the specific contact does not get opened, instead all my contacts in whatsApp open up.
My code so far -
func messageViaWhatsApp (sender: AnyObject) {
let messageBody = "Hello"
let whatsURL = "whatsapp://send?text=\(messageBody)"
let whatsAppURL = NSURL(string: whatsURL.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!)
if UIApplication.sharedApplication().canOpenURL(whatsAppURL!)
{
UIApplication.sharedApplication().openURL(whatsAppURL!)
}
else
{
let alert = UIAlertView(title: "Sorry", message: "Your device does not have whatsApp installed ", delegate: nil, cancelButtonTitle: "OK")
}
}
Thanks for your help. XCode - 8.0, Swift 2.3

For security purpose Apple doesn't allow you to send to a particular contact.

Try this....
let urlWhats = "whatsapp://send?phone=***********&text=***"
var characterSet = CharacterSet.urlQueryAllowed
characterSet.insert(charactersIn: "?&")
if let urlString = urlWhats.addingPercentEncoding(withAllowedCharacters: characterSet){
if let whatsappURL = NSURL(string: urlString) {
if UIApplication.shared.canOpenURL(whatsappURL as URL){
UIApplication.shared.openURL(whatsappURL as URL)
}
else {
print("Install Whatsapp")
}
}
}
Note:Country code (Ex:+91) is mandatory to open mobile number Chat
Note: Add url scheme in info.plist
<key>LSApplicationQueriesSchemes</key>
<array>
<string>whatsapp</string>
</array>

Related

How to open Whatsapp or other iOS app on click of Button in Swift?

I want to open an iOS app_B from app_A and then wants the data of app_B back into app_A, tried below to open whatsapp, but didn't work. Please help how to achieve this in iOS, thanks in advance.
#IBAction func clickMe(_ sender: UIButton) {
let url = "https://api.whatsapp.com/send?00919599****** "
let whatUpUrl = NSURL(string: url)
if UIApplication.shared.canOpenURL(whatUpUrl! as URL){
UIApplication.shared.openURL(whatUpUrl! as URL)
} else {
//redirect to safari because the user doesn't have Whatsapp installed
UIApplication.shared.openURL(NSURL(string: "http://whatsapp.com/")! as URL)
}
}
WebUrl Link open Chat
let whatsappURL = URL(string: "https://api.whatsapp.com/send?phone=9512347895&text=Invitation")
if UIApplication.shared.canOpenURL(whatsappURL!) {
UIApplication.shared.openURL(whatsappURL!)
}
Note: Add url scheme in info.plist
<key>LSApplicationQueriesSchemes</key>
<array>
<string>whatsapp</string>
</array>
Add this to Info.plist
Then on the button you want to open whatsapp use this.
#IBAction func whatsappButtonPressed(_ sender: Any) {
var str = "Hello to whatsapp"
str = str.addingPercentEncoding(withAllowedCharacters: (NSCharacterSet.urlQueryAllowed))!
let whatsappURL = NSURL(string: "whatsapp://send?text=\(str)")
if UIApplication.shared.canOpenURL(whatsappURL! as URL) {
UIApplication.shared.openURL(whatsappURL! as URL)
} else {
showAlert(message: "Whatsapp is not installed on this device. Please install Whatsapp and try again.")
}
}
Similarly for other apps :
Replace -
NSURL(string: "whatsapp://send?text=(str)") with
NSURL(string: "APPNAME://").
You will also need to add that app to Info.plist as described above.
Thanks!!

How to open Facebook Messenger and direct to someone?

I have FBSDK already and can use FBSDKShareKit send something on Messenger.
I want just open a chat with someone in Facebook Messenger. like this:
Click a button in my app(sample: Facebook app):
http://i.imgur.com/j60P3Ng.png
Go to Facebook Messenger and open a chat with this person:
http://i.imgur.com/yU0EXKF.png
How Can I do it?
Swift 4
UI
In my app I show a user's Facebook ID as a button:
Code
#IBAction func messengerButton(_ sender: UIButton) {
if let id = sender.titleLabel?.text {
if let url = URL(string: "fb-messenger://user-thread/\(id)") {
// Attempt to open in Messenger App first
UIApplication.shared.open(url, options: [:], completionHandler: {
(success) in
if success == false {
// Messenger is not installed. Open in browser instead.
let url = URL(string: "https://m.me/\(id)")
if UIApplication.shared.canOpenURL(url!) {
UIApplication.shared.open(url!)
}
}
})
}
}
}
User's Facebook ID
The user can get another person's Facebook ID from looking them up on Facebook and then observing the URL:
I found a solution with URL Scheme:
let userID = 4
let urlStr = String(format: "fb-messenger://user-thread/%d", userID)
let theUrl = NSURL(string: urlStr)
[UIApplication.sharedApplication() .openURL(theUrl!)]
This code will open Message application and talk to Mark.
in swift 5.1, use
guard let messenger = URL(string: "fb-messenger://user-thread/your_id") else { return }
UIApplication.shared.open(messenger)

iOS/Swift - Is there a way we can link our app as a WhatsApp message?

I have my app running on my iPhone, and I'm able to send some data to my WhatsApp from my App. I went through the following to do the same :
Sending message to WhatsApp from your app using Swift?
Is there a way we can create a URL that would open our own app directly if it is installed? Could someone suggest any place where I could understand how it could be done?
Something like this should work:
let originalString = "Some text you want to send"
let encodedString = originalString.addingPercentEncoding(withAllowedCharacters: NSCharacterSet.urlQueryAllowed)
let url = NSURL(string: "whatsapp://send?text="+encodedString!)
if UIApplication.sharedApplication().canOpenURL(url!) {
UIApplication.sharedApplication().open(url as URL, options: [:]) { (success) in
if success {
print("WhatsApp accessed successfully")
} else {
print("Error accessing WhatsApp")
}
}
} else {
print("whatsapp not installed")
}

Open Gmail app from my app

I'm trying to send an email from my app. But what I want is if user is having Gmail app on his/her phone, then mail should be sent using it. If Gmail app is unavailable then the user should be redirected to Mailbox.
So how can I know if user contains Gmail app and how can I redirect user to it.
Setup for iOS9+
As explained here, if you're on iOS9+, don't forget to add googlegmail to LSApplicationQueriesSchemes on your info.plist
Code to open GMail
Then, you can do the same as the accepted answer (below is my swift 2.3 version):
let googleUrlString = "googlegmail:///co?subject=Hello&body=Hi"
if let googleUrl = NSURL(string: googleUrlString) {
// show alert to choose app
if UIApplication.sharedApplication().canOpenURL(googleUrl) {
if #available(iOS 10.0, *) {
UIApplication.sharedApplication().openURL(googleUrl, options: [:], completionHandler: nil)
} else {
UIApplication.sharedApplication().openURL(googleUrl)
}
}
}
You need to use custom URL Scheme. For gmail application its:
googlegmail://
If you want to compose a message there you can add more parameters to this URL:
co?subject=Example&body=ExampleBody
You can determinate if any kind of application is installed using this code (just replace customURL obviously for an other apps):
NSString *customURL = #"googlegmail://";
if ([[UIApplication sharedApplication]
canOpenURL:[NSURL URLWithString:customURL]])
{
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:customURL]];
}
else
{
//not installed, show popup for a user or an error
}
For Swift 3.0+
Notes:
This solution shows how to use spaces or newlines in the arguments to the URL (Gmail may not respect the newlines).
It is NOT necessary to register with LSApplicationQueriesSchemes as long as you don't call canOpenURL(url). Just try and use the completion handler to determine if it succeeded.
let googleUrlString = "googlegmail:///co?to=\(address.addingPercentEncoding(withAllowedCharacters: .alphanumerics) ?? "")&subject=\(subject.addingPercentEncoding(withAllowedCharacters: .alphanumerics) ?? "")&body=\(buildInfo.addingPercentEncoding(withAllowedCharacters: .alphanumerics) ?? "")"
if let googleUrl = URL(string: googleUrlString) {
UIApplication.shared.open(googleUrl, options: [:]) {
success in
if !success {
// Notify user or handle failure as appropriate
}
}
}
else {
print("Could not get URL from string")
}
I couldn't figure out why this wasn't working for me until I realised I was targetting a info_development.plist instead of the production-file info.plist
If you're like me and happen to have multiple Plists (one for development, one for prod etc) make sure you edit it everywhere. ;-)
Swift 5
These answers can open gmail but what if the user do not have gmail installed in the device? In that case I have handled opening apple mail/outlook/yahoo/spark. If none of them are present, I am showing an alert.
#IBAction func openmailAction() {
if let googleUrl = NSURL(string: "googlegmail://") {
openMail(googleUrl)
} else if let mailURL = NSURL(string: "message://") {
openMail(mailURL)
} else if let outlookURL = NSURL(string: "ms-outlook://") {
openMail(outlookURL)
} else if let yahooURL = NSURL(string: "ymail://") {
openMail(yahooURL)
} else if let sparkUrl = NSURL(string: "readdle-spark://") {
openMail(sparkUrl)
} else {
// showAlert
}
}
func openMail(_ url: NSURL) {
if UIApplication.shared.canOpenURL(url as URL) {
UIApplication.shared.open(url as URL, options: [:], completionHandler: nil)
}
}
You might also may have to add this in the plist
<key>LSApplicationQueriesSchemes</key>
<array>
<string>googlegmail</string>
<string>ms-outlook</string>
<string>readdle-spark</string>
<string>ymail</string>
</array>

Sharing images to Whatsapp using UIDocumentIntractionController in ios

Is it possible to share Image and Text from an iOS app to WhatsApp using UIDocumentIntractionController or API in iPhone application development?
Please look at this link from the FAQ:
http://www.whatsapp.com/faq/en/iphone/23559013
I have found that If your application creates photos, videos or audio notes and you’d like your users to share these media using WhatsApp, you can use the Document Interaction API to send your media to your WhatsApp contacts and groups.
You can refer this link : http://www.whatsapp.com/faq/en/iphone/23559013
In Swift 3 use this code
#IBAction func whatsappShareWithImages(_ sender: AnyObject)
{
let urlWhats = "whatsapp://app"
if let urlString = urlWhats.addingPercentEncoding(withAllowedCharacters:CharacterSet.urlQueryAllowed) {
if let whatsappURL = URL(string: urlString) {
if UIApplication.shared.canOpenURL(whatsappURL as URL) {
if let image = UIImage(named: "whatsappIcon") {
if let imageData = UIImageJPEGRepresentation(image, 1.0) {
let tempFile = URL(fileURLWithPath: NSHomeDirectory()).appendingPathComponent("Documents/whatsAppTmp.wai")
do {
try imageData.write(to: tempFile, options: .atomic)
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
}
}
}
}
Add this code in your app "plist"
<key>LSApplicationQueriesSchemes</key>
<array>
<string>whatsapp</string>
</array>
You can also refer to small app for reference : https://github.com/nithinbemitk/iOS-Whatsapp-Share

Resources