问题
How can I fix the following errors when running the code below? I already searched in SO but can't find anything for Swift 3.
// Delete all files in given directory
let path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as String
let dataPath = NSURL(fileURLWithPath: path)
if let enumerator = FileManager.default.enumerator(atPath: dataPath.path!) {
while let fileName = enumerator.nextObject() as? String {
do {
try FileManager.default.removeItem(atPath: "\(dataPath)\(fileName)")
}
catch let e as NSError {
print(e)
}
catch {
print("error")
}
}
}
Log:
Error Domain=NSCocoaErrorDomain Code=4 "“.DS_Store” couldn’t be removed." UserInfo={NSFilePath=file:///Users/CIPL0469/Library/Developer/CoreSimulator/Devices/F0106B28-C4D1-4FE2-A425-D04C6BFDDC01/data/Containers/Data/Application/A5AB9B7B-6174-4BA7-9EFD-0E9F1C98CB17/Documents/.DS_Store, NSUserStringVariant=( Remove ), NSUnderlyingError=0x60800004fed0 {Error Domain=NSPOSIXErrorDomain Code=2 "No such file or directory"}}
Error Domain=NSCocoaErrorDomain Code=4 "“2017-01-31_10-44-21.m4a” couldn’t be removed." UserInfo={NSFilePath=file:///Users/CIPL0469/Library/Developer/CoreSimulator/Devices/F0106B28-C4D1-4FE2-A425-D04C6BFDDC01/data/Containers/Data/Application/A5AB9B7B-6174-4BA7-9EFD-0E9F1C98CB17/Documents/2017-01-31_10-44-21.m4a, NSUserStringVariant=( Remove ), NSUnderlyingError=0x60800004fa80 {Error Domain=NSPOSIXErrorDomain Code=2 "No such file or directory"}}
Error Domain=NSCocoaErrorDomain Code=4 "“2017-01-31_10-44-26.m4a” couldn’t be removed." UserInfo={NSFilePath=file:///Users/CIPL0469/Library/Developer/CoreSimulator/Devices/F0106B28-C4D1-4FE2-A425-D04C6BFDDC01/data/Containers/Data/Application/A5AB9B7B-6174-4BA7-9EFD-0E9F1C98CB17/Documents/2017-01-31_10-44-26.m4a, NSUserStringVariant=( Remove ), NSUnderlyingError=0x60000004f570 {Error Domain=NSPOSIXErrorDomain Code=2 "No such file or directory"}}
回答1:
nextObject()
of (NS)DirectoryEnumerator
returns always the full path / url of the enumerated items, an additional concatenation breaks the path. Aside form that concatenating URL
and String
with String Interpolation to pass it as path
parameter doesn't work at all.
I recommend to use the URL related API anyway
let fileManager = FileManager.default
do {
let url = try fileManager.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false)
if let enumerator = fileManager.enumerator(at: url, includingPropertiesForKeys: nil) {
while let fileURL = enumerator.nextObject() as? URL {
try fileManager.removeItem(at: fileURL)
}
}
} catch {
print(error)
}
回答2:
Just to make it clear:
let addr = one["resourceAddr"] as! String
do {
try FileManager.default.removeItem(at: URL(string:addr)!)
} catch let error as NSError {
print("error: ", error.localizedDescription)
}
来源:https://stackoverflow.com/questions/41974312/error-deleting-contents-in-directory-domain-nscocoaerrordomain-code-4-domain