Swift deleting file from folder in documents directory - swift

I appreciate some assistance. I created a folder inside my documents directory named "MyPhotos". I added three image files to the folder. No issues.
Next I'm attempting to construct some code that will delete the files when needed but can't get it right. I can append the MyPhotos folder to the search path but can't subsequently append the file name to the path after multiple tries. tempPhotoTitle is a variable. Thank you for helping.
let fileManager = FileManager.default
let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory,.userDomainMask,true)[0] as NSString
let destinationPath = documentsPath.appendingPathComponent("MyPhotos")
let finalPath = destinationPath.appending(tempPhotoTitle)
do {
try fileManager.removeItem(atPath: finalPath)
}
catch {
print(error)
}

The issue there is that you are working with strings (paths) and not adding the slash. I recommend always working with URLs this way you dont need to worry about adding the slash to your path.
do {
let tempPhotoTitle = "filename.jpg"
let documents = try FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
let photos = documents.appendingPathComponent("MyPhotos")
let fileURL = photos.appendingPathComponent(tempPhotoTitle)
try FileManager.default.removeItem(at: fileURL)
} catch {
print(error)
}

Leo Dabus's answer of working with URLs is the better one. However, it's worth mentioning that when working with Strings, if you bridge to NSString again, appendingPathComponent is available:
let finalPath = (destinationPath as NSString).appendingPathComponent(tempPhotoTitle)

Related

Permission error when saving to documentDirectory

I am trying to save favourites to document directory, the code works fine when I run it in simulator however when I build it to my device I am getting the following error.
You don’t have permission to save the file
“Documents.LikedDepartments” in the folder
“F36073C0-AC1E-46CA-BC1E-E03F9F316E1D”.
Also it might be worth noting that when I change use .cachesDirectory instead of .documentDirectory it works fine.
How can I grant write access for the documents directory ?
import Foundation
extension FileManager {
static var documentsDirectory: URL {
let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
print(paths)
return paths[0]
}
}
let savePath = FileManager.documentsDirectory.appendingPathExtension("LikedDepartments")
func save() {
let favourites = calculateFavourites()
do {
let data = try JSONEncoder().encode(favourites)
try data.write(to:savePath, options: [.atomic, .completeFileProtection])
} catch {
print("\(error)")
}
}
Cool file extension .LikedDepartments
Use appendingPathComponent instead.
https://developer.apple.com/documentation/foundation/nsstring/1417069-appendingpathcomponent

swift save file after download Alamofire

download and save file
let destination: DownloadRequest.DownloadFileDestination = { _, _ in
// var fileURL = self.createFolder(folderName: downloadFolderName)
var fileURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
let fileName = URL(string : currentFile.link )
fileURL = fileURL.appendingPathComponent((fileName?.lastPathComponent)!)
return (fileURL, [.removePreviousFile, .createIntermediateDirectories])
}
Alamofire.download(currentDownloadedFile.link , to: destination).response(completionHandler: { (DefaultDownloadResponse) in
print("res ",DefaultDownloadResponse.destinationURL!);
completion(true)
})
but when i wont to check file in this dirrectory i get nil
let filemanager:FileManager = FileManager()
let fileURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
let files = filemanager.enumerator(atPath: fileURL.absoluteString) // = nil
while let file = files?.nextObject() {
print(file)
}
if i save local path to file and after reload app wont to share it -> "share" app cant send file (mb cant found it)
can u pls help me. how it works ? why when i print all files he didnt find it? how to save file who after reboot app it will be saved in same link
You are using the wrong API
For file system URLs use always path, absoluteString returns the full string including the scheme (e. g. file:// or http://)
let files = filemanager.enumerator(atPath: fileURL.path)

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")
}

Replace folder in file system using Swift

How can I copy and paste the entire content of a folder using Swift on a OS X? If the destinationPath already contains the folder, than it should replace it.
I tried
let appSupportSourceURL = NSURL(string: appSupportSourcePath)
let appSupportDestinationURL = NSURL(string: appSupportDestinationPath+"/"+appSupportFileName)
if (fileManager.isReadableFileAtPath(appSupportSourcePath)){
do {
try fileManager.copyItemAtURL(appSupportSourceURL!, toURL: appSupportDestinationURL!)}
catch{
}
}
but I realised, that this only works for files. I am trying to replace a whole folder.
I know Apple encourages new code to use the URLs to specify file system path. However NSFileManager is an old class and it's still in transition between the old string-based path and the new URL-based paradigm. Try this:
let appSupportSourcePath = "..."
let appSupportDestinationPath = "..."
let fileManager = NSFileManager.defaultManager()
do {
// Delete if already exists
if fileManager.fileExistsAtPath(appSupportDestinationPath) {
try fileManager.removeItemAtPath(appSupportDestinationPath)
}
try fileManager.copyItemAtPath(appSupportSourcePath, toPath: appSupportDestinationPath)
} catch {
print(error)
}
Edit: method with NSURL
let appSupportSourceURL = NSURL(fileURLWithPath: "...", isDirectory: true)
let appSupportDestionURL = NSURL(fileURLWithPath: "...", isDirectory: true)
try! NSFileManager.defaultManager().copyItemAtURL(appSupportSourceURL, toURL: appSupportDestionURL)