Getting an error zipfail error in swift ios - swift

Given the code below I am successfully downloading my tar.gz file but when I try unzip it I get
Error creating a file file:///Users/xxxxx/Library/Developer/CoreSimulator/Devices/346A7980-8EFB-4ACE-88FC-617C9533E893/data/Containers/Data/Application/22F22B8E-2C15-4C17-B6CD-3777B66D2AAE/Documents/ : unzipFail
Can anyone tell me what I am doing wrong?
import UIKit
import WebKit
import Zip
class ViewController: UIViewController, WKUIDelegate {
var webView: WKWebView!
override func loadView() {
let webConfiguration = WKWebViewConfiguration()
webView = WKWebView(frame: .zero, configuration: webConfiguration)
webView.uiDelegate = self
view = webView
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
// Create destination URL
let documentsUrl:URL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
let destinationFileUrl = documentsUrl.appendingPathComponent("data.tar.gz")
//Create URL to the source file you want to download
let fileURL = URL(string: "https:/www.myurl.com/data.tar.gz")
let sessionConfig = URLSessionConfiguration.default
let session = URLSession(configuration: sessionConfig)
let request = URLRequest(url:fileURL!)
let task = session.downloadTask(with: request) { (tempLocalUrl, response, error) in
if let tempLocalUrl = tempLocalUrl, error == nil {
// Success
if let statusCode = (response as? HTTPURLResponse)?.statusCode {
print("Successfully downloaded. Status code: \(statusCode)")
do {
try? FileManager.default.removeItem(at: destinationFileUrl)
try FileManager.default.copyItem(at: tempLocalUrl, to: destinationFileUrl)
let unzipDirectory = try Zip.quickUnzipFile(destinationFileUrl)
} catch (let writeError) {
print("Error creating a file \(documentsUrl) : \(writeError)")
}
}
} else {
print("Error took place while downloading a file. Error description: %#", error?.localizedDescription);
}
}
task.resume()
}

The problem was that the tar.gz is not supported. I used an alternative library

Related

How to download a blob URI using AlamoFire

I am trying to work with a WKWebView in swift and currently have a download engine using AlamoFire. I have run into a site that uses the blob: url scheme to download items. Is there a way to download blob files using AlamoFire or WKWebView in general?
My specific goal is to download the content from this blob URI to a file.
I would appreciate any help. Thank you.
All relevant code is attached below.
Here's the URL I was having a problem with:
blob:https://cubari.moe/87d49857-dfef-4f0f-bb83-db8517fd3094
Here is the error in my logs:
2021-12-10 22:41:45.382527-0500 Asobi[14529:358202] -canOpenURL: failed for URL: "blob:https://cubari.moe/87d49857-dfef-4f0f-bb83-db8517fd3094" - error: "This app is not allowed to query for scheme blob"
2021-12-10 22:41:45.474214-0500 Asobi[14529:358357] Task <4B011CC1-60E9-4AAD-98F0-BB6A6D0C92FB>.<1> finished with error [-1002] Error Domain=NSURLErrorDomain Code=-1002 "unsupported URL" UserInfo={NSLocalizedDescription=unsupported URL, NSErrorFailingURLStringKey=blob:https://cubari.moe/87d49857-dfef-4f0f-bb83-db8517fd3094, NSErrorFailingURLKey=blob:https://cubari.moe/87d49857-dfef-4f0f-bb83-db8517fd3094, _NSURLErrorRelatedURLSessionTaskErrorKey=(
"LocalDownloadTask <4B011CC1-60E9-4AAD-98F0-BB6A6D0C92FB>.<1>"
), _NSURLErrorFailingURLSessionTaskErrorKey=LocalDownloadTask <4B011CC1-60E9-4AAD-98F0-BB6A6D0C92FB>.<1>, NSUnderlyingError=0x6000017e99b0 {Error Domain=kCFErrorDomainCFNetwork Code=-1002 "(null)"}}
2021-12-10 22:41:45.476703-0500 Asobi[14529:358202] [Process] 0x124034e18 - [pageProxyID=6, webPageID=7, PID=14540] WebPageProxy::didFailProvisionalLoadForFrame: frameID=3, domain=WebKitErrorDomain, code=102
Failed provisional nav: Error Domain=WebKitErrorDomain Code=102 "Frame load interrupted" UserInfo={_WKRecoveryAttempterErrorKey=<WKReloadFrameErrorRecoveryAttempter: 0x6000019a88c0>, NSErrorFailingURLStringKey=blob:https://cubari.moe/87d49857-dfef-4f0f-bb83-db8517fd3094, NSErrorFailingURLKey=blob:https://cubari.moe/87d49857-dfef-4f0f-bb83-db8517fd3094, NSLocalizedDescription=Frame load interrupted}
Here is the code for my download decision handler in WKNavigation decision policy
// Check if a page can be downloaded
func webView(_ webView: WKWebView,
decidePolicyFor navigationResponse: WKNavigationResponse,
decisionHandler: #escaping (WKNavigationResponsePolicy) -> Void) {
if navigationResponse.canShowMIMEType {
decisionHandler(.allow)
} else {
let url = navigationResponse.response.url
// Alternative to decisionHandler(.download) since that's iOS 15 and up
//let documentUrl = url?.appendingPathComponent(navigationResponse.response.suggestedFilename!)
parent.webModel.downloadDocumentFrom(url: url!)
decisionHandler(.cancel)
}
}
Here is the code for my download data function (it uses the AF.download method)
// Download file from page
func downloadDocumentFrom(url downloadUrl : URL) {
if currentDownload != nil {
showDuplicateDownloadAlert = true
return
}
let queue = DispatchQueue(label: "download", qos: .userInitiated)
var lastTime = Date()
let destination: DownloadRequest.Destination = { tempUrl, response in
let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
let suggestedName = response.suggestedFilename ?? "unknown"
let fileURL = documentsURL.appendingPathComponent(suggestedName)
return (fileURL, [.removePreviousFile, .createIntermediateDirectories])
}
self.showDownloadProgress = true
currentDownload = AF.download(downloadUrl, to: destination)
.downloadProgress(queue: queue) { progress in
if Date().timeIntervalSince(lastTime) > 1.5 {
lastTime = Date()
DispatchQueue.main.async {
self.downloadProgress = progress.fractionCompleted
}
}
}
.response { response in
DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
self.showDownloadProgress = false
self.downloadProgress = 0.0
}
if response.error == nil, let currentPath = response.fileURL {
self.downloadFileUrl = currentPath
self.showFileMover = true
}
if let error = response.error {
self.errorDescription = "Download could not be completed. \(error)"
self.showError = true
}
}
}
After a few days, I was able to figure out how to download a blob URL without WKDownloadDelegate. The following code builds upon this answer.
A message handler needs to be created to respond to JS messages. I created this in the makeUIView function
webModel.webView.configuration.userContentController.add(context.coordinator, name: "jsListener")
Inside your WKNavigationDelegate, you need to add this code on a navigation action.
NOTE: Since I use SwiftUI, all of my variables/models are located in the parent class (UIViewRepresentable coordinator).
func webView(_ webView: WKWebView,
decidePolicyFor navigationAction: WKNavigationAction,
decisionHandler: #escaping (WKNavigationActionPolicy) -> Void) {
if let url = navigationAction.request.url, let scheme = url.scheme?.lowercased() {
if scheme == "blob" {
// Defer to JS handling
parent.webModel.executeBlobDownloadJS(url: url)
decisionHandler(.cancel)
} else {
decisionHandler(.allow)
}
}
}
Here's the JS to request for the blob stored in the browser memory. I added this JS in a wrapper function which called evaluateJavaScript with the url for cleanliness of my code.
function blobToDataURL(blob, callback) {
var reader = new FileReader()
reader.onload = function(e) {callback(e.target.result.split(",")[1])}
reader.readAsDataURL(blob)
}
async function run() {
const url = "\(url)"
const blob = await fetch(url).then(r => r.blob())
blobToDataURL(blob, datauri => {
const responseObj = {
url: url,
mimeType: blob.type,
size: blob.size,
dataString: datauri
}
window.webkit.messageHandlers.jsListener.postMessage(JSON.stringify(responseObj))
})
}
run()
In addition to the returned JS object, I had to make a struct where I can deserialize the JSON string:
struct BlobComponents: Codable {
let url: String
let mimeType: String
let size: Int64
let dataString: String
}
I then took the messages sent to the WKScriptMessageHandler and interpreted them for saving to files. I used the SwiftUI file mover here, but you can do anything you want with this content.
func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
guard let jsonString = message.body as? String else {
return
}
parent.webModel.blobDownloadWith(jsonString: jsonString)
}
In my web model (needed to import CoreServices):
func blobDownloadWith(jsonString: String) {
guard let jsonData = jsonString.data(using: .utf8) else {
print("Cannot convert blob JSON into data!")
return
}
let decoder = JSONDecoder()
do {
let file = try decoder.decode(BlobComponents.self, from: jsonData)
guard let data = Data(base64Encoded: file.dataString),
let uti = UTTypeCreatePreferredIdentifierForTag(kUTTagClassMIMEType, file.mimeType as CFString, nil),
let ext = UTTypeCopyPreferredTagWithClass(uti.takeRetainedValue(), kUTTagClassFilenameExtension)
else {
print("Error! \(error)")
return
}
let fileName = file.url.components(separatedBy: "/").last ?? "unknown"
let path = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
let url = path.appendingPathComponent("blobDownload-\(fileName).\(ext.takeRetainedValue())")
try data.write(to: url)
downloadFileUrl = url
showFileMover = true
} catch {
print("Error! \(error)")
return
}
}

Opening a PDF stored in local memory in a PDFView SWIFT

I have downloaded a pdf file to my cache memory.Now I wish to open this PDF file in a PDFView.
I have added a PDFView to my ViewController, here is the code for the same.
let pdfView = PDFView()
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(pdfView)
}
The below given code will return the location to which the PDF was downloaded as a URL.
guard let pdfURL = downloader.downloadData(urlString: "https://www.tutorialspoint.com/swift/swift_tutorial.pdf", downloadType: DownloadType.cache.rawValue) else { return }
I have checked the URL given back and the file exists.
Now in the following code I am trying to open it in the pdf view.
if let document = PDFDocument(url: pdfURL) {
pdfView.document = document
}
Below given code shows the download data method.
public func downloadData(urlString : String,downloadType : String)->URL?{
let documentsUrl:URL = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first as URL!
var destinationFileUrl = documentsUrl.appendingPathComponent("downloadedFile.pdf")
try? FileManager.default.removeItem(at: destinationFileUrl)
guard let url = URL(string: urlString)else{
return nil
}
let urlSession = URLSession(configuration: .default)
let downloadTask = urlSession.downloadTask(with: url) { (tempLocalUrl, response, error) in
if let tempLocalUrl = tempLocalUrl, error == nil {
if let statusCode = (response as? HTTPURLResponse)?.statusCode {
print("Successfully downloaded. Status code: \(statusCode)")
}
if downloadType == "cache" {
do {
try? FileManager.default.removeItem(at: destinationFileUrl)
try FileManager.default.copyItem(at: tempLocalUrl, to: destinationFileUrl)
} catch (let writeError) {
print("Error creating a file \(destinationFileUrl) : \(writeError)")
}
}
} else {
print("Error took place while downloading a file. Error description: %#", error?.localizedDescription);
}
}
downloadTask.resume()
return destinationFileUrl
}
But it seems like it is returning nil and the code inside if let block is not executed. Please Help!!
Nil of course.
return destinationFileUrl, use it to init PDF, gets nil.
it returns, While the task is still executing, so the file in the path not exists.
Because downloading is an asynchronous action.
So here is completionHandler closure for.
Ususlly, turn this
public func downloadData(urlString : String,downloadType : String)->URL?{
let documentsUrl:URL = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first as URL!
var destinationFileUrl = documentsUrl.appendingPathComponent("downloadedFile.pdf")
try? FileManager.default.removeItem(at: destinationFileUrl)
guard let url = URL(string: urlString)else{
return nil
}
let urlSession = URLSession(configuration: .default)
let downloadTask = urlSession.downloadTask(with: url) { (tempLocalUrl, response, error) in
if let tempLocalUrl = tempLocalUrl, error == nil {
if let statusCode = (response as? HTTPURLResponse)?.statusCode {
print("Successfully downloaded. Status code: \(statusCode)")
}
if downloadType == "cache" {
do {
try? FileManager.default.removeItem(at: destinationFileUrl)
try FileManager.default.copyItem(at: tempLocalUrl, to: destinationFileUrl)
} catch (let writeError) {
print("Error creating a file \(destinationFileUrl) : \(writeError)")
}
}
} else {
print("Error took place while downloading a file. Error description: %#", error?.localizedDescription);
}
}
downloadTask.resume()
return destinationFileUrl
}
into
public func downloadData(urlString : String,downloadType : String, completionHandler: #escaping (URL) -> Void){
let documentsUrl:URL = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first as URL!
var destinationFileUrl = documentsUrl.appendingPathComponent("downloadedFile.pdf")
try? FileManager.default.removeItem(at: destinationFileUrl)
guard let url = URL(string: urlString)else{
return nil
}
let urlSession = URLSession(configuration: .default)
let downloadTask = urlSession.downloadTask(with: url) { (tempLocalUrl, response, error) in
if let tempLocalUrl = tempLocalUrl, error == nil {
if let statusCode = (response as? HTTPURLResponse)?.statusCode {
print("Successfully downloaded. Status code: \(statusCode)")
}
if downloadType == "cache" {
do {
try? FileManager.default.removeItem(at: destinationFileUrl)
try FileManager.default.copyItem(at: tempLocalUrl, to: destinationFileUrl)
completionHandler(destinationFileUrl)
} catch (let writeError) {
print("Error creating a file \(destinationFileUrl) : \(writeError)")
}
}
} else {
print("Error took place while downloading a file. Error description: %#", error?.localizedDescription);
}
}
downloadTask.resume()
}
In the completionHandler call back , init the PDF

View pdf in swift 4

i have tried everything on internet to add a PDFViewer in my app. im working with ios 12. im asking you to help me understand what is the possible ways to add a pdf and a solution that can solve it in a easy way for my low experience with swift coding. thank you
We can use our native UIDocumentInteractionController for the same.
Follow below steps :
Step 1
var documentInteractionController = UIDocumentInteractionController()
Step 2
self.documentInteractionController.delegate = self
Step 3
func openDocument(atURL url: URL, screenTitle: String) {
self.documentInteractionController.url = url
self.documentInteractionController.name = screenTitle
self.documentInteractionController.delegate = self
self.documentInteractionController.presentPreview(animated: true)
}
Step 4 : Implement UIDocumentInteractionControllerDelegate
extension ViewController: UIDocumentInteractionControllerDelegate {
// when a document interaction controller needs a view controller for presenting a document preview.
func documentInteractionControllerViewControllerForPreview(_ controller: UIDocumentInteractionController) -> UIViewController {
return self.navigationController ?? UIViewController()
}
}
Some helper methods :
a) View Pdf
func viewPdf(urlPath: String, screenTitle: String) {
// open pdf for booking id
guard let url = urlPath.toUrl else {
print("Please pass valid url")
return
}
self.downloadPdf(fileURL: url, screenTitle: screenTitle) { localPdf in
if let url = localPdf {
DispatchQueue.main.sync {
self.openDocument(atURL: url, screenTitle: screenTitle)
}
}
}
}
b) function for download file
// method for download pdf file
func downloadPdf(fileURL: URL, screenTitle: String, complition: #escaping ((URL?) -> Void)) {
// Create destination URL
if let documentsUrl: URL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first {
let destinationFileUrl = documentsUrl.appendingPathComponent("\(screenTitle).pdf")
if FileManager.default.fileExists(atPath: destinationFileUrl.path) {
try? FileManager.default.removeItem(at: destinationFileUrl)
}
let sessionConfig = URLSessionConfiguration.default
let session = URLSession(configuration: sessionConfig)
let request = URLRequest(url: fileURL)
let task = session.downloadTask(with: request) { tempLocalUrl, response, error in
if let tempLocalUrl = tempLocalUrl, error == nil {
// Success
if let statusCode = (response as? HTTPURLResponse)?.statusCode {
print("Successfully downloaded. Status code: \(statusCode)")
}
do {
try FileManager.default.copyItem(at: tempLocalUrl, to: destinationFileUrl)
complition(destinationFileUrl)
} catch let writeError {
print("Error creating a file \(destinationFileUrl) : \(writeError)")
}
} else {
print("Error took place while downloading a file. Error description: \(error?.localizedDescription ?? "N/A")")
}
}
task.resume()
} else {
complition(nil)
}
}
here I am Downloading PDF and store on in File And Open That file in Quick Look
Here I am sharing screen
enter image description here
Reference link: https://www.hackingwithswift.com/example-code/libraries/how-to-preview-files-using-quick-look-and-qlpreviewcontroller
If you just need to present the PDF, you could use a WebView from WebKit and pass the data using the mimetype application/pdf.
like this:
webView.load(data, mimeType: "application/pdf", characterEncodingName: "UTF-8", baseURL: baseURL)

Swift3 file preview not working

I think something changed within Swift that disabled me from previewing my files. It worked fine previously. If I click on say a PDF file in my app, I see the title of the PDF, but the content of PDF (preview) area does not show.
Below is my code & logs & also the screenshot. If anyone has an idea of where I can fix the issue, any help would be greatly appreciated.
// When file is clicked this method is called
#objc private func handleTapped() {
guard let url = self.file.fileUrl else { return }
if self.file.isDownloaded {
self.showDocumentController(url: self.file.urlInDocumentsDirectory! as NSURL)
return
}
SVProgressHUD.showProgress(0)
let destination: DownloadRequest.DownloadFileDestination = { _, _ in
let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
let fileURL = documentsURL.appendingPathComponent("pig.png")
return (documentsURL, [.removePreviousFile, .createIntermediateDirectories])
}
Alamofire.download(url, to: destination)
.downloadProgress { (download) in
DispatchQueue.main.async() {
SVProgressHUD.showProgress(Float(download.fractionCompleted))
}
}.validate(statusCode: 200..<300)
.response { (response) in
SVProgressHUD.dismiss()
guard response.response?.statusCode == 200 else { return }
let directoryURL = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
let pathURL = URL(fileURLWithPath: directoryURL, isDirectory: true)
//pathURL: file:///var/mobile/Containers/Data/Application/6DDCCC30-107C-4613-B63D-18962C3D06D3/Documents/
guard let fileName = response.response?.suggestedFilename else { return }
//fileName: 05_기조강연_RobertMankin_BETTER+OFFICES+GREATER+INNOVATION.pdf
let fileURL = pathURL.appendingPathComponent(fileName)
//fileURL: file:///var/mobile/Containers/Data/Application/6DDCCC30-107C-4613-B63D-18962C3D06D3/Documents/05_%E1%84%80%E1%85%B5%E1%84%8C%E1%85%A9%E1%84%80%E1%85%A1%E1%86%BC%E1%84%8B%E1%85%A7%E1%86%AB_RobertMankin_BETTER+OFFICES+GREATER+INNOVATION.pdf
self.saveFileURL(url: fileURL as NSURL)
self.showDocumentController(url: fileURL as NSURL)
}
}
private func saveFileURL(url: NSURL) {
self.file.urlInDocumentsDirectory = url as URL
let realm = RealmService.defaultRealm
try! realm?.write {
realm?.add(self.file, update: true)
}
self.file = self.file.copyFromRealm()
}
private func showDocumentController(url: NSURL) {
let docController = UIDocumentInteractionController(url: url as URL)
docController.delegate = self
docController.presentPreview(animated: true)
}
// MARK: UIDocumentInteractionControllerDelegate methods
func documentInteractionControllerViewControllerForPreview(_ controller: UIDocumentInteractionController) -> UIViewController {
if let controller = UIApplication.shared.keyWindow?.topMostViewController() {
return controller
}
return UIViewController()
}
this is how the preview shows
Here Is The Code
import UIKit
import Alamofire
class ViewController: UIViewController, UIWebViewDelegate
{
#IBOutlet weak var WebView: UIWebView!
var NewsURL: String = ""
override func viewDidLoad()
{
super.viewDidLoad()
Self.LoadPdf()
}
func LoadPdf()
{
let url = NSURL (string: "\(http://)") //Your Pdf URL Here
let requestObj = NSURLRequest(URL: url!);
WebView.loadRequest(requestObj)
}
}

Swift3 ios10 Xcode8 saving and loading pdfs to and from device

(this is my first post here, I am sorry for any mistakes i have made)
i have code that works perfectly on the iOS simulator but once i run it on a real device it shows online a white screen and this error: com.apple.WebKit.WebContent: 113: Could not find specified service
this is my code for downloading a pdf file from firebase to the device:
#IBAction func downloadButtonPressed (sender: UIButton) {
print("zzz download button pressed")
let directoryPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true) //FileManager().url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
if directoryPath.count > 0 {
let documentsDirectory = directoryPath[0]
let pathURL = URL(fileURLWithPath: documentsDirectory)
let fileURL = pathURL.appendingPathComponent("\(fixture.id).pdf")
let httpsReference = FIRStorage.storage().reference(forURL: fixture.onlineManual)
print("zzz urlManual: \(fixture.onlineManual)")
let downloadTask = httpsReference.write(toFile: fileURL) {(URL, error) in
if error != nil {
print("downloadError with pdf")
print(error?.localizedDescription)
} else {
print("zzz donwload successful: \(URL!)")
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let context = appDelegate.persistentContainer.viewContext
let newManual = NSEntityDescription.insertNewObject(forEntityName: "OfflineManuals", into: context)
newManual.setValue(self.fixture.id, forKey: "id")
newManual.setValue("\(URL!)", forKey: "manual")
do {
try context.save()
print("zzz manual saved to device")
} catch {
print("zzz error saving manual to core data")
}
}
}
}
}
this is the code that loads the file from the device and displays it in a WKWebView
func loadRequest() {
let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
if documentsPath.count > 0 {
let documentsDirectory = documentsPath[0]
let restorePath = documentsDirectory + "/\(manualURL!).pdf"
let url = URL(fileURLWithPath: restorePath)
print("zzz url for local file: \(url)")
let req = URLRequest(url: url)
webView.load(req)
}
}
thank you for reading!
I finally found a way to do this. I still have no clou why my code in the question does not work on real devices but this one does and since i found a lot of people with similar problems desperatly looking for an answer use this:
SWIFT3 XCODE 8 IOS 10
import UIKit
import WebKit
class ViewController: UIViewController {
#IBOutlet weak var myView: UIView!
var webView: WKWebView!
let sema = DispatchSemaphore( value: 0 )
override func viewDidLoad() {
super.viewDidLoad()
webView = WKWebView()
myView.addSubview(webView)
savePDFtoDevice()
loadPDF()
}
the LayoutSubviews is not needed but i had problems without it...
override func viewDidLayoutSubviews() {
print("zzz width: \(self.myView.frame.size.width), height: \(myView.frame.size.height)")
print("zzz width screen: \(self.view.frame.width)")
let frame = CGRect(x: 30.0, y: 30.0, width: (self.myView.frame.width - 60), height: 300)
webView.frame = frame
}
func savePDFtoDevice(){
let myURL = URL(string: "http://www.claypaky.it/media/documents/HR_Mythos_Manual_05.2016_EN.pdf")
let req = URLRequest(url: myURL!)
let session = URLSession(configuration: .default)
session.dataTask(with: req) { (data, response, error) in
if error != nil {
print("zzz error got no session")
} else {
if let pdfData = data {
var url = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
url = url.appendingPathComponent("file.pdf")
print("zzz url to save: \(url)")
print("zzz got data: \(pdfData.description)")
try? data?.write(to: url)
print("zzz wrote to file")
self.sema.signal()
}
}
}.resume()
sema.wait()
}
func loadPDF() {
let url = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
print("zzz url to load from: \(url)")
do {
let content = try FileManager.default.contentsOfDirectory(at: url, includingPropertiesForKeys: nil, options: .skipsHiddenFiles)[0]
print("zzz file: \(content)")
webView.loadFileURL(content, allowingReadAccessTo: content)
print("zzz webView loaded")
} catch {
print("zzz error with getting the contents...")
}
}
}
I tried it in my app with changing URLs and filenames etc. and it does the trick.
Finally!!!!