Как загрузить PDF и сохранить его локально на iPhone?
Я могу успешно просмотреть PDF файл с веб-сайта. Я хочу, чтобы иметь возможность загрузить этот PDF файл на устройство, затем получить доступ к этому файлу локально.
Когда приложение будет открыто, оно проверит дату онлайн-PDF. Если он новее, чем локально сохраненный PDF файл, приложение будет загружать новый, иначе он откроет локально сохраненный PDF файл.
Используемый мной код:
PDFAddress = [NSURL URLWithString:@"http://www.msy.com.au/Parts/PARTS.pdf"];
request = [NSURLRequest requestWithURL:PDFAddress];
[webView loadRequest:request];
webView.scalesPageToFit = YES;
Как я могу это достичь?
Ответы
Ответ 1
Я нашел один метод, который я попробовал сам:
// Get the PDF Data from the url in a NSData Object
NSData *pdfData = [[NSData alloc] initWithContentsOfURL:[
NSURL URLWithString:@"http://www.example.com/info.pdf"]];
// Store the Data locally as PDF File
NSString *resourceDocPath = [[NSString alloc] initWithString:[
[[[NSBundle mainBundle] resourcePath] stringByDeletingLastPathComponent]
stringByAppendingPathComponent:@"Documents"
]];
NSString *filePath = [resourceDocPath
stringByAppendingPathComponent:@"myPDF.pdf"];
[pdfData writeToFile:filePath atomically:YES];
// Now create Request for the file that was saved in your documents folder
NSURL *url = [NSURL fileURLWithPath:filePath];
NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
[webView setUserInteractionEnabled:YES];
[webView setDelegate:self];
[webView loadRequest:requestObj];
Это сохранит ваш PDF локально и загрузит его в ваш UIWebView.
Ответ 2
В Swift 4.1
// Url in String format
let urlStr = "http://www.msy.com.au/Parts/PARTS.pdf"
// Converting string to URL Object
let url = URL(string: urlStr)
// Get the PDF Data form the Url in a Data Object
let pdfData = try? Data.init(contentsOf: url!)
// Get the Document Directory path of the Application
let resourceDocPath = (FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)).last! as URL
// Split the url into a string Array by separator "/" to get the pdf name
let pdfNameFromUrlArr = urlStr.components(separatedBy: "/")
// Appending the Document Directory path with the pdf name
let actualPath = resourceDocPath.appendingPathComponent(pdfNameFromUrlArr[
pdfNameFromUrlArr.count - 1])
// Writing the PDF file data to the Document Directory Path
do {
_ = try pdfData.write(to: actualPath, options: .atomic)
}catch{
print("Pdf can't be saved")
}
// Showing the pdf file name in a label
lblPdfName.text = pdfNameFromUrlArr[pdfNameFromUrlArr.count - 1]
// URLRequest for the PDF file saved in the Document Directory folder
let urlRequest = URLRequest(url: actualPath)
webVw.isUserInteractionEnabled = true
webVw.delegate = self
webVw.loadRequest(urlRequest)
Если вы хотите сохранить Pdf в определенной папке/каталоге в каталоге основного документа
let resourceDocPath = (FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)).last! as URL
// The New Directory/folder name
let newPath = resourceDocPath.appendingPathComponent("QMSDocuments")
// Creating the New Directory inside Documents Directory
do {
try FileManager.default.createDirectory(atPath: newPath.path, withIntermediateDirectories: true, attributes: nil)
} catch let error as NSError {
NSLog("Unable to create directory \(error.debugDescription)")
}
// Split the url into a string Array by separator "/" to get the pdf name
pdfNameFromUrlArr = urlStr.components(separatedBy: "/")
// Appending to the newly created directory path with the pdf name
actualPath = newPath.appendingPathComponent(pdfNameFromUrlArr[pdfNameFromUrlArr.count - 1])
Счастливое кодирование:)
Ответ 3
Вам нужно прочитать Руководство по управлению файлами и данными от Apple. Он будет описывать, какие местоположения доступны в изолированной программной среде приложения для локального сохранения файлов и получения ссылки на эти местоположения. В нем также есть раздел для чтения и записи:)
Наслаждайтесь!
Ответ 4
Я также рекомендую взглянуть на ASIHTTPRequest для легкой загрузки файлов.
Ответ 5
Я нашел для него быструю версию:
let url = "http://example.com/examplePDF.pdf"
if let pdfData = NSData(contentsOfURL: url) {
let resourceDocPath = NSHomeDirectory().stringByAppendingString("/Documents/yourPDF.pdf")
unlink(resourceDocPath)
pdfData.writeToFile(resourceDocPath, atomically: true)
}
Не забудьте сохранить файл пути, и вы сможете его извлекать, когда вам это нужно.
Ответ 6
Загрузка и отображение PDF в Webview с помощью Swift.
let request = URLRequest(url: URL(string: "http://www.msy.com.au/Parts/PARTS.pdf")!)
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()
Ответ 7
func urlSession (_ сессия: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
let path = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)
let documentDirectoryPath:String = path[0]
let fileManager = FileManager()
let destinationURLForFile = URL(fileURLWithPath: documentDirectoryPath.appendingFormat("/BibleFile\(id).pdf"))
do {
try fileManager.moveItem(at: location, to: destinationURLForFile)
// show file
showFileWithPath(path: destinationURLForFile)
}catch{
print("An error occurred while moving file to destination url")
}
}
Ответ 8
С синтаксисом Swift версии 3.0:
let url = NSURL(fileURLWithPath: "http://example.com/examplePDF.pdf")
if let pdfData = NSData(contentsOf: url as URL) {
let resourceDocPath = NSHomeDirectory().appending("/Documents/yourPDF.pdf")
unlink(resourceDocPath)
pdfData.write(toFile: resourceDocPath, atomically: true)
}