我正在尝试使用以下代码段创建自定义目录,我实际上是从同一应用程序的工作Obj-C代码翻译而来。
class func pathToConfigFolder() -> String {
let urls: [String] = NSSearchPathForDirectoriesInDomains(.LibraryDirectory, .UserDomainMask, true)
let libraryPath: String = urls.last!
let configFolder: String = NSURL(fileURLWithPath: libraryPath).URLByAppendingPathComponent(".conf").absoluteString
var directory: ObjCBool = ObjCBool(true)
if !NSFileManager.defaultManager().fileExistsAtPath(configFolder, isDirectory: &directory) {
do {
try NSFileManager.defaultManager().createDirectoryAtPath(configFolder, withIntermediateDirectories: false, attributes: nil)
} catch let error {
print(" Error thrown... \(error)")
}
}
return configFolder
}
但代码失败并出现以下错误。
Error thrown... Error Domain=NSCocoaErrorDomain Code=4 "The operation couldn’t be completed. (Cocoa error 4.)" UserInfo=0x17526f4c0 {NSFilePath=file:///var/mobile/Containers/Data/Application/44D90AEB-DD7A-4C8C-9AD0-2665147BAAEC/Library/conf, NSUnderlyingError=0x174054c40 "The operation couldn’t be completed. No such file or directory"}
我在设备和运行iOS 9的模拟器上都试过了。
修改 Objective-C代码
+ (NSString*) pathToConfigFolder
{
NSArray *urls = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory,
NSUserDomainMask, YES);
NSString *libraryPath = [urls lastObject];
NSString *configFolder = [libraryPath stringByAppendingPathComponent:@".conf"];
NSError *error = nil;
if ( ! [[NSFileManager defaultManager] fileExistsAtPath:configFolder]) {
[[NSFileManager defaultManager] createDirectoryAtPath:configFolder
withIntermediateDirectories:NO
attributes:nil
error:&error];
}
return configFolder;
}
答案 0 :(得分:1)
你的问题在这里:
let libraryPath: String = urls.last!
let configFolder: String = NSURL(fileURLWithPath: libraryPath).URLByAppendingPathComponent(".conf").absoluteString
absoluteString
方法将整个网址作为字符串返回,因此configFolder
为file:///var/mobile/Containers/Data/Application/44D90AEB-DD7A-4C8C-9AD0-2665147BAAEC/Library/conf
。也就是说,它包含 file://
,因此不适合与您使用它的NSFileManager
方法一起使用的有效文件路径。
将这些行更改为这样可以解决问题:
let libraryPath: NSString = urls.last!
let configFolder = libraryPath.stringByAppendingPathComponent(".conf")
我在这里使用NSString
因为那里定义了stringByAppendingPathComponent
。