How can i save my pdf stored in my iphone to ibooks with activityController?
My code is ` pageSize = CGSizeMake (850, 1100)
let fileName: NSString = "Cars.pdf"
let path:NSArray = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
let documentDirectory: AnyObject = path.objectAtIndex(0)
let pdfPathWithFileName = documentDirectory.stringByAppendingPathComponent(fileName as String)
self.generatePDFs(pdfPathWithFileName)
//lines written to get the document directory path for the generated pdf file.
if let documentsPath = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).first?.path {
print(documentsPath)
let File = [documentDirectory]
let activityViewController : UIActivityViewController = UIActivityViewController(activityItems: File, applicationActivities: nil)
presentViewController(activityViewController, animated: true, completion: nil)`
but it only shows the documentDirectory in a mail.. i need something to say.. hey there is a pdf file...
Related
I am attempting to use a UIActivityViewController to create a share menu using PDF data using the code below. (The type is 'Data', I also attempted NSData to no avail):
let activityViewController = UIActivityViewController(
activityItems: [documentData],
applicationActivities: nil)
It works fine on iPhone and iPad but when running on macOS I only get "More..."
By comparison here's how the exact same file behaves on iOS:
You need to save the data to a file and share the URL of that file.
let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
let fileURL = documentsURL.appendingPathComponent("file.pdf")
try? pdfData.write(to: fileURL)
let activityController = UIActivityViewController(activityItems: [fileURL], applicationActivities: nil)
present(activityController, animated: true, completion: nil)
#IBAction func clickedViewData(_ sender: Any) {
let fileManager = FileManager.default
let documentoPath = (self.getDirectoryPath() as NSString).appendingPathComponent("zip_2MB.zip")
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")
}
}
i have one Zip file i want to share as a .zip directly..but cant get proper solution to share .zip file..when i share file its share as data file.. i read some documents but cant get proper way for share zip file in activity controller.. please help to solve this problem.
Thank You
let fileManager = FileManager.default
let documentoPath = ("self.getDirectoryPath()" as NSString).appendingPathComponent("zip_2MB.zip")
let documento = NSData(contentsOfFile: documentoPath)
var url = URL(fileURLWithPath: NSTemporaryDirectory() + ("My File.txt"))
documento?.write(to: url, atomically: false)
// create activity view controller
var activityViewController = UIActivityViewController(activityItems: [url], applicationActivities: nil)
I give my pdfData to user to save. He can save to files and make a file, but the default name of the pdf file is: PDF document.pdf. I want my own filename if this is possible. Perhaps I can change the filename within the pdfData before I give pdfData to UIActivityViewController?
Here is my code:
// Create page rect
let pageRect = CGRect(x: 0, y: 0, width: 595.28, height: 841.89) // A4, 72 dpi
// Create PDF context and draw
let pdfData = NSMutableData()
UIGraphicsBeginPDFContextToData(pdfData, pageRect, nil)
UIGraphicsBeginPDFPage()
// From here you can draw page, best make it in a function
PdfErstellung.PdfErstellen(auswahlZeilen, vitalstoffWerteListe, heuteString)
UIGraphicsEndPDFContext()
// Save pdf DATA through user
let activityViewController = UIActivityViewController(activityItems: [pdfData], applicationActivities: nil)
activityViewController.popoverPresentationController?.sourceView = self.view // für IPAD nötig
self.present(activityViewController, animated: true, completion: nil)
-- UPDATE --
My new idea ist, first try save the file and try a URL, and if this fail, then use the pdfData directly, because in some simulator use URL give no error and in other give error.
More here: https://stackoverflow.com/a/52499637/10392572
You just need to save your pdfData to a temporary fileURL and share that URL.
let temporaryFolder = FileManager.default.temporaryDirectory
let fileName = "document.pdf"
let temporaryFileURL = temporaryFolder.appendingPathComponent(fileName)
print(temporaryFileURL.path) // /Users/lsd/Library/Developer/XCPGDevices/E2003834-07AB-4833-B206-843DC0A52967/data/Containers/Data/Application/322D1F1D-4C97-474C-9040-FE5E740D38CF/tmp/document.pdf
do {
try pdfData.write(to: temporaryFileURL)
// your code
let activityViewController = UIActivityViewController(activityItems: [temporaryFileURL], applicationActivities: nil)
} catch {
print(error)
}
Note that you can also set a user title for AirDrop to be used as follows:
let temporaryFolder = FileManager.default.temporaryDirectory
let fileName = "Carburant Discount Historique des Prix au \(Date()).json"
let temporaryFileURL = temporaryFolder.appendingPathComponent(fileName)
print(temporaryFileURL.path)
do {
try? FileManager.default.removeItem(at: temporaryFileURL)
try json.write(to: temporaryFileURL)
}
catch let error {
print("\(#function): *** Error while writing json to temporary file. \(error.localizedDescription)")
alert("Export impossible")
return
}
/// Sets the **title** along with the URL
let dataToShare: [Any] = ["Historique des prix", temporaryFileURL]
let activityViewController = UIActivityViewController(activityItems: dataToShare, applicationActivities: nil)
so I'm working on exporting a .txt file from Xcode, but whenever I try to export it, say through email, it creates an email with no attachments and an empty message. When I try to export it to iCloud Drive, a white screen comes up for a second, then leaves. When I check iCloud Drive, the file isn't there. What is wrong here?
let message = testLabel.text
func getDocumentsDirectory() -> NSString {
let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
let documentsDirectory = paths[0]
return documentsDirectory as NSString
}
let filePath = getDocumentsDirectory().appendingPathComponent("matrixFile.txt")
do{
try message?.write(toFile: filePath, atomically: true, encoding: String.Encoding.utf8)
}catch let error as NSError{
testLabel.text = String(describing: error)
}
let documentInteractionController = UIDocumentInteractionController()
documentInteractionController.url = NSURL.fileURL(withPath: filePath)
documentInteractionController.uti = "public.data, public.content"
documentInteractionController.name = "matrixFile"
documentInteractionController.presentOptionsMenu(from: view.frame, in: view, animated: true)
The problem is you are declaring your document interaction controller as a constant within the method that calls it, like:
func someButton() {
let controller = UIDocumentInteractionController...
}
It will not work like that. The interaction controller needs to be an instance variable of the class that presents it, and it should be reinitialized every time you present it with a new url, like so:
var controller: UIDocumentInteractionController!
func someButton() {
controller = UIDocumentInteractionController(url: someURL)
controller.presentOptionsMenu...
}
Why? I have no idea, but file a bug report if you think this is absurd.
Your UTI is wrong. For a text file you should use "public.text". But there is a constant for this already - kUTTypePlainText. You just need to import MobileCoreServices to use it.
import MobileCoreServices
then:
documentInteractionController.uti = kUTTypePlainText as String
You should also use the proper initializer when creating the controller:
let documentInteractionController = UIDocumentInteractionController(url: URL(fileURLWithPath: filePath))
documentInteractionController.uti = kUTTypePlainText as String
documentInteractionController.name = "matrixFile"
documentInteractionController.presentOptionsMenu(from: view.frame, in: view, animated: true)
And I would only create and show the controller if the text isn't nil and you successfully write the file:
if let message = testLabel.text {
let filePath = getDocumentsDirectory().appendingPathComponent("matrixFile.txt")
do {
try message.write(toFile: filePath, atomically: true, encoding: String.Encoding.utf8)
let documentInteractionController = UIDocumentInteractionController(url: URL(fileURLWithPath: filePath))
documentInteractionController.uti = kUTTypePlainText as String
documentInteractionController.name = "matrixFile"
documentInteractionController.presentOptionsMenu(from: view.frame, in: view, animated: true)
} catch let error as NSError {
testLabel.text = String(describing: error)
}
}
I have write this code to show pdf using UIDocumentInteractionController.But,I don't know how to search pdf at local directory and open in iOS 8 and below..Any help?
let filename = history.invoiceLongDate // 01223642
if !filename.isEmpty{
let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
let docs = paths[0]
let pathURL = NSURL(fileURLWithPath: docs, isDirectory: true)
if #available(iOS 9.0, *) {
let fileURL = NSURL(fileURLWithPath: "\(filename)_my_invoice.pdf", isDirectory: false, relativeToURL: pathURL)
self.docController = UIDocumentInteractionController(URL: fileURL)
self.docController?.delegate = self
self.docController?.presentOptionsMenuFromRect(sender.frame, inView: self.view, animated: true)
} else {
// Fallback on earlier versions
// Any Help with that?
}
}
You can view PDF in iOS 8 by using webview. Try below code,
if let pdf = NSBundle.mainBundle().URLForResource("myPDF", withExtension: "pdf", subdirectory: nil, localization: nil) {
let req = NSURLRequest(URL: pdf)
let webView = UIWebView(frame: CGRectMake(0,0,self.view.frame.size.width,self.view.frame.size.height))
webView.loadRequest(req)
self.view.addSubview(webView)
}
OR
if let baseUrl = NSURL.fileURLWithPath(pathURL) {
let fileURL = baseUrl.URLByAppendingPathComponent(NFConstants.NFCoreDataStringIdentifiers.CoreDataStoresPathComponent.rawValue)
}
Hope this will be helpful to you.
UIDocumentInteractionController is available with (iOS 3.2, *).
For Viewing PDF file:
var documentInteractionController: UIDocumentInteractionController!
#IBAction func openDocument(sender: UIButton) {
let URL: NSURL = NSBundle.mainBundle().URLForResource("pdf-sample", withExtension: "pdf")!
if (URL != "") {
// Initialize Document Interaction Controller
self.documentInteractionController = UIDocumentInteractionController(URL: URL)
// Configure Document Interaction Controller
self.documentInteractionController.delegate = self
// Present Open In Menu
self.documentInteractionController.presentOptionsMenuFromRect(sender.frame, inView: self.view, animated: true)
//presentOpenInMenuFromRect(button.frame, inView: self.view, animated: true)
}
}
// MARK: UIDocumentInteractionControllerDelegate
func documentInteractionControllerViewControllerForPreview(controller: UIDocumentInteractionController) -> UIViewController {
return self
}