Using UIActivityViewController to specify file type - ios

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)

Related

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")
}
}

Unable to share doc /ppt /Xlsx using UIActivityViewController

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)

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 .

Email CSV using MFMailComposeViewController in swift

I am using this code to export CSV file https://gist.github.com/kenechilearnscode/2d5d35f550f593332319
And it is exporting correctly but I want to email this CSV using MFMailComposeViewController. The above code opens an applicationActivities from where I can choose mail and the file is attached but the subject and recipients are not set. Code I am using to email the CSV is following. Its setting the subject and recipients etc but not attaching the CSV file.
if( MFMailComposeViewController.canSendMail() ) {
print("Can send email.")
let mailComposer = MFMailComposeViewController()
mailComposer.mailComposeDelegate = self
//Set the subject and message of the email
mailComposer.setSubject("Patient Data")
mailComposer.setMessageBody("Please find attached herewith complete patient data", isHTML: false)
mailComposer.setToRecipients(secondaryEmailList)
mailComposer.setCcRecipients([masterEmail])
if let filePath = Bundle.main.path(forResource: "export", ofType: "csv") {
print("File path loaded.")
if let fileData = NSData(contentsOfFile: filePath) {
print("File data loaded.")
mailComposer.addAttachmentData(fileData as Data, mimeType: "text/csv", fileName: "export")
}
}
self.present(mailComposer, animated: true, completion: nil)
}
Here is the code I am using to generate CSV file
func saveAndExport(exportString: String) {
let exportFilePath = NSTemporaryDirectory() + "export.csv"
let exportFileURL = NSURL(fileURLWithPath: exportFilePath)
FileManager.default.createFile(atPath: exportFilePath, contents: NSData() as Data, attributes: nil)
var fileHandleError: NSError? = nil
var fileHandle: FileHandle? = nil
do {
fileHandle = try FileHandle(forWritingTo: exportFileURL as URL)
} catch {
print("Error with fileHandle")
}
if fileHandle != nil {
fileHandle!.seekToEndOfFile()
let csvData = exportString.data(using: String.Encoding.utf8, allowLossyConversion: false)
fileHandle!.write(csvData!)
fileHandle!.closeFile()
let firstActivityItem = NSURL(fileURLWithPath: exportFilePath)
let activityViewController : UIActivityViewController = UIActivityViewController(
activityItems: [firstActivityItem], applicationActivities: nil)
activityViewController.excludedActivityTypes = [
UIActivityType.assignToContact,
UIActivityType.saveToCameraRoll,
UIActivityType.postToFlickr,
UIActivityType.postToVimeo,
UIActivityType.postToTencentWeibo
]
self.present(activityViewController, animated: true, completion: nil)
}
}

How to share longitude and latitude using UIActivityViewController

I'm trying to share a (longitude, latitude) associated with your's location in a UIActivityViewController so that the user can share the location in an SMS with someone else and it shows up as a clickable little map as shown below.
I know how to share an address as a text. Here is my code for sharing the address:
#IBAction func didTapShareLocation(_ sender: UIButton) {
guard let carAddress = self.adressLabel.text else {
return
}
let textToShare = "My car is at this address: \(carAddress)"
let objectsToShare = [textToShare] as [Any]
let activityVC = UIActivityViewController(activityItems: objectsToShare, applicationActivities: nil)
activityVC.popoverPresentationController?.sourceView = sender
myParentVC?.present(activityVC, animated: true, completion: nil)
}
Here is a complete answer in Swift 3.1 which I put together after getting pieces of information from several places. I hope it helps someone.
#IBAction func didTapShareLocation(_ sender: UIButton) {
guard let carAddress = self.adressLabel.text, let lat = self.carCoordinates?.latitude, let lon = self.carCoordinates?.longitude else {
return
}
guard CLLocationCoordinate2DIsValid(self.carCoordinates!) else {
print("Location not valid!")
return
}
let carAddressString = "My car is at this address: \n\(carAddress)\n"
let vcardString = [
"BEGIN:VCARD",
"VERSION:3.0",
"N:;Shared Location;;;",
"FN:Shared Location",
"item1.URL;type=pref:http://maps.apple.com/?ll=\(lat),\(lon)",
"item1.X-ABLabel:map url",
"END:VCARD"
].joined(separator: "\n")
let directory = FileManager().urls(for: .cachesDirectory, in: .userDomainMask)
let path = directory.first!.path + "_vcard_for_location_sharing.loc.vcf"
do {
try vcardString.write(toFile: path, atomically: true, encoding: .ascii)
let url = NSURL(fileURLWithPath: path)
let objectsToShare = [url, carAddressString] as [Any]
let activityVC = UIActivityViewController(activityItems: objectsToShare, applicationActivities: nil)
activityVC.popoverPresentationController?.sourceView = sender
self.present(activityVC, animated: true, completion: nil)
}
catch {
print("problem saving vcard: \(error.localizedDescription)")
}
}

Resources