iOS sharing document to WhatsApp using UIDocumentInteractionController - ios

I'm trying to share a simple .txt file to WhatsApp using UIDocumentInteractionController on iOS.
I found this FAQ of WhatsApp explaining the Custom URL Scheme for WhatsApp, but it is not explaining how to share another document to WhatsApp. This should be possible with a WhatsApp update released about 2 months ago.
I also found this answer, but it does not work for other document types. Can anyone help me?
My code, that does not work, because the URL Scheme is wrong:
let urlWhats = "whatsapp://app"
if let urlString = urlWhats.addingPercentEncoding(withAllowedCharacters: NSCharacterSet.urlQueryAllowed) {
if let whatsappURL = URL(string: urlString) {
if UIApplication.shared.canOpenURL(whatsappURL) {
activityVc = UIDocumentInteractionController(url: URL(fileURLWithPath: txtPath))
activityVc.uti = "net.whatsapp.document"
activityVc.presentOptionsMenu(from: CGRect.zero, in: self.view, animated: true)
}
}

Related

File sharing using UIActivityViewController/ UIDocumentInteractionController not working - [can't share via AirDrop, Whatapp, iMessage, Mail, etc.]

While trying to share an '.mp3' file that I have downloaded onto my app using the device's share-sheet feature, I'm able to fetch the file from the documents directory but unable to share it.
When I try to share it via Whatsapp, I get an error saying:
This item cannot be shared. Please select a different item.
If I share via AirDrop, it just says "Failed" (in red) and sharing via other options leads to a blank message (e.g. a new email with no file attached or a new msg with nothing in it)
Here are the code options I've tried so far:
Option 1 - Using UIActivityViewController
let fileURL = NSURL(fileURLWithPath: FileURLFromDocumentsDirectory)
var filesToShare = [Any]()
filesToShare.append(fileURL)
let activityViewController = UIActivityViewController(activityItems: filesToShare, applicationActivities: nil)
self.present(activityViewController, animated: true, completion: nil)
Option 2 - Using UIDocumentInteractionController
let docController : UIDocumentInteractionController?
docController = UIDocumentInteractionController(url: URL(string: fileToSharePath)!)
docController?.delegate = self
docController?.presentOptionsMenu(from: self.view.frame, in:self.view, animated:true)
In both options, I do get the file but can't share it. The phone does recognize the share as an audio file but I can't do anything with it.
Sample URL:
file:///Users/UserName/Library/Developer/CoreSimulator/Devices/C8B09E62-091F-4E61-BA6C-3D9EC23LKC01/data/Containers/Data/Application/EF2CKKJF-AB35-55G5-B778-439812EFGGG5/Documents/audioFile.mp3
The sharing works for text but not for the audio files.
Do I also need to enable some features or add some code to the AppDelegate?
Appreciate any help. Thanks.
Update #1: Code with Suggestions from #dfd [still doesn't work]
let shareAction = UIContextualAction(style: .normal, title: "Share") { (action, view, completionHandler) in
let fileURL = NSURL(fileURLWithPath: (downloadedFile?.documentDirectoryURL)!)
let activityViewController = UIActivityViewController(activityItems: [fileURL], applicationActivities: nil)
self.present(activityViewController, animated: true, completion: nil)
}
Also, for all these options, I get the audio file (mp3) as an 'Audio Recording' in the Share Sheet.
Instead of sharing the original file, can you try to create a copy of this in a temporary directory and share that copy. Once done with sharing you can delete or leave it to the system to delete it.
Something like this (You can add more check about file and directory existance):
let fileManager = FileManager.default
let tempDirectory = fileManager.temporaryDirectory
let tempPath = tempDirectory.path + "/" + fileToSharePath.lastPathComponent
let tempURL = URL(fileURLWithPath: tempPath)
try? fileManager.copyItem(atPath:fileToSharePath.path , toPath: tempPath)
let docController : UIDocumentInteractionController?
docController = UIDocumentInteractionController(url: URL(string: tempURL)!)
docController?.delegate = self
docController?.presentOptionsMenu(from: self.view.frame, in:self.view, animated:true)

How to share video on WhatsApp without using UIActivityViewController?

I am currently trying to enable the functionality to share a video on WhatsApp but without using UIActivityViewController, as Tik Tok does for example. When you click on "share" on WhatsApp, it directly redirects you to WhatsApp and contacts pop up so that you can share the video.
I kinda succeeded in sharing it but with ActivityViewController, this way:
let path = Bundle.main.url(forResource: "Rap God", withExtension: "mp4")!.relativePath
let fileUrl = NSURL(fileURLWithPath: path)
controller = UIDocumentInteractionController(url: fileUrl as URL)
controller.uti = "net.whatsapp.movie"
controller.presentOpenInMenu(from: CGRect.zero, in: self.view, animated: true)
I would be glad to know someone can help me out.
Try using UIApplication's canOpenURL(_:) and open(_:options:completionHandler:),
let urlString = "https://stackoverflow.com/questions/60282744/how-to-share-video-on-whatsapp-without-using-uiactivityviewcontroller"
let shareString = "whatsapp://send?text=\(urlString)"
if let url = URL(string: shareString), UIApplication.shared.canOpenURL(url) {
UIApplication.shared.open(url, options: [:]) { (completed) in
print(completed)
}
}

how to share post on facebook or google using URLScheme

I want to share an HTML link on facebook without install SDK like WhatsApp or twitter. I am using below code for share a link on facebook. But I want to share the post to direct app without an open safari browser.
Please tell me this is possible or not.I have searched alot but not find any solution.
//For share twitter
let urlWhats = "twitter://post?message=\(fileURL)"
let urlString = urlWhats.addingPercentEncoding(withAllowedCharacters: NSCharacterSet.urlQueryAllowed)
let whatsappURL = URL(string: urlString!)
if UIApplication.shared.canOpenURL(whatsappURL!)
{
UIApplication.shared.open(whatsappURL!, options: [:], completionHandler: nil)
}
//For Facebook
let shareURL = "https://www.facebook.com/sharer/sharer.php?u=" + url
if let url = URL(string:shareURL)
{
let vc = SFSafariViewController(url: url, entersReaderIfAvailable: true)
vc.delegate=self
present(vc, animated: true)
}
Thanks in Advance
For sharing in FB make use of 'FacebookShare'
import FBSDKShareKit
class yourViewController: UIViewController {
func shareContentInFB() {
let content = FBSDKShareLinkContent()
content.contentURL = URL(string: "http://yourURL/")
content.quote = "Hey !!!!"
let dialog : FBSDKShareDialog = FBSDKShareDialog()
dialog.fromViewController = self
dialog.shareContent = content
dialog.mode = FBSDKShareDialogMode.automatic
dialog.show()
}
}
You cannot prefill text in fb using this, if you have to do it then make use of Fb graph API

How to make iMessage to open my app with a custom document type

EDIT: As requested added info.pslist and code.
I have a custom Document Type and I have registered the UTIs and a new MIME type. I basically followed the steps by this tutorial. I am using a Codable object that it is no more than a JSON file with a custom extension and a custom icon. Honestly it looks pretty cool to me. The app I am doing is is a Grocery list app that makes a lot of sense being able to share it by a note or iMessage.
Like the finalised app in the tutorial I followed it opens in mail and even in notes!!! but iMessage does not recognise the extension and shows a folder icon and does not open it.
My question is how can I tell iMessage that this file is meant to be opened by my App. Do I need an iMessage extension? I am pretty new to iOS. info.pslist:
And now code:
func exportToUrl() -> URL? {
let contents = try? JSONEncoder().encode(shoppingList)
guard let path = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else {
return nil
}
let saveUrl = path.appendingPathComponent("/list.grabgrocerieslist")
try? contents?.write(to: saveUrl, options: .atomic)
return saveUrl
}
#IBAction func sharedTapped(_ sender: UIBarButtonItem) {
guard let url = exportToUrl() else {
return
}
let activityController = UIActivityViewController(activityItems: ["Shopping List", url], applicationActivities: nil)
activityController.excludedActivityTypes = [.assignToContact, .saveToCameraRoll, .postToFacebook ]
activityController.popoverPresentationController?.barButtonItem = sender
self.present(activityController, animated: true, completion: nil)
}
Many Thanks,

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