Unable to share doc /ppt /Xlsx using UIActivityViewController - ios

I am unable to share the msword and msexcel and ppt files in Swift Using UIActivityViewController
Here is the code snippet I am using
func ShareFileFromApptoIpad(filename : String!){
let fileManager = FileManager.default
let documentoPath = (self.getDirectoryPath() as NSString).appendingPathComponent("\(filename!)")
print("doc\(documentoPath)")
if fileManager.fileExists(atPath: documentoPath){
let documento = NSData(contentsOfFile: documentoPath)
let activityViewController: UIActivityViewController = UIActivityViewController(activityItems: [documento!], applicationActivities: nil)
activityViewController.popoverPresentationController?.sourceView=self.view
present(activityViewController, animated: true, completion: nil)
}
else {
print("document was not found")
}
}

you can change your url Like this
let url = NSURL.fileURL(withPath: myFileName)
and then use in
let activityViewController = UIActivityViewController(activityItems: [url] , applicationActivities: nil)

Related

Share Image Via URL

I am creating Images app from my WordPress website with json and i am using swift, i want to share image on Social Networks from my app , currently i tried this code it works but only with image name i want to share image from image url, is that possible ?
this is my code
let myWebsite = NSURL(string: "nice")
let img: UIImage = UIImage(named:"splash")!
guard let url = myWebsite else {
print("nothing found")
return
}
let shareItems:Array = [img,url]
let activityViewController:UIActivityViewController = UIActivityViewController(activityItems: shareItems, applicationActivities: nil)
activityViewController.excludedActivityTypes = [UIActivity.ActivityType.print, UIActivity.ActivityType.postToWeibo, UIActivity.ActivityType.copyToPasteboard, UIActivity.ActivityType.addToReadingList, UIActivity.ActivityType.postToVimeo]
self!.present(activityViewController, animated: true, completion: nil)
If you need to download an image and then share you should do that separately, there is no single method that does that for you. Here is how:
func shareImageFromUrl(_ string: String) {
guard let myUrl = URL(string: string) else {
print("Invalid url!")
return
}
URLSession.shared.dataTask(with: myUrl) { (data, _, _) in
guard let data = data,
let image = UIImage(data: data) else
{ return }
let activityViewController:UIActivityViewController = UIActivityViewController(activityItems: [image], applicationActivities: nil)
activityViewController.excludedActivityTypes = [UIActivity.ActivityType.print, UIActivity.ActivityType.postToWeibo, UIActivity.ActivityType.copyToPasteboard, UIActivity.ActivityType.addToReadingList, UIActivity.ActivityType.postToVimeo]
DispatchQueue.main.async {
self.present(activityViewController, animated: true, completion: nil)
}
}.resume()
}

share pdf file using UIActivityViewController in Swift 4

I am using UIActivityViewController to share a PDF file:
let pdfFilePath = URL(string: "https://www.tutorialspoint.com/swift/swift_tutorial.pdf")
let pdfData = NSData(contentsOf: pdfFilePath!)
let activityVC = UIActivityViewController(activityItems: [pdfData!], applicationActivities: nil)
present(activityVC, animated: true, completion: nil)
The below result is displayed:
What I want is to display more features like "copy to Books" and "Add to Notes" like the following:
If you want to share your pdf file which is on the server and you have a URL. Then first you download that file in your device and then share that file to any other person.
If you using Alamofire in your code then there is code.
Stape 1
import Alamofire
Stape 2
Add this function in your class:-
func downloadPdf(downloadUrl : String, fileName: String, completionHandler:#escaping(String, Bool)->()){
let destinationPath: DownloadRequest.DownloadFileDestination = { _, _ in
let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0];
let fileURL = documentsURL.appendingPathComponent("\(fileName).pdf")
return (fileURL, [.removePreviousFile, .createIntermediateDirectories])
}
print(downloadUrl)
Alamofire.download(downloadUrl, to: destinationPath)
.downloadProgress { progress in
}
.responseData { response in
print("response: \(response)")
switch response.result{
case .success:
if response.destinationURL != nil, let filePath = response.destinationURL?.absoluteString {
completionHandler(filePath, true)
}
break
case .failure:
completionHandler("", false)
break
}
}
}
Stape 3
Add this action on your share button
#IBAction func btnShareAction(_ sender: UIButton) {
let myURL = "http://www.demo.com/demo.pdf" // change this with your URL
self.downloadPdf(downloadUrl : myURL, fileName: "invoice") { (localFileUrl, bool) in
let fileURL = NSURL(fileURLWithPath: localFileUrl)
let activityViewController = UIActivityViewController(activityItems: [fileURL], applicationActivities: nil)
self.present(activityViewController, animated: true, completion: nil)
}
}
Simple Steps! Copy paste the give code
#objc private func btnShareTapped(_ sender: UIButton) {
guard let urlString = strURL,
let url = URL(string: urlString),
let docPath = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).last else {
return
}
let actualPath = docPath.appendingPathComponent("Statement.pdf")
let pdfData = try? Data.init(contentsOf: url)
do {
try pdfData?.write(to: actualPath, options: .atomic)
let fileURL = URL(fileURLWithPath: actualPath.absoluteString)
let activityVC = UIActivityViewController(activityItems: [fileURL],
applicationActivities: nil)
present(activityVC, animated: true)
} catch {
debugPrint("Pdf could not be saved")
}
}

How to share excel file with UIActivityView Controller or UIDocumentInteractionController?

I want to share excel file with UIAtivityViewController or UIDocumentInteractionController
let documentsPath = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as NSString).appendingPathComponent(self.stateMentType)
do {
_ = try data?.write(to: URL.init(fileURLWithPath: documentsPath), options: .atomicWrite)
}
catch {
print("Error in writing \(error)")
}
let documents = NSData(contentsOfFile: documentsPath)
if fileManager.fileExists(atPath: documentsPath) {
// let activityController = UIActivityViewController(activityItems: [documents!], applicationActivities: nil)
// self.present(activityController, animated: true, completion: nil)
let url = URL(fileURLWithPath: documentsPath)
let dc = UIDocumentInteractionController(url: url)
dc.uti = "public.data"
dc.presentOpenInMenu(from: self.view.bounds, in: self.view, animated: true)
// dc.presentOptionsMenu(from: self.view.bounds, in: self.view, animated: true)
}
I am using this code with UIDocumentInteractionController. I am also added some key in Info Tab.
When i share the excel file , sharing views is opened but file is not sharing. Please help me .

Using UIActivityViewController to specify file type

Following up from this question, how would I go about using UIActivityViewController to specify the file type of a file I am sharing over airdrop?
Worked it out:
let myFileManager = FileManager.default
var activityArray = [NSURL]()
activityArray.removeAll()
for (i, data) in dataToShare.enumerated() {
let docsurl = try! myFileManager.url(for:.documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false)
let myurl = docsurl.appendingPathComponent("shareData\(i).gymProf")
var myUrlString = myurl.absoluteString
myUrlString = myUrlString.replacingOccurrences(of: "file://", with: "")
myFileManager.createFile(atPath: myUrlString, contents: data, attributes: nil)
activityArray.append(NSURL(fileURLWithPath: myUrlString))
if myFileManager.fileExists(atPath: myUrlString) {
print("File Exists at \(myUrlString)")
} else {
print("File not found")
}
}
let activityViewController = UIActivityViewController(activityItems: activityArray, applicationActivities: nil)
activityViewController.popoverPresentationController?.sourceView = self.view
self.present(activityViewController, animated: true, completion: nil)

How Can I share text and Image Together on Whatsapp

I want to share image and text together with swift.How Can I do That ?
let url = NSURL(string: "whatsapp://app")
let shareText = "Beni Bons'da ekle : \(PFUser.currentUser()!.username!). http://apple.co/29RMfNn"
let bonsCardImage = UIImage.renderUIViewToImage(bonsCardView)
let activityItems = [bonsCardImage]
let vc = UIActivityViewController(activityItems: activityItems, applicationActivities: nil)
presentViewController(vc, animated: true, completion: nil)
Thanks

Resources