我使用以下代码将pdf文件保存到电话文件系统中。
func downloadAndSavePdf (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 = "\(fileName)"
let path = resourceDocPath.appendingPathComponent(pdfNameFromUrl)
do {
try pdfData?.write(to: path, options: .atomic)
print("pdf successfully saved in! \(path)")
} catch {
print("Pdf could not be saved")
}
}
}
当我成功保存后尝试打印路径时,它类似于file:///Users/macuser/Library/Developer/CoreSimulator/Devices/088BF978-9DE7-436B-9E4B-FE1879EA806A/data/Containers/Data/Application/AF3216C3-FEFD-42C6-B8CD-DD7347FCF00C/Documents/myfile.pdf
我的问题是
1.我将把这个文件和路径存储到数据库中,然后再打开它。
2.我无法使用下面的代码打开文件。
func openPdfFile(){
//let pdfView = PDFView()
let webView = WKWebView()
let documentDir = FileManager.SearchPathDirectory.documentDirectory
let userDir = FileManager.SearchPathDomainMask.userDomainMask
let paths = NSSearchPathForDirectoriesInDomains(documentDir, userDir, true)
if let dirPath = paths.first
{
let pdfURL = URL(fileURLWithPath: dirPath).appendingPathComponent("myFile.pdf")
//let image = UIImage(contentsOfFile: imageURL.path)
do {
let data = try Data(contentsOf: pdfURL)
webView.load(data, mimeType: "application/pdf", characterEncodingName:"", baseURL: pdfURL.deletingPathExtension())
print("pdf file loading...")
}
catch {
print("failed to open pdf")
}
return
}
}
呼叫是
openPdfFile()
它无法在Web视图中打开pdf。我打印出了路径,可以在Web浏览器中打开文件。 请帮忙!非常感谢
答案 0 :(得分:0)
好的,现在可以使用了。我需要添加WKWebview组件
到我的视图控制器。然后将其拖动到快速文件
@IBOutlet弱var webView:WKWebView!
现在的问题是Web视图无法扩展到整个屏幕。我不知道如何检测屏幕尺寸并相应地设置网络视图尺寸