转换为Swift2.2后,我的Swift代码无效。 我的代码:
Swift 1.0代码:
Class func getPath(filename: String ) -> String {
return NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory,NSSearchPathDomainMask.UserDomainMask,true)[0].stringByAppendingComponent(filename)
}
错误:在NSURL上使用URLByAppendingPathComponent。
答案 0 :(得分:2)
使用与URL相关的API和现代方式获取文档目录:
在Swift 2中,类函数标有static
static func getPath(filename: String ) -> String {
// try! is safe
let documentDirectory = try! NSFileManager.defaultManager().URLForDirectory(.DocumentDirectory,
inDomain: .UserDomainMask,
appropriateForURL: nil,
create: true)
return documentDirectory.URLByAppendingPathComponent(filename).path!
}
或完全基于网址:
static func getURL(filename: String ) -> NSURL {
let documentDirectory = try! NSFileManager.defaultManager().URLForDirectory(.DocumentDirectory,
inDomain: .UserDomainMask,
appropriateForURL: nil,
create: true)
return documentDirectory.URLByAppendingPathComponent(filename)
}
答案 1 :(得分:0)
Class func getPath(filename: String ) -> String {
let basePath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0]
let baseURL = NSURL(fileURLWithPath: basePath)
let fullURL = baseURL.URLByAppendingPathComponent(filename)
return fullURL.path!
}