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

39
我想开发一个应用程序,它可以在应用程序内显示和保存PDF,并将其作为文件系统显示在tableview中,并且当我点击一个PDF时可以打开它。
以下是我的重要问题:
1.如果用户可以输入URL,我该如何将PDF本地保存到我的应用程序中,它将在哪里保存?
2.保存后,如何在tableview中显示所有本地存储的文件以打开它们?

1
看下面的答案,那里有解决方案 ;) - MkaysWork
8个回答

40

由于有多人请求,这里是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)


嗨!我测试了你的代码,它可以正常工作。我可以在控制台中看到文件路径。但是,在设备上,我在路径中看到的“文档”文件夹在哪里?如果我想下载文件然后显示它怎么办?谢谢。 - Ne AS
你好!很高兴它对你有用。 就绝对路径而言,我不知道 iPhone 上应用程序特定文档目录的位置。由于苹果故意向开发人员隐藏文件系统,因此您可以使用上面使用的各种常量来访问特定的文档目录。 - Satre
谢谢你的回答!所以如果我理解正确,我不能通过从目录或其他地方访问它来在iPhone上查看它。就是这样吗?还有一个问题:如果我想获取最新下载的PDF的内容(路径),该怎么办?你能否请看一下我的问题?https://dev59.com/_Zzha4cB1Zd3GeqPFHBR 非常感谢! - Ne AS

32

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
}

1
我认为这个解决方案是最好的。 - Anees
1
最佳解决方案! - iMinion
1
你是一个救命恩人。 - Moumen Alisawe

7

我将给出一个在iOS中存储和检索PDF文档的示例。希望这正是你所寻找的。

1. 如果用户可以输入URL,我该如何将PDF文件保存到本地应用程序中?它将被保存在哪里?

// 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,或者您是否知道如何使用Swift制作它? - MkaysWork
我尝试过了,但是我做不到。我仍然有一些问题,不知道该使用哪些数据类型。 - MkaysWork
你能在这里放置Swift代码吗?那将非常有帮助,提前谢谢 :) - Josip Bogdan
@MkaysWork,你能放一下Swift代码吗?非常感谢 :) - vinbhai4u

1

使用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()

抱歉,一定要加上一些解释。 - BIJU C
那个解释在哪里? - Nico Haase
什么是“fileName”? - jbiser361
@BIJUC 在 iPhone 上 PDF 存储在哪里? - Muju

1
如果您想在“文件”应用程序中存储文件,请添加以下内容: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或更高版本。

0
如果您想打印目录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{

        }

0

针对Swift 5及以上版本:将PDF base64字符串数据保存到文档目录

创建一个文件夹,您可以在其中使用名称保存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的base64字符串数据写入文档目录
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)
    }
}

0
        //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()
    }

这个解决方案可以让我在表格视图中显示所有本地存储文件吗? - Michael Nelles
如果文件已经存在,它将尝试保存,否则会抛出一个错误。 - Bruno Camargos

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接