在iOS中使用Swift保存PDF文件并显示它们



我想构建一个应用程序,该应用程序还可以在应用程序中显示和保存PDF,并在表视图中显示它们(作为文件系统),当我点击一个PDF时打开它们。

以下是我的重要问题:

1.如何在我的应用程序上本地保存PDF(例如,如果用户可以输入url),以及它将在哪里保存

2.保存时,如何在表视图中显示所有本地存储的文件以打开它们

由于有几个人要求这样做,这里的答案相当于Swift中的第一个答案:

//The URL to Save
let yourURL = NSURL(string: "http://somewebsite.com/somefile.pdf")
//Create a URL request
let urlRequest = NSURLRequest(URL: yourURL!)
//get the data
let theData = NSURLConnection.sendSynchronousRequest(urlRequest, returningResponse: nil, error: nil)
//Get the local docs directory and append your local filename.
var docURL = (NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)).last as? NSURL
docURL = docURL?.URLByAppendingPathComponent( "myFileName.pdf")
//Lastly, write your file to the disk.
theData?.writeToURL(docURL!, atomically: true)

此外,由于此代码使用同步网络请求,我强烈建议将其调度到后台队列:

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), { () -> Void in
    //The URL to Save
    let yourURL = NSURL(string: "http://somewebsite.com/somefile.pdf")
    //Create a URL request
    let urlRequest = NSURLRequest(URL: yourURL!)
    //get the data
    let theData = NSURLConnection.sendSynchronousRequest(urlRequest, returningResponse: nil, error: nil)
    //Get the local docs directory and append your local filename.
    var docURL = (NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)).last as? NSURL
    docURL = docURL?.URLByAppendingPathComponent( "myFileName.pdf")
    //Lastly, write your file to the disk.
    theData?.writeToURL(docURL!, atomically: true)
})

Swift中第二个问题的答案:

//Getting a list of the docs directory
let docURL = (NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).last) as? NSURL
//put the contents in an array.
var contents = (NSFileManager.defaultManager().contentsOfDirectoryAtURL(docURL!, includingPropertiesForKeys: nil, options: NSDirectoryEnumerationOptions.SkipsHiddenFiles, error: nil))
//print the file listing to the console
println(contents)

Swift 4.1

 func savePdf(urlString:String, fileName:String) {
        DispatchQueue.main.async {
            let url = URL(string: urlString)
            let pdfData = try? Data.init(contentsOf: url!)
            let resourceDocPath = (FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)).last! as URL
            let pdfNameFromUrl = "YourAppName-(fileName).pdf"
            let actualPath = resourceDocPath.appendingPathComponent(pdfNameFromUrl)
            do {
                try pdfData?.write(to: actualPath, options: .atomic)
                print("pdf successfully saved!")
            } catch {
                print("Pdf could not be saved")
            }
        }
    }
    func showSavedPdf(url:String, fileName:String) {
        if #available(iOS 10.0, *) {
            do {
                let docURL = try FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false)
                let contents = try FileManager.default.contentsOfDirectory(at: docURL, includingPropertiesForKeys: [.fileResourceTypeKey], options: .skipsHiddenFiles)
                for url in contents {
                    if url.description.contains("(fileName).pdf") {
                       // its your file! do what you want with it!
                }
            }
        } catch {
            print("could not locate pdf file !!!!!!!")
        }
    }
}
// check to avoid saving a file multiple times
func pdfFileAlreadySaved(url:String, fileName:String)-> Bool {
    var status = false
    if #available(iOS 10.0, *) {
        do {
            let docURL = try FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false)
            let contents = try FileManager.default.contentsOfDirectory(at: docURL, includingPropertiesForKeys: [.fileResourceTypeKey], options: .skipsHiddenFiles)
            for url in contents {
                if url.description.contains("YourAppName-(fileName).pdf") {
                    status = true
                }
            }
        } catch {
            print("could not locate pdf file !!!!!!!")
        }
    }
    return status
}

我给出了一个在iOS中存储和检索pdf文档的示例。我希望这就是你想要的。

1.如何在我的应用程序上本地保存PDF(例如,如果用户可以输入url),以及它将在哪里保存

// the URL to save
NSURL *yourURL = [NSURL URLWithString:@"http://yourdomain.com/yourfile.pdf"];
// turn it into a request and use NSData to load its content
NSURLRequest *request = [NSURLRequest requestWithURL:result.link];
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
// find Documents directory and append your local filename
NSURL *documentsURL = [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
documentsURL = [documentsURL URLByAppendingPathComponent:@"localFile.pdf"];
// and finally save the file
[data writeToURL:documentsURL atomically:YES];

2.保存时,如何在表视图中显示所有本地存储的文件以打开它们

您可以检查文件是否已下载,也可以列出Documents目录,如下所示:

// list contents of Documents Directory just to check
NSURL *documentsURL = [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
NSArray *contents = [[NSFileManager defaultManager]contentsOfDirectoryAtURL:documentsURL includingPropertiesForKeys:nil options:NSDirectoryEnumerationSkipsHiddenFiles error:nil];
NSLog(@"%@", [contents description]);

使用Swift在Webview中下载并显示PDF。

let request = URLRequest(url:  URL(string: "http://<your pdf url>")!)
        let config = URLSessionConfiguration.default
        let session =  URLSession(configuration: config)
        let task = session.dataTask(with: request, completionHandler: {(data, response, error) in
            if error == nil{
                if let pdfData = data {
                   let pathURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0].appendingPathComponent("(filename).pdf")
                    do {
                        try pdfData.write(to: pathURL, options: .atomic)
                    }catch{
                        print("Error while writting")
                    }
                    DispatchQueue.main.async {
                        self.webView.delegate = self
                        self.webView.scalesPageToFit = true
                        self.webView.loadRequest(URLRequest(url: pathURL))
                    }
                }
            }else{
                print(error?.localizedDescription ?? "")
            }
        }); task.resume()

如果您想在Files应用程序中存储文件,请添加`

NSURL *url = [NSURL URLWithString:@"PATH TO PDF"];
UIDocumentPickerViewController *documentPicker = [[UIDocumentPickerViewController alloc] initWithURL:url inMode:UIDocumentPickerModeExportToService];
[documentPicker setDelegate:self];
[self presentViewController:documentPicker animated:YES completion:nil];

以下是委托方法

- (void)documentPickerWasCancelled:(UIDocumentPickerViewController *)controller {
}
- (void)documentPicker:(UIDocumentPickerViewController *)controller didPickDocumentsAtURLs:(NSArray<NSURL *> *)urls {
}

它将打开DocumentPickerViewController,您可以在其中选择一个文件夹来存储文件。

需要iOS11或更高版本。

如果您想打印目录URL中的PDF数据,请使用:

let printInfo = NSPrintInfo.shared
        let manager = FileManager.default
        do{
            let directoryURL = try manager.url(for: .documentDirectory, in:.userDomainMask, appropriateFor:nil, create:true)
            let docURL = NSURL(string:"LadetagMahlzeiten.pdf", relativeTo:directoryURL)
            let pdfDoc =  PDFDocument.init(url: docURL! as URL)
            let page = CGRect(x: 0, y: 0, width: 595.2, height: 1841.8) // A4, 72 dpi
            let pdfView : PDFView = PDFView.init(frame: page)
            pdfView.document = pdfDoc
            let operation: NSPrintOperation = NSPrintOperation(view: pdfView, printInfo: printInfo)
            operation.printPanel.options.insert(NSPrintPanel.Options.showsPaperSize)
            operation.printPanel.options.insert(NSPrintPanel.Options.showsOrientation)
            operation.run()
        }catch{
        }
        //savePdf(urlString:url, fileName:fileName)
        let urlString = "here String with your URL"
        let url = URL(string: urlString)
        let fileName = String((url!.lastPathComponent)) as NSString
        // Create destination URL
        let documentsUrl:URL =  FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first as URL!
        let destinationFileUrl = documentsUrl.appendingPathComponent("(fileName)")
        //Create URL to the source file you want to download
        let fileURL = URL(string: urlString)
        let sessionConfig = URLSessionConfiguration.default
        let session = URLSession(configuration: sessionConfig)
        let request = URLRequest(url:fileURL!)
        let task = session.downloadTask(with: request) { (tempLocalUrl, response, error) in
            if let tempLocalUrl = tempLocalUrl, error == nil {
                // Success
                if let statusCode = (response as? HTTPURLResponse)?.statusCode {
                    print("Successfully downloaded. Status code: (statusCode)")
                }
                do {
                    try FileManager.default.copyItem(at: tempLocalUrl, to: destinationFileUrl)
                    do {
                        //Show UIActivityViewController to save the downloaded file
                        let contents  = try FileManager.default.contentsOfDirectory(at: documentsUrl, includingPropertiesForKeys: nil, options: .skipsHiddenFiles)
                        for indexx in 0..<contents.count {
                            if contents[indexx].lastPathComponent == destinationFileUrl.lastPathComponent {
                                let activityViewController = UIActivityViewController(activityItems: [contents[indexx]], applicationActivities: nil)
                                self.present(activityViewController, animated: true, completion: nil)
                            }
                        }
                    }
                    catch (let err) {
                        print("error: (err)")
                    }
                } catch (let writeError) {
                    print("Error creating a file (destinationFileUrl) : (writeError)")
                }
            } else {
                print("Error took place while downloading a file. Error description: (error?.localizedDescription ?? "")")
            }
        }
        task.resume()
    }

对于Swift 5及以上版本:将基于PDF的64字符串数据保存到文档目录

创建一个文件夹,用于保存名为的PDF文件

   fileprivate func getFilePath() -> URL? {
            let documentDirectoryURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
            let directoryURl = documentDirectoryURL.appendingPathComponent("Invoice", isDirectory: true)
            
            if FileManager.default.fileExists(atPath: directoryURl.path) {
                return directoryURl
            } else {
                do {
                    try FileManager.default.createDirectory(at: directoryURl, withIntermediateDirectories: true, attributes: nil)
                    return directoryURl
                } catch {
                    print(error.localizedDescription)
                    return nil
                }
            }
        }

将基于PDF的64字符串数据写入文档目录

fileprivate func saveInvoice(invoiceName: String, invoiceData: String) {
    
    guard let directoryURl = getFilePath() else {
        print("Invoice save error")
        return }
    
    let fileURL = directoryURl.appendingPathComponent("(invoiceName).pdf")
    
    guard let data = Data(base64Encoded: invoiceData, options: .ignoreUnknownCharacters) else {
        print("Invoice downloaded Error")
        self.hideHUD()
        return
    }
    
    do {
        try data.write(to: fileURL, options: .atomic)
        print("Invoice downloaded successfully")
    } catch {
        print(error.localizedDescription)
    }
}

相关内容

最新更新