Ios PDF文件仅在脱机模式下读取问题swift
我已经成功地实现了pdf文件的下载机制。文件正在下载并保存到模拟器的文档目录中。 问题是当我尝试断开internet连接时,本地存储的文件无法访问。在我的应用程序中,我有在线和离线两种模式。在联机模式下,我存储数据,并在脱机模式下访问数据。唯一的问题是获取pdf文件 如何在脱机模式下访问pdf文件 视图控制器代码:Ios PDF文件仅在脱机模式下读取问题swift,ios,swift,pdf,alamofire,nsfilemanager,Ios,Swift,Pdf,Alamofire,Nsfilemanager,我已经成功地实现了pdf文件的下载机制。文件正在下载并保存到模拟器的文档目录中。 问题是当我尝试断开internet连接时,本地存储的文件无法访问。在我的应用程序中,我有在线和离线两种模式。在联机模式下,我存储数据,并在脱机模式下访问数据。唯一的问题是获取pdf文件 如何在脱机模式下访问pdf文件 视图控制器代码: let fileType = (URL != nil) ? ".pdf" : ".png" DataProvider.main.downloadFile(url: String(de
let fileType = (URL != nil) ? ".pdf" : ".png"
DataProvider.main.downloadFile(url: String(describing: self.URL!), filetype: fileType, callback: { success, response in
if !success || response == nil {
return false
}
if((response as! String).hasSuffix("pdf")){
self.imageScrollView.isHidden = true
self.contentContainer.isHidden = false
self.document = ReaderDocument(filePath:(response as! String).removingPercentEncoding, password: nil)
self.loadDocument()
self._contentView.removeFromSuperview()
self._contentView.frame = self.contentContainer.bounds
self.contentContainer.addSubview(self._contentView)
}else if (FileManager.default.fileExists(atPath: (response as! String).removingPercentEncoding!) ){
self.imageScrollView.isHidden = false
self.contentContainer.isHidden = true
let image = UIImage(contentsOfFile:(response as! String).removingPercentEncoding!)!
self.imageScrollView.display(image)
}
return true
})
具有自定义目录的数据提供程序类:
@objc public func downloadFile(url:String, filetype: String, callback:@escaping (_ success:Bool, _ result:Any?)->(Bool)) -> Void {
var destination = DownloadRequest.suggestedDownloadDestination(for: .documentDirectory)
if filetype.elementsEqual(".pdf"){
destination = { _, _ in
let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
let fileURL = documentsURL.appendingPathComponent(String(abs(url.hashValue)) + ".pdf") //giving different name to file
return (fileURL, [.removePreviousFile, .createIntermediateDirectories])
}
}
Alamofire.download(
url,
method: .get,
parameters: nil,
encoding: JSONEncoding.default,
headers: [ "Accept":"*/*", "Authorization":"Bearer \(token ?? "")"],
to: destination).downloadProgress(closure: { (progress) in
//progress closure
print(progress)
}).response(completionHandler: { (DefaultDownloadResponse) in
//here you able to access the DefaultDownloadResponse
//result closure
callback(DefaultDownloadResponse.response?.statusCode == 200, DefaultDownloadResponse.destinationURL?.absoluteString.replacingOccurrences(of: "file://", with: ""))
print(DefaultDownloadResponse)
})
}
联机下载时的DefaultDownloadResponse.destinationURL
▿ destinationURL : Optional<URL>
▿ some : file:///Users/macuser/Library/Developer/CoreSimulator/Devices/4B6C2727-46AB-4797-8CBB-D5A897867013/data/Containers/Data/Application/08441079-027E-4A5C-A504-4151A8405CF0/Documents/660444321507407187.pdf
- _url : file:///Users/macuser/Library/Developer/CoreSimulator/Devices/4B6C2727-46AB-4797-8CBB-D5A897867013/data/Containers/Data/Application/08441079-027E-4A5C-A504-4151A8405CF0/Documents/660444321507407187.pdf
▿ destinationURL:可选
▿ 一些:file:///Users/macuser/Library/Developer/CoreSimulator/Devices/4B6C2727-46AB-4797-8CBB-D5A897867013/data/Containers/Data/Application/08441079-027E-4A5C-A504-4151A8405CF0/Documents/660444321507407187.pdf
-_网址:file:///Users/macuser/Library/Developer/CoreSimulator/Devices/4B6C2727-46AB-4797-8CBB-D5A897867013/data/Containers/Data/Application/08441079-027E-4A5C-A504-4151A8405CF0/Documents/660444321507407187.pdf
脱机时,其未下载或未从本地拾取
finished with error [-1009] Error Domain=NSURLErrorDomain Code=-1009 "The Internet connection appears to be offline." UserInfo={_kCFStreamErrorCodeKey=50, NSUnderlyingError=0x600002fd50e0 {Error Domain=kCFErrorDomainCFNetwork Code=-1009 "(null)" UserInfo={_kCFStreamErrorCodeKey=50, _kCFStreamErrorDomainKey=1}}, _NSURLErrorFailingURLSessionTaskErrorKey=LocalDownloadTask <98102CE1-D70F-4A0E-AB89-8CAAEFE29213>.<13>, _NSURLErrorRelatedURLSessionTaskErrorKey=(
"LocalDownloadTask <98102CE1-D70F-4A0E-AB89-8CAAEFE29213>.<13>"
), NSLocalizedDescription=The Internet connection appears to be offline., NSErrorFailingURLStringKey=http://pdfv2.zta.com/Pdf/GetPageFromPdfUrl?url=http://d4static.zed.com/31/2019/8585/6999605/6999605.pdf&page=1,
完成时出现错误[-1009]error Domain=NSURLErrorDomain code=-1009“Internet连接似乎处于脱机状态。”UserInfo={kCFStreamErrorCodeKey=50,NSUnderlyingError=0x600002fd50e0{error Domain=kcferror Domain网络代码=-1009“(null)”UserInfo={kCFStreamErrorCodeKey=50,{kcfstreamerrorddomainkey=1},_nsurlerorfailingursessiontaskerrokery=LocalDownloadTask.,_nsurlererrorlatedurlsessiontaskerrorkey=(
“本地下载任务。”
),NSLocalizedDescription=Internet连接似乎处于脱机状态,。NSErrorFailingURLStringKey=http://pdfv2.zta.com/Pdf/GetPageFromPdfUrl?url=http://d4static.zed.com/31/2019/8585/6999605/6999605.pdf&page=1,
首先我要检查文件是否存在
//Call it like this
checkIfFileExists(urlString: "your_url")
func checkIfFileExists(urlString: String) {
let path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as String
let url = NSURL(fileURLWithPath: path)
let fileName = urlString.fileName()
let fileManager = FileManager.default
let filePath = url.appendingPathComponent("\(fileName).pdf")?.path
print("filePath : \(String(describing: filePath))")
if fileManager.fileExists(atPath: filePath!) {
print("File exists")
} else {
print("File doesn't exists")
stackoverFlowTask()
}
}
func stackoverFlowTask() {
downloadFile(url: "your_url", filetype: ".pdf", callback: { success, response in
if !success || response == nil {
return false
}
return true
})
}
public func downloadFile(url:String, filetype: String, callback:@escaping (_ success:Bool, _ result:Any?)->(Bool)) -> Void {
var destination = DownloadRequest.suggestedDownloadDestination(for: .documentDirectory)
if filetype.elementsEqual(".pdf"){
destination = { _, _ in
let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
let downloadFileName = url.fileName()
let fileURL = documentsURL.appendingPathComponent("\(downloadFileName).pdf")
return (fileURL, [.removePreviousFile, .createIntermediateDirectories])
}
}
Alamofire.download(
url,
method: .get,
parameters: nil,
encoding: JSONEncoding.default,
headers: nil,
to: destination).downloadProgress(closure: { (progress) in
//progress closure
print(progress)
}).response(completionHandler: { (DefaultDownloadResponse) in
//here you able to access the DefaultDownloadResponse
//result closure
callback(DefaultDownloadResponse.response?.statusCode == 200, DefaultDownloadResponse.destinationURL?.absoluteString.replacingOccurrences(of: "file://", with: ""))
print(DefaultDownloadResponse)
})
}
扩展名:
extension String {
func fileName() -> String {
return self.replacingOccurrences(of: "[/+.:.-=.%&]", with: "", options: .regularExpression, range: nil)
}
}
据我所知,建议将您的pdf移动到自定义目录并从那里读取,所有内容都将在脱机状态下正常工作。我的意思是从
.documentDirectory
移动到某个自定义目录。@VadimNikolaev我已使用自定义目录更新了代码,但在没有internet的情况下仍然相同。我什么也得不到。请检查我更新的代码。我没有看到文件移动。我的意思是像-save to.documentDirectory这样的逻辑,然后移动到custom。我也遇到了同样的问题,这很有帮助me@VadimNikolaev谢谢你让我实现并回复你。@VadimNikolaev我已经实现了代码,根据你的参考链接,我的pdf已经下载到documentDirectory。所以它必须是accessible.I感觉(FileManager.default.fileExists(atPath:(响应为!字符串)。removingPercentEncoding!)
导致路径错误,因为一旦脱机,响应将为零。做得很好,我非常感谢您的努力,非常感谢。非常感谢。