I have a project that is associated with opening PDF files. This is set in the Info.plist
. When I get a PDF attachment in email, I can hold my finger on the PDF attachment and then 'Open in' in my app. In my AppDelegate
, I have the following added:
func application(app: UIApplication, openURL url: NSURL, options: [String : AnyObject]) -> Bool {
incomingTransfer = URL
return true
}
incomingTransfer
is a Global Variable
declared in another ViewController
as an NSURL
. This ViewController
also has a UIWebView
and the incomingTransfer
loads into it and I'm able to see the new PDF file. My goal is to have a button that allows the user to save the incoming PDF as a PDF. I'm having trouble with this. I thought I had it all figured out, but it wasn't saving as a PDF at all, but rather as a String
. Can someone help me please? My goal is to save the incoming PDF file as a PDF to the app memory, preferably in DocumentDirectory
. I have a hard time trying to convert Objective C to Swift. My original code to save it was:
let html = String(incomingFileTransfer)
let fmt = UIMarkupTextPrintFormatter(markupText: html)
let render = UIPrintPageRenderer()
render.addPrintFormatter(fmt, startingAtPageAtIndex: 0)
let page = CGRect(x: 0, y: 0, width: 595.2, height: 841.8) // A4, 72 dpi
let printable = CGRectInset(page, 0, 0)
render.setValue(NSValue(CGRect: page), forKey: "paperRect")
render.setValue(NSValue(CGRect: printable), forKey: "printableRect")
let pdfData = NSMutableData()
UIGraphicsBeginPDFContextToData(pdfData, CGRectZero, nil)
for i in 1...render.numberOfPages() {
UIGraphicsBeginPDFPage();
let bounds = UIGraphicsGetPDFContextBounds()
render.drawPageAtIndex(i - 1, inRect: bounds)
}
UIGraphicsEndPDFContext();
recipeFileName = fileName.text!
print("File Name Entered: \(recipeFileName)")
let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0]
pdfData.writeToFile("\(documentsPath)/\(recipeFileName).pdf", atomically: true)