I am capturing an image in my app and what to share it using WHATSAPP by pressing share button like in RETRICA. But i didn't find any way to do it properly. i used UIDocumentInteraction but it didn't work. How can i share it using share extension of WHATSAPP in IOS8.
I got this exception while using UIDocumentInteractionController.
'UIDocumentInteractionController: invalid scheme (null). Only the file scheme is supported.'
this is my code
let image = UIImage(named: "nature")
let path = NSHomeDirectory().stringByAppendingPathComponent("Documents/whatsAppTmp.wai")
UIImageJPEGRepresentation(image!, 100.0)?.writeToFile(path, atomically: true)
let documentInteractionController = UIDocumentInteractionController(URL: NSURL(string: path)!)
documentInteractionController.UTI = "net.whatsapp.image"
Maybe this can help you:
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
}
}
}
You can see this answer
Share image/text through WhatsApp in an iOS app
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
Related
I am integrating sharing options from my app to Snapchat.
I have a dynamic URL obtained in an object and clicking the Snapchat's share button directly opens the app if Snapchat is there on the device and show the text with the link. I am using the below code to share which gives an error on Snapchat. Below is my Code.
func shareTextOnSnapchat(obj:VideoData) {
let shaUrl = URL(string: obj.share_url ?? "")
if let myURL:URL = shaUrl{
let promoText = "Check out this great new video from \(obj.name ?? ""), I found on talent app"
let shareString = "snapchat://text=\(promoText)&url=\(myURL)"
let escapedShareString = shareString.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)!
let url = URL(string: escapedShareString)
UIApplication.shared.openURL(url!)
}
}
I have used this to post video to snapchat. You have option to either post text or a video.
Pod used
pod 'SnapSDK', :subspecs => ['SCSDKCreativeKit']
import SCSDKCreativeKit
var scInstalled = false
override func viewDidLoad() {
super.viewDidLoad()
scInstalled = schemeAvailable(scheme: "snapchat://")
}
func ShowSnapchat(){
if scInstalled {
//shareTextOnSnapchat(obj:videoObj ?? VideoData())
shareFileOnSnapchat(obj:videoObj ?? VideoData())
}else{
downloadSharingAppAlert(appName:"Snapchat")
}
}
func shareTextOnSnapchat(obj:VideoData) {
let shaUrl = URL(string: obj.share_url ?? "")
if let myURL:URL = shaUrl{
let originalString = "\(myURL)"
let escapedString = originalString.addingPercentEncoding(withAllowedCharacters:CharacterSet.urlQueryAllowed)
//let url = URL(string: "snapchat://snap?text=\(escapedString!)")
let url = URL(string: "https://www.snapchat.com/send?text=\(escapedString!)")
if UIApplication.shared.canOpenURL(url! as URL)
{
UIApplication.shared.open(url! as URL, options: [:], completionHandler: nil)
}
}
}
func shareFileOnSnapchat(obj:VideoData){
//// SHARE VIDEO
LoadingOverlay.shared.showLoaderView(view: self.view)
let shaUrl = URL(string: obj.output_vid ?? "")
if let myURL:URL = shaUrl{
let snapVideo = SCSDKSnapVideo(videoUrl: myURL)
let snapContent = SCSDKVideoSnapContent(snapVideo: snapVideo)
// Send it over to Snapchat
snapAPI.startSending(snapContent) { (error) in
if let error = error {
print(error.localizedDescription)
LoadingOverlay.shared.hideLoaderView()
MyCustomAlert.sharedInstance.ShowAlert(vc: self, myTitle: "", myMessage: StringClass.sharedInstance.lcStr_oopsSomethingWentwrong)
} else {
// success
print("Posted to snapchat")
LoadingOverlay.shared.hideLoaderView()
MyCustomAlert.sharedInstance.ShowAlert(vc: self, myTitle: "", myMessage: StringClass.sharedInstance.lcStr_postedToSnapchat)
}
}
}
}
}
func downloadSharingAppAlert(appName:String){
var appStoreURL = "https://apps.apple.com/in/app/snapchat/id447188370"
//Open Appstore for Download
}
I have seen answers to how to share to instagram. The problem is that I am unable to share DIRECTLY to insta. Currently when I run this code I get a thing for sharing come up from the bottom and see Copy to Instagram when I tap then it opens insta and I can share. But I would like to skip this step like I have seen in other apps. How can I do this?
My current code for this:
let instagramURL = URL(string: "instagram://app")
if UIApplication.shared.canOpenURL(instagramURL!) {
if let url = Auth.auth().currentUser?.photoURL {
let image = self.getImage(url: url)
let imageData = image.jpegData(compressionQuality: 1.0)//UIImage.jpegData(image)
let writePath = (NSTemporaryDirectory() as NSString).appendingPathComponent("instagram.igo")
do {
try imageData!.write(to: URL(fileURLWithPath: writePath), options: .atomic)
//try imageData.write(to: URL(fileURLWithPath: writePath), options: .atomic)
} catch {
// print(error)
}
let fileURL = URL(fileURLWithPath: writePath)
self.documentController = UIDocumentInteractionController(url: fileURL)
self.documentController.delegate = self
self.documentController.uti = "com.instagram.exlusivegram"
if UIDevice.current.userInterfaceIdiom == .phone {
self.documentController.presentOpenInMenu(from: self.view.bounds, in: self.view, animated: true)
}
// else {
// self.documentController.presentOpenInMenu(from: self.IGBarButton, animated: true)
// }
} else {
let imageData = UIImage(named: "media")!.jpegData(compressionQuality: 1.0)//UIImage.jpegData(image)
let writePath = (NSTemporaryDirectory() as NSString).appendingPathComponent("instagram.igo")
do {
try imageData!.write(to: URL(fileURLWithPath: writePath), options: .atomic)
} catch {
// print(error)
}
let fileURL = URL(fileURLWithPath: writePath)
self.documentController = UIDocumentInteractionController(url: fileURL)
self.documentController.delegate = self
self.documentController.uti = "com.instagram.exlusivegram"
if UIDevice.current.userInterfaceIdiom == .phone {
self.documentController.presentOpenInMenu(from: self.view.bounds, in: self.view, animated: true)
}
// else {
// self.documentController.presentOpenInMenu(from: self.IGBarButton, animated: true)
// }
}
}
I found the solution here: IOS. Sharing image to Instagram without using a menu display
As Soroush Shahi said in the comments
I am trying to share photo from my iOS app to instagram app using UIDocumentInteractionController and I want to show only instagram app in popover. As instagram describe here it's possible but it not works for me, I don't know what I am missing.
Below is screenshot of instagram, that confirms it's possible.
Below is the code I am using for this.
#IBAction func sharePhoto(btn: UIButton) {
let photoBundlePath = Bundle.main.url(forResource: "Photo", withExtension: ".png")
do {
let data = try Data(contentsOf: photoBundlePath!)
let fileSavedPath = saveFile(data: data, name: "photo", fileExtension: ".igo")
let instagramUrl = URL(string: "instagram://app")
if UIApplication.shared.canOpenURL(instagramUrl!) {
ic = UIDocumentInteractionController(url: fileSavedPath)
ic.delegate = self
ic.uti = "com.instagram.exclusivegram"
ic.presentOptionsMenu(from: btn.frame, in: self.view, animated: true)
ic.annotation = ["InstagramCaption" : "Testing"]
} else {
print("Instagram is not present in your device")
}
} catch {
print(error)
}
}
func saveFile(data: Data, name: String, fileExtension: String) -> URL {
let fileManager = FileManager.default
let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
let documentDirectory = paths[0]
let fullPath = documentDirectory + "/" + name + fileExtension
fileManager.createFile(atPath: fullPath, contents: data, attributes: nil)
return URL(fileURLWithPath: fullPath)
}
One more thing here is why Instagram is shown with text "Copy to" as one can see in below image.
I am trying to share an image from my application to Instagram. I have followed all the steps mentioned here.
https://www.instagram.com/developer/mobile-sharing/iphone-hooks/
Here is my code
class ViewController: UIViewController {
lazy private var documentInteractionController = UIDocumentInteractionController()
func shareImageOnInstagram()
{
let image = UIImage(named: "sample")
let instagramURL = NSURL(string: "instagram://app")
if UIApplication.shared.canOpenURL(instagramURL! as URL) {
let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
let saveImagePath = (documentsPath as NSString).appendingPathComponent("Image.igo")
let imageData = UIImagePNGRepresentation(image!)
do {
try imageData?.write(to: URL.init(fileURLWithPath: saveImagePath), options: NSData.WritingOptions(rawValue: 0))
} catch {
print("Instagram sharing error")
}
documentInteractionController.url = URL.init(fileURLWithPath: saveImagePath)
documentInteractionController.uti = "com.instagram.exclusivegram"
if !self.documentInteractionController.presentOpenInMenu(from: CGRect.zero, in: self.view, animated: true) {
print("Instagram not found")
}
}
else {
print("Instagram not found")
}
}
#IBAction func onShowInstagramClicked(_ sender: Any)
{
self.shareImageOnInstagram()
}
}
In iOS 11.1 whenever onShowInstagramClicked is called, it shows all other applications including instagram.
Same piece of code works perfectly fine on iOS 10.3.2 and shows instagram (and Notes)
Is there any extra thing necessary for iOS 11 ?
This question already has answers here:
Add Instagram to UIActivityViewController
(2 answers)
Closed 6 years ago.
I am not able to find solution to add Instagram option to UIActivityViewController. Could anyone help. Thanks.
Use something like this:
#IBAction func shareOnIntagram(sender: UIButton) {
let finalImage: UIImage = UIImage.imageWithView(photoView)
let instagramURL = NSURL(string: "instagram://app")
if (UIApplication.sharedApplication().canOpenURL(instagramURL!)) {
let imageData = UIImageJPEGRepresentation(finalImage, 1)
let captionString = "caption"
let writePath = (NSTemporaryDirectory() as NSString).stringByAppendingPathComponent("instagram.ig")
if imageData?.writeToFile(writePath, atomically: true) == false {
return
} else {
let fileURL = NSURL(fileURLWithPath: writePath)
self.documentController = UIDocumentInteractionController(URL: fileURL)
self.documentController.delegate = self
self.documentController.UTI = "com.instagram.photo"
self.documentController.annotation = NSDictionary(object: captionString, forKey: "InstagramCaption")
self.documentController.presentOpenInMenuFromRect(self.view.frame, inView: self.view, animated: true)
}
} else {
print(" Instagram is not installed ")
}
}
To make this code work, don't forget to add UIDocumentInteractionControllerDelegate in the UIViewController class.