I have saved and opened a PDF file on my view controller, and then I save the array of PDFs to the system data. I then pull my array from the data and use the string of the location in the new view controller. However when I attempt to load the file at said directory it fails to appear in the WebView, even though I was able to load it from the same directory on the first ViewController.
How can I get it to open after the app has been closed?
Here is how I save and open the PDF the first time:
func generatePreview() {
let A4paperSize = CGSize(width: 595, height: 842)
let pdf = SimplePDF(pageSize: A4paperSize, pageMargin: 20.0)
createFirstPage(x: pdf)
pdf.beginNewPage()
addAreas(x: pdf)
//add disclamer and like dress the pdf up
let pdfData = pdf.generatePDFdata()
let resourceDocPath = (FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)).last! as URL
let pdfNameFromUrl = "Survey-\(finalOverview.name).pdf"
let actualPath = resourceDocPath.appendingPathComponent(pdfNameFromUrl)
do {
try pdfData.write(to: actualPath, options: .atomic)
print("pdf successfully saved!")
} catch {
print("Pdf could not be saved")
}
let request = URLRequest(url: actualPath)
pdfPreview.load(request)
let pdfObj = pdfArray(fileTitle: finalOverview.name, fileName: actualPath)
//pdfView.GlobalVariable.myPDFs.append(pdfObj)
savePDF(x: pdfObj)
}
I made the mentioned changes but still no luck
My issue was when I was creating the string the second time, the optional was not wrapped. So when I unwrapped it the code worked as intended.
Related
I have a WKWebView app which i will like to clear a specific cache when image is uploaded .
When i upload an image, the name remains same but the old image will be override with new one, like old image is logo.png, new image will be renamed with logo.png also. But because of cache users will still be seeing the old image.
I have below line of code to clear cache once image has been uploaded and it working fine, but my only problem now is that all cached data is being cleared also.
Is there any way i can clear cache for just the image was uploaded, maybe by passing the image name?
Or just clear cache for images?
static func clearCache(){
let cacheURL = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first!
let fileManager = FileManager.default
do {
// Get the directory contents urls (including subfolders urls)
let directoryContents = try FileManager.default.contentsOfDirectory( at: cacheURL, includingPropertiesForKeys: nil, options: [])
for file in directoryContents {
print("CACHE = ", file)
do {
try fileManager.removeItem(at: file)
}
catch let error as NSError {
debugPrint("Ooops! Something went wrong: \(error)")
}
}
} catch let error as NSError {
print(error.localizedDescription)
}
}
From the loop i got this
CACHE =
file:///private/var/mobile/Containers/Data/Application/BFEB788B-9EA4-4921-A902-230869CAC814/Library/Caches/com.myapp.ios.sellers/
CACHE =
file:///private/var/mobile/Containers/Data/Application/BFEB788B-9EA4-4921-A902-230869CAC814/Library/Caches/google-sdks-events/
CACHE =
file:///private/var/mobile/Containers/Data/Application/BFEB788B-9EA4-4921-A902-230869CAC814/Library/Caches/com.apple.WebKit.WebContent/
CACHE =
file:///private/var/mobile/Containers/Data/Application/BFEB788B-9EA4-4921-A902-230869CAC814/Library/Caches/WebKit/
It seems like you need to find the file you want to remove when you are in the for loop loop for files. Remove that specific image when the for loop hits. Right now that for loop removes all cache in directoryContents.
In my iOS Swift App, I have created files in my App's documents directory through this code:
let localFileName = String("\(fileName).rtf")
let text = String("text text text")
if let dir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first {
let fileURL = dir.appendingPathComponent(localFileName)
do {
try text.write(to: fileURL, atomically: false, encoding: .utf8)
}
catch {
}
}
Now I want to Add a link in my app to this directory where file is created so that user can see files. Currently I am doing this by this code:
let importMenu = UIDocumentPickerViewController(documentTypes: [String(kUTTypeRTF)], in: .open)
importMenu.delegate = self
importMenu.modalPresentationStyle = .formSheet
present(importMenu, animated: true, completion: nil)
but this code is for picking documents, not for opening directory, So How I can open my App's Documents directory, not for picking documents, just only for showing documents?
It is not possible to explore/open a directory in iOS app. Apple doesn't provide any api for the same. You need to create it by your own.
What you can do
You need to fetch all the files from the specific directory and list them all in either tableview or collection view.
And when user click on the any file, you can show that in web view or based on the file type you can do any specific operations.
So ultimately you need to explore more about FileManager.
This class contains what you want.
hope you are doing good in development. I have a question regarding Zipping currently i am using Zip framework which I am using for zip the all captured image in device but the problem here is I do not want to save the Zip file in document directory instead I wanna save this memory itself. I am struggling since last week please let me know how can we achieve the zipping without saving it in local directory filepath
Also when I captured the image successfully I saved it to local directory using
let documentsDirectory = FileManager.default.urls(for:
.documentDirectory, in: .userDomainMask).first!
let fileName = "image.jpg"
let fileURL = documentsDirectory.appendingPathComponent(fileName)
if let data = UIImageJPEGRepresentation(image, 1.0),
!FileManager.default.fileExists(atPath: fileURL.path) {
do {
// writes the image data to disk
try data.write(to: fileURL)
print("file saved")
} catch {
print("error saving file:", error)
}
}
After when I am trying to send the image before our server I want to make it all one file so I have implemented the Zip (framework)
Here filpathArray meant all captured image in local path
do {
var urls = [URL]()
for i in 0..<(self.filePathArray.count)
{
urls.append(self.filePathArray[i] as! URL)
}
if self.filePathArray.count > 0 {
let zipFiles = try Zip.quickZipFiles(urls, fileName: "AllFiles")
}
}
Here zipping is done successfully but it saved in local path so when using app container I can able to see the images, I do not want to see the images in device like apple sandbox or Xcode container itself
I want to make zipping on the flow like without saving it document directory, Thanks in advance.
As I understand from Apple documentation, that there is sandbox for each app , so there local storage to the app can save data and files inside it and the other apps can not access its data and files, but I tried to create file by app and retrieved file URL from it and create another app and pass the file URL to it, but the new app open this file successfully, why that happen? the other app must can not be able to open the file according to Apple documentation
In first App:
I download file using Alamofire
let destination: DownloadRequest.DownloadFileDestination =
{
(temporaryURL, response)in
let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory,.userDomainMask, true)[0]
let documentsURL = URL(fileURLWithPath: documentsPath, isDirectory: true)
let tmpURL = documentsURL.appendingPathComponent("wordFile.docx")
return (tmpURL, [.removePreviousFile, .createIntermediateDirectories])
}
Alamofire.download(urlString, to:
destination).responseData { response in
(response.destinationURL?.path)!
//The "response.destinationURL?.path" is: "/Users/user/Library/Developer/CoreSimulator/Devices/A0427AC0-6D5E-4734-A550-73A8224BD54D/data/Containers/Data/Application/4126243E-E166-4311-A950-D8FF49A07991/Documents/wordFile.docx"
})
In second App:
I got the file path from previous App (response.destinationURL?.path)!
and pass it to webView , but the webView show file the successfully
How would one programmatically save an image generated from a playground to the resources folder?
I have generated some photos through filters in my playground that I would like to save somehow. The resources folder seems like a good fit. What if I wanted to save the image to the desktop?
I've seen this done with saving images for apps, but I just want to save it to my desktop (or a specified folder in a specified location.)
Create folder first in 'Documents' with name 'Shared Playground Data' otherwise app will give error.
SWIFT 5:
let image = // your UIImage
let filepath = playgroundSharedDataDirectory.appendingPathComponent("export.jpg")
let imagedata = image.jpegData(compressionQuality: 1.0)
try! imagedata?.write(to: URL.init(fileURLWithPath: filepath.path))
print("write to \(filepath)")
In Xcode 11, the folder is not in ~/Documents anymore for iOS playgrounds but buried deep in ~/Library/Developer/. You have to print the path and create the Shared Playground Data folder manually to save a file from a playground:
import PlaygroundSupport
// ...
let url = playgroundSharedDataDirectory.appendingPathComponent("example.png")
print(url)
try! image.pngData()!.write(to: url)
Here's how to save it to the shared data directory:
Create a path to the image:
let path = XCPlaygroundSharedDataDirectoryURL.appendingPathComponent("export.jpg")!
(you may need to create the directory ~/Documents/Shared Playground Data/)
Then to save your output (in this case a CIImage from a filter)
let temp:CGImage = context.createCGImage(output, from: output.extent)!
let image = UIImage(cgImage: temp)
let data = UIImageJPEGRepresentation(image, 1.0)
try! data?.write(to: path)
While the first answer helped point me in the right direction, the lack of ability to validate the required playgroundSharedDataDirectory path exists, the requirement to create that directory in order for the path to work, as well as force unwrapping (using !) the try can lead to frustration as well as drag out the process.
Here is a safer, more convenient solution that checks the name you provide for extra safety:
func writeImage(_ image: UIImage, name: String) {
if name.isEmpty || name.count < 3 {
print("Name cannot be empty or less than 3 characters.")
return
}
guard let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else {
print("No documents directory found.")
return
}
let imagePath = documentsDirectory.appendingPathComponent("\(name).png")
let imagedata = image.jpegData(compressionQuality: 1.0)
do {
try imagedata?.write(to: imagePath)
print("Image successfully written to path:\n\n \(documentsDirectory) \n\n")
} catch {
print("Error writing image: \(error)")
}
}
Call using:
writeImage(image, name: "MyNewImage")
A break down of what is happening:
The method writeImage checks to see if the documents directory exists.
If the documents directory does not exist (unlikely), stop process.
If the documents directory exists, carry on and write the image to the path.