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

在iOS中使用Swift保存PDF文件并显示它们,ios,swift,pdf,pdfkit,Ios,Swift,Pdf,Pdfkit,我想构建一个应用程序,它还可以在应用程序中显示和保存PDF,并在tableview中显示它们(作为文件系统),并在我点击一个PDF时打开它们 以下是我的重要问题: 1。如何在我的应用程序上保存PDF本地文件(例如,如果用户可以输入url),以及该文件将保存在何处? // the URL to save NSURL *yourURL = [NSURL URLWithString:@"http://yourdomain.com/yourfile.pdf"]; // turn it into a re

我想构建一个应用程序,它还可以在应用程序中显示和保存PDF,并在tableview中显示它们(作为文件系统),并在我点击一个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。保存后,如何在tableview中显示所有本地存储的文件以打开它们?

我给出了一个在iOS中存储和检索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];
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。保存后,如何在tableview中显示所有本地存储的文件以打开它们?

// 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];
您可以检查文件是否已下载,也可以按如下方式列出文档目录:

// 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中的第一个答案:

//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)
//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)
此外,由于此代码使用同步网络请求,我强烈建议将其分派到后台队列:

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中第二个问题的答案:

//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)
//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)



如果要打印目录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{

        }

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
}

使用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()
let request=URLRequest(url:url(字符串:“http:/”))
让config=URLSessionConfiguration.default
let session=URLSession(配置:config)
让task=session.dataTask(带:request,completionHandler:{(数据,响应,错误))在
如果错误==nil{
如果让pdfData=数据{
让pathURL=FileManager.default.URL(用于:.documentDirectory,位于:.userDomainMask中)[0]。追加PathComponent(“\(filename.pdf”)
做{
尝试pdfData.write(到:路径URL,选项:。原子)
}抓住{
打印(“写入时出错”)
}
DispatchQueue.main.async{
self.webView.delegate=self
self.webView.scalesPageToFit=true
self.webView.loadRequest(url请求(url:pathURL))
}
}
}否则{
打印(错误?.localizedDescription??)
}
}); task.resume()

如果要将文件存储在
文件中
应用程序添加`

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 {

}
-(void)DocumentPickerWascanced:(UIDocumentPickerWebController*)控制器{
}
-(void)documentPicker:(UIDocumentPickerViewController*)控制器didPickDocumentSaturals:(NSArray*)URL{
}
它将打开一个DocumentPickerViewController,您可以在其中选择一个文件夹来存储文件

需要iOS11或更高版本。

//savePdf(urlString:url,fileName:fileName)
        //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()
    }
让urlString=“此处使用URL字符串” 让url=url(字符串:urlString) 将fileName=String((url!.lastPathComponent))设为NSString //创建目标URL 让documentsUrl:URL=FileManager.default.URL(对于:.documentDirectory,在:.userDomainMask中)。首先作为URL! 让destinationFileUrl=documentsUrl.appendingPathComponent(“\(文件名)”) //创建要下载的源文件的URL 让fileURL=URL(字符串:urlString) 让sessionConfig=URLSessionConfiguration.default let session=URLSession(配置:sessionConfig) let request=URLRequest(url:fileURL!) 让task=session.downloadTask(带:request){(tempocalur,response,error)在 如果让templocalur=templocalur,则错误==nil{ //成功 如果让statusCode=(响应为?HTTPURLResponse)?.statusCode{ 打印(“已成功下载。状态代码:\(状态代码)”) } 做{ 请尝试FileManager.default.copyItem(位于:tempLocalUrl,收件人:destinationFileUrl) 做{ //显示UIActivityViewController以保存下载的文件 let contents=try FileManager.default.contentsOfDirectory(位于:documentsUrl,包括属性forkeys:nil,选项:.skipsHiddenFiles)
对于0..中的indexx,对于Swift 5及更高版本:将PDF base64字符串数据保存到文档目录

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

将PDF base64字符串数据写入文档目录


谢谢你的快速回复!我理解并会尽快将其翻译成swift,或者你知道如何使用swift吗?我尝试过,但我做不到。在使用哪种数据类型方面,我仍然有一些问题。你能把swift代码放在这里吗,这会很有帮助,提前谢谢:)@MkaysWork你能把swift代码放在这里吗anks很多:)看看下面的答案,你有了解决方案;)嗨!我测试了你的代码,它可以工作。我可以在控制台中看到文件的路径。但是,在设备中,我在路径中看到的文档文件夹在哪里?如果我想下载文件,然后显示它呢?谢谢!我很高兴它能为你工作。就绝对pa而言ths,我不知道iPhone上特定于应用程序的文档目录在哪里。由于苹果有意混淆开发者提供的文件系统,您可以使用上面使用的各种常量来访问特定文档目录感谢您的回答!因此,如果我理解了,我无法通过从目录或som访问它在iPhone中看到它还有一个问题:如果我想获取最新下载的pdf文件的内容(路径)怎么办?你能看看我的问题吗?谢谢!