I have a function that successfully moves a file into the shared App group, but my function to delete that file does not seem to be working. If I print out the fullpath2 variable it appears to be the correct location but the file is not removed and an error is not returned.
Here is my function:
func getSharedFilePath(appGroup:String,sharedFilename:String)->URL? {
if let directoryPath = FileManager().containerURL(forSecurityApplicationGroupIdentifier: appGroup) {
return directoryPath.appendingPathComponent(sharedFilename)
} else {
return nil
}
}
public func deleteFromSharedFile(sharedFilename: String, fileExtension: String)->String {
let sharedFilename = "\(sharedFilename).\(fileExtension)"
guard let url = getSharedFilePath(appGroup:applicationGroup,sharedFilename:sharedFilename) else {
return("Error getting shared file path")
}
// read file from file system to data variable
let fileManager = FileManager.default
do {
try fileManager.removeItem(atPath: (url.path))
return("File Removed")
}
catch let error as NSError {
return("File Remove Failed - \(error)")
}
}
Here is some code snippet of my emoji app.
It works well.
func removeImage(itemName: String, fileExtension: String) {
let fileName:String = itemName + "." + fileExtension
let fileManager = FileManager.default
guard let groupURL = fileManager.containerURL(forSecurityApplicationGroupIdentifier: "group.io.XXXXXX.XXXX") else {
return
}
let storagePathUrl = groupURL.appendingPathComponent("image/" + fileName, isDirectory: false)
let storagePath = storagePathUrl.path
do {
if fileManager.fileExists(atPath: storagePath) {
try fileManager.removeItem(atPath: storagePath)
}
} catch let error as NSError {
print(error.debugDescription)
}
}
"image" is just the name of sub folder of app group.
If you are saving files directly in the root folder, you can remove it.
Hope it helps you.