Для этого вам нужно использовать Quicklook, это встроенная функция iOS: -
import Foundation
import UIKit
import QuickLook
class ClassQuickLookFilePreviewHandler {
static let shared = ClassQuickLookFilePreviewHandler()
var url: URL?
var tempURL: URL?
func previewFile(vc: UIViewController, url: URL, fileName: String) {
let previewController = QLPreviewController()
self.url = url
previewController.dataSource = self
previewController.view.tintColor = UIColor(hexString: "#ff3366")
tempURL = FileManager.default.temporaryDirectory.appendingPathComponent(fileName)
previewController.currentPreviewItemIndex = 0
URLSession.shared.dataTask(with: url) { data, _, error in
guard let data = data, error == nil else {
// in case of failure to download your data you need to present alert to the user and update the UI from the main thread
DispatchQueue.main.async {
UIApplication.shared.isNetworkActivityIndicatorVisible = false
let alert = UIAlertController(title: "Alert", message: error?.localizedDescription ?? "Failed to download the pdf!!!", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default))
vc.present(alert, animated: true)
}
return
}
// write the downloaded data to a temporary folder or to the document directory if you want to keep the pdf for later usage
do {
try data.write(to: self.tempURL!, options: .atomic) // atomic option overwrites it if needed
// you neeed to check if the downloaded data is a valid pdf
// and present your controller from the main thread
DispatchQueue.main.async {
UIApplication.shared.isNetworkActivityIndicatorVisible = false
vc.present(previewController, animated: true)
}
} catch {
print(error)
return
}
}.resume()
UIApplication.shared.isNetworkActivityIndicatorVisible = true
}
}
extension ClassQuickLookFilePreviewHandler: QLPreviewControllerDataSource {
func numberOfPreviewItems(in controller: QLPreviewController) -> Int {
return 1
}
func previewController(_ controller: QLPreviewController, previewItemAt index: Int) -> QLPreviewItem {
return tempURL! as QLPreviewItem
}
}
Использование: -
ClassQuickLookFilePreviewHandler.shared.previewFile(vc: self, url: URL(string: ?*documentURL)!, fileName: ?*documentFileName)
Надеюсь, это поможет:)