How to save video data to document directory in swift? - swift

I want to save video data to document directory.
I know how to create document directory my folder.
But how to save data that document directory??
let fileManager = FileManager.default
if let tDocumentDirectory = fileManager.urls(for: .documentDirectory, in: .userDomainMask).first {
let filePath = tDocumentDirectory.appendingPathComponent("\(FOLDER_NAME)")
if !fileManager.fileExists(atPath: filePath.path) {
do {
try fileManager.createDirectory(atPath: filePath.path, withIntermediateDirectories: true, attributes: nil)
} catch {
print("Couldn't create document directory")
}
}
print("Document directory is \(filePath)")
}
Now, I have (FOLDER_NAME) folder. But How to save video data to (FOLDER_NAME) folder??
And How to I get saved video file path?
I apologize for my stupidity.

In your Info.plist, add the following permissions:
Supports opening documents in place: YES
Application supports iTunes file sharing: YES
let videoFilename = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] + "/" + getFileName() //return your filename from the getFileName function
videoNSData.write(toFile: videoFilename, atomically: true)
Then, inside Files, you can get a folder named with your app name, where you can access your saved video file (with the specified filename).

Related

Unable to save multiple text files in same folder (MacOS Swift Application)

I am trying to save multiple text files in the same folder. So far I can save one text file into a generated folder in my document directory, but I cannot save more than one text file in that same folder.
let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
let documentsDirectory = paths[0]
let docURL = URL(string: documentsDirectory)!
let dataPath = docURL.appendingPathComponent("User_Notes")
// this is the folder name
if !FileManager.default.fileExists(atPath: dataPath.path) {
do {
try
FileManager.default.createDirectory(atPath: dataPath.path, withIntermediateDirectories: true, attributes: nil)
// try stringToWrite.write(to: &dataPath)
try stringToWrite.write(toFile: "\(dataPath)/\(userNotes)).txt", atomically: true, encoding: String.Encoding.utf8)
} catch {
print(error.localizedDescription)
}
}
if error != nil {
print("Error saving user data.")
}
}

Annotating PDF file and saving in swift

In my iOS app using swift, I annotated the pdf field and saved in the document directory. The view correctly display annotated field and the file is saved with annotation in document directory, however in the debugging area I am getting messages. The last method for two run was Ok but then also giving error message although displayed file and saved file in doc directory was fine. Any idea?
2020-02-14 21:51:23.245079-0800 PDFSaving[4092:1084625] [Unknown process name] Failed to load /System/Library/PrivateFrameworks/CorePDF.framework/Versions/A/CorePDF
2020-02-14 21:51:23.262963-0800 PDFSaving[4092:1084625] Error: Attempting to save dictionary with key: <CGPDFNameRef (/Encoding)>. Dictionary keys must be of type string.
2020-02-14 21:51:23.263062-0800 PDFSaving[4092:1084625] Error: Attempting to save dictionary with key: <CGPDFNameRef (/Font)>. Dictionary keys must be of type string.
2020-02-14 21:51:23.263113-0800 PDFSaving[4092:1084625] Error: Could not create dictionary value for key: /DR. Invalid value.
2020-02-14 21:51:23.263161-0800 PDFSaving[4092:1084625] Error: Cannot save value for annotation key: /DR. Invalid type.
I have used various techniques to save the pdf file but all are giving same message in the debugging area`
// 1st method of deleting and saving file
// File saving with errors in debugging area
let path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
let fileNameWithPath = "\(path)/editedFile.pdf"
if FileManager.default.fileExists(atPath: getFilePath()){
do{
try FileManager.default.removeItem(atPath: getFilePath())
print("File path for deleted file: \(path)")
print("File is deleted successfully, path & filename of deleted file: \(fileNameWithPath)")
}catch{
print("error while deleting item from docDir :: \(error.localizedDescription)")
}
}
if let data = pdfDocument.dataRepresentation(){
let url = URL(fileURLWithPath: fileNameWithPath)
do{
try data.write(to: url)
print("pdf saved successfully \(fileNameWithPath)")
}catch{
print("error while saving file \(error.localizedDescription)")
}
}
// 2nd method of deleting and saving file
// File saving with errors in debugging area
let path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
let fileNameWithPath = "\(path)/editedFile.pdf"
if FileManager.default.fileExists(atPath: getFilePath()){
do{
try FileManager.default.removeItem(atPath: getFilePath())
print("File path for deleted file: \(path)")
print("File is deleted successfully, path & filename of deleted file: \(fileNameWithPath)")
}catch{
print("error while deleting item from docDir :: \(error.localizedDescription)")
}
}
guard let url = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first,
let data = pdfView.document?.dataRepresentation() else {return}
let fileURL = url.appendingPathComponent(filename)
do {
try data.write(to: fileURL)
print("File path of saved file : \(path)")
print("pdf saved successfully, path and filename of saved file: \(fileNameWithPath)")
} catch {
print("error while saving file \(error.localizedDescription)")
}
// 3rd method of deleting and saving file
// Blank file is saving without any error in debugging area
let bundlePath = Bundle.main.path(forResource: "QW484A_2017R8", ofType: ".pdf")
let destPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first!
let fileManager = FileManager.default
let fullDestPath = URL(fileURLWithPath: destPath).appendingPathComponent("editedFile.pdf")
if fileManager.fileExists(atPath: fullDestPath.path){
do {
try fileManager.removeItem(at: fullDestPath)
print("File path for removed file: \(destPath)")
print("File path & filename of file removed: \(fullDestPath)")
}
catch{
print("error while removing modified file: \(error.localizedDescription)")
}
}
do{
try fileManager.copyItem(atPath: bundlePath!, toPath: fullDestPath.path)
print("File path of saved file : \(destPath)")
print("database saved successfully, path and filename of saved file: \(fullDestPath.path)")
}catch{
print("error while saving modified file: \(error.localizedDescription)")
}
// 4th method of deleting and saving
// File saving with errors in debugging area
let destPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first!
let fileManager = FileManager.default
let fullDestPath = URL(fileURLWithPath: destPath).appendingPathComponent("editedFile.pdf")
if fileManager.fileExists(atPath: fullDestPath.path){
do {
try fileManager.removeItem(at: fullDestPath)
print("File path for removed file: \(destPath)")
print("File path & filename of file removed: \(fullDestPath)")
}
catch{
print("error while removing modified file: \(error.localizedDescription)")
}
}
self.pdfDocument.write(to: fullDestPath)
print("The save filed path and name: \(fullDestPath)")
// 5th method of saving
// File saving with errors in debugging area
guard let url2 = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first,
let data = pdfView.document?.dataRepresentation() else {return}
let fileURL = url2.appendingPathComponent("editedfile.pdf")
do {
try data.write(to: fileURL)
print("print path: \(fileURL)")
} catch {
print(error.localizedDescription)
}
// 6th method
let destPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first!
let fileManager = FileManager.default
let fullDestPath = URL(fileURLWithPath: destPath).appendingPathComponent("editedFile.pdf")
if fileManager.fileExists(atPath: fullDestPath.path){
do {
try fileManager.removeItem(at: fullDestPath)
print("File path for removed file: \(destPath)")
print("File path & filename of file removed: \(fullDestPath)")
}
catch{
print("error while removing modified file: \(error.localizedDescription)")
}
}
self.pdfView.document?.write(to: fullDestPath)
print("The save filed path and name: \(fullDestPath)")
`
So finally I work around this issue. I thought to update as it may be hurting others. There two methods used for PDF form generation, ist form was created in word and than transferred to PDF with annotations, in 2nd method PDF form was generated using Acro Form, both were giving above problem. In 3rd attempt I created the the PDF form using Adobe Acrobat DC from scratch and tried, this time no problem in saving the PDF with annotations, seems this is the issue with format transformation

How can I find the path of iOS app internal directory in Swift?

How can I find the path of iOS app internal directory in Swift?
Firstly, what is the equivalent name of android app internal directory in iOS app?
Secondly, how can I find the path of the directory?
which api should I use in Swift?
My main purpose is trying to copy Bundle sqlite file to the directory
To get path of document directory you can use this code.
// path to documents directory
let documentDirectoryPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first
if let documentDirectoryPath = documentDirectoryPath {
}
For more information follow these links : File System Basics and Accessing Files and Directories
Try this -
public func getDatabasePath() -> String {
let databaseURL = try? FileManager.default
.url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
.appendingPathComponent("YOUR_DB_FILE_NAME.sqlite")
// If DB file not present in file manager copy DB file to user document directory
let fileManager = FileManager.default
if fileManager.fileExists(atPath: (databaseURL?.path)!) {
print("FILE AVAILABLE")
return (databaseURL?.path)!
} else {
print("FILE NOT AVAILABLE ... Copying")
if fileManager.createFile(atPath: (databaseURL?.path)!, contents: Data(), attributes: nil) {
return (databaseURL?.path)!
}
}
return ""
}

Issue with loading file from disk

Ok so this one has had me scratching my head for a while.
I have a png file that I write out to disk. I get the data by:
let data = UIImagePNGRepresentation(scaledImage!)
let filename = getDocumentsDirectory().appendingPathComponent("\(record.uid!).png")
I do a try catch and everything seems to work. The resulting filename is:
file:///var/mobile/Containers/Data/Application/C6B796E8-2DB6-45A4-9B18-EF808B8CA3CA/Documents/580420d51800cd826a7e217c.png
The problem comes when I try to load that image back from the disk.
When I get a list of all files in the documents directory I get:
[file:///private/var/mobile/Containers/Data/Application/C6B796E8-2DB6-45A4-9B18-EF808B8CA3CA/Documents/580420d51800cd826a7e217c.png]
The only difference I can see is the 'private' part of the filepath. When I try to check to see if the file exists using the filepath I get back from appending the filename (the one without the private part) I get false.
What am I missing?
Swift 3/4 code
Let us assume the method getDocumentsDirectory() is defined as follows
func getDocumentsDirectory() -> URL {
let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
let documentsDirectory = paths[0]
return documentsDirectory
}
In order to save the image
let data = UIImagePNGRepresentation(scaledImage!)
let filename = getDocumentsDirectory().appendingPathComponent("\(record.uid!).png")
try? data?.write(to: filename)
And your image is saved in Documents Directory
Now in order to load it back
let imagePath = getDocumentsDirectory().appendingPathComponent("\(record.uid!).png").path
let fileManager = FileManager.default
if fileManager.fileExists(atPath: imagePath){
print("Image Present")
//load it in some imageView
}else {
print("No Image")
}

Get file path from NSBundle in Swift

I have a file stored in:
/var/mobile/Containers/Data/Application/083EA15E7/Documents/myFile.zip
It got there after I downloaded it from a server.
If I know the file name is myFile.zip, how can I find it with NSBundle?
Like this:
if let URL = NSBundle.mainBundle().URLForResource("myFile", withExtension: "zip") {
// do stuff
}
currently this returns false, not sure how I can specify the whole path. Any ideas?
This item is not in your bundle, an item in your bundle is something that you add before compiling, such as assets, fonts etc.
iOS provides each app with a sandbox. In that sandbox, the Documents folder exists. To access files from the Documents folder try this:
let documentsURL = NSURL(
fileURLWithPath: NSSearchPathForDirectoriesInDomains(
.DocumentDirectory, .UserDomainMask, true).first!,
isDirectory: true
)
To get the file, you will need to get its path and append it to the documents path like so.
let URLToMyFile = documentsURL.URLByAppendingPathComponent("MyFile.zip")
To get the path as a string you can access the path property of the URL.
print(URLToMyPath.path!)
That will print out the path of your downloaded resource.
Tested on: xCode 8.3.2 & Swift 3.1
First drag your file (JPG, MP3, ZIP) inside your project folder and make sure Copy items if needed is checked and project/app is selected in Add to targets
Inside relevant ViewController
let fileName = "fileName"
let fileType = "fileType"
if let filePath = Bundle.main.path(forResource: fileName, ofType: fileType) {
print(filePath)
}
If you need to get the file URL you can use NSBundle method
if let fileURL = Bundle.main.url(forResource: fileName, withExtension: fileType) {
print(fileURL)
}
Also NSBundle method pathForResource has an initializer that you can specify in which directory your files are located like:
if let filePath = Bundle.main.path(forResource: fileName, ofType: fileType, inDirectory: "filesSubDirectory") {
print(filePath)
}
And for getting file URL:
if let fileURL = Bundle.main.url(forResource: fileName, withExtension: fileType, subdirectory: "filesSubDirectory") {
print(fileURL)
}
run time created file are stored in Document directory not in NSBundle. NSBundle stores the files like System file you put in your Xcode project while your developing
Here is the example
This code is fully tested on Swift 2.0
let file = "myFile.zip"
if let dir : NSString = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.AllDomainsMask, true).first {
//path will be stored here
let sPath = dir.stringByAppendingPathComponent(file);
print(sPath) // printing the file path
}