我能够从网站成功查看PDF。我希望能够将该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;
我如何实现这一目标?
答案 0 :(得分:49)
我找到了一种自己尝试的方法:
// 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中。
答案 1 :(得分: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])
快乐编码:)
答案 2 :(得分:0)
您需要阅读Apple的File and Data Management Guide。它将描述应用程序沙箱中可用于在本地保存文件的位置以及如何获取对这些位置的引用。它还有一个阅读和写作部分:)
享受!
答案 3 :(得分:0)
我还建议您查看ASIHTTPRequest以便轻松下载文件。
答案 4 :(得分:0)
我找到了一个快速版本:
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)
}
请记住保存路径文件,并且您可以在需要时随时获取它。
答案 5 :(得分:0)
使用Swift在Webview中下载并显示PDF。
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()
答案 6 :(得分:-1)
使用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)
}