问题
I'm saving an image using .writetofile but I don't know how to recover it. This how I save the image:
self.pdfData.writeToURL(NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).first!.URLByAppendingPathComponent("testgogo.pdf"), atomically: true) // what it is saved as
self.pdfData.writeToFile("tessst.pdf", atomically: false)
print(NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).first!.path!)
var pdfData: NSData {
let result = NSMutableData()
UIGraphicsBeginPDFContextToData(result, frame, nil)
guard let context = UIGraphicsGetCurrentContext()
else { return result }
UIGraphicsBeginPDFPage()
layer.renderInContext(context)
UIGraphicsEndPDFContext()
return result
}
How can I fetch the image back later on ?
回答1:
Here is an example of how you could do it in Swift 2.x.
It uses the NSData(contentsOfFile: myFilePath)
to load the file.
The example uses a PNG file.
Directly from my Playground:
import UIKit
/*
* Creates an UIImage from a UIView
*/
func createImage(fromView view: UIView) -> UIImage {
UIGraphicsBeginImageContext(view.frame.size)
let context = UIGraphicsGetCurrentContext()
view.layer.renderInContext(context!)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext();
return image
}
/*
* Finds the path in Document folder
*/
func createMyFilePath(forFileName fileName: String) -> String? {
let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory,.UserDomainMask,true)
if let path = paths.first {
return path + "/\(fileName)"
}
return nil
}
/*
* Main behaviour
*/
// ImageView with Label on it
let imageView = UIImageView(image: UIImage(named: "borat"))
let label = UILabel(frame: imageView.frame)
label.font = UIFont(name: "helvetica", size: 40)
label.text = "Great Success!"
imageView .addSubview(label)
// Find the path where to save
guard let myFilePath = createMyFilePath(forFileName: "borat-with-label.png") else {
print("Cannot generate file path ☹️")
exit(0)
}
// Use this to check in finder where your file is saved
print(myFilePath)
// Transform the imageView in UIImage to save it
let imageToSave = createImage(fromView: imageView)
// Get the image as data
guard let imageToSaveAsData = UIImagePNGRepresentation(imageToSave) else {
print("Cannot transform image to data ☹️")
exit(1)
}
// Save to Disk!
do{
try imageToSaveAsData.writeToFile(myFilePath, options: .DataWritingAtomic)
} catch {
print("Error, cannot write to the location \(myFilePath)")
}
// Load from Disk!
let loadedImageData = NSData(contentsOfFile: myFilePath)
// Check the data is the same
if loadedImageData == imageToSaveAsData {
print("✌️")
}
// Have a look at the loaded image!
UIImage(data: loadedImageData!)
回答2:
You will need to remember the URL
where you saved the image/pdf that you are storing.
In order to get it back, you can use the NSData
class to get the contents of the file at that url.
dataWithContentsOfURL:(NSURL *)aURL
is a good place to start.
回答3:
It looks like the problem might be that you are trying to load the pdf file as an image which won't work. Try this method:
if let pdfURL = NSBundle.mainBundle().URLForResource("myPDF", withExtension: "pdf", subdirectory: nil, localization: nil),data = NSData(contentsOfURL: pdfURL), baseURL = pdfURL.URLByDeletingLastPathComponent {
let webView = UIWebView(frame: CGRectMake(20,20,self.view.frame.size.width-40,self.view.frame.size.height-40))
webView.loadData(data, MIMEType: "application/pdf", textEncodingName:"", baseURL: baseURL)
self.view.addSubview(webView)
}
Ps I got this code from here: How to Load Local PDF in UIWebView in Swift
回答4:
Using a slightly modified version of the code in this other answer
I have the following code:
class ViewController: UIViewController {
@IBOutlet weak var webView: UIWebView!
lazy var documentsPath = {
return NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0]
}()
let fileName = "file.pdf"
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
createPDF()
loadPDF()
}
func createPDF() {
let html = "<b>Hello <i>World!</i></b> <p>Generate PDF file from HTML in Swift</p>"
let fmt = UIMarkupTextPrintFormatter(markupText: html)
// 2. Assign print formatter to UIPrintPageRenderer
let render = UIPrintPageRenderer()
render.addPrintFormatter(fmt, startingAtPageAtIndex: 0)
// 3. Assign paperRect and printableRect
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")
// 4. Create PDF context and draw
let pdfData = NSMutableData()
UIGraphicsBeginPDFContextToData(pdfData, CGRectZero, nil)
for i in 1...render.numberOfPages() {
UIGraphicsBeginPDFPage();
let bounds = UIGraphicsGetPDFContextBounds()
render.drawPageAtIndex(i - 1, inRect: bounds)
}
UIGraphicsEndPDFContext();
// 5. Save PDF file
pdfData.writeToFile("\(documentsPath)/\(fileName)", atomically: true)
}
func loadPDF() {
let filePath = "\(documentsPath)/\(fileName)"
let url = NSURL(fileURLWithPath: filePath)
let urlRequest = NSURLRequest(URL: url)
webView.loadRequest(urlRequest)
}
}
This code works, it creates a PDF file and then loads the same PDF file into a webView. The only thing that I changed was to create a lazy variable that returns the documents directory and I use a constant for the file path.
You should be able to use the same methods to save and retrieve your PDF file.
来源:https://stackoverflow.com/questions/35945469/how-to-recover-pdfs-from-writetofile-in-swift