我正在尝试使用代码获取Documents文件夹的路径:
var documentsPath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory:0,NSSearchPathDomainMask:0,true)
但是Xcode给出了错误:Cannot convert expression's type 'AnyObject[]!' to type 'NSSearchPathDirectory'
我正在尝试理解代码中的错误之处。
发布于 2014-12-26 21:11:57
最新的建议是对文件和目录使用NSURL,而不是基于NSString的路径:
因此,要以NSURL的形式获取应用程序的文档目录:
func databaseURL() -> NSURL? {
let fileManager = NSFileManager.defaultManager()
let urls = fileManager.URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
if let documentDirectory: NSURL = urls.first as? NSURL {
// This is where the database should be in the documents directory
let finalDatabaseURL = documentDirectory.URLByAppendingPathComponent("items.db")
if finalDatabaseURL.checkResourceIsReachableAndReturnError(nil) {
// The file already exists, so just return the URL
return finalDatabaseURL
} else {
// Copy the initial file from the application bundle to the documents directory
if let bundleURL = NSBundle.mainBundle().URLForResource("items", withExtension: "db") {
let success = fileManager.copyItemAtURL(bundleURL, toURL: finalDatabaseURL, error: nil)
if success {
return finalDatabaseURL
} else {
println("Couldn't copy file to final location!")
}
} else {
println("Couldn't find initial database in the bundle!")
}
}
} else {
println("Couldn't get documents directory!")
}
return nil
}
这有基本的错误处理,因为这在某种程度上取决于您的应用程序在这种情况下将做什么。但它使用文件URL和更现代的api来返回数据库URL,如果初始版本不存在,则将其复制到捆绑包之外,如果出现错误,则返回nil。
发布于 2021-08-04 18:39:36
将此行复制并粘贴到App delegate中,如下所示打印路径
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
print(NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).last! as String)
return true
}
复制路径并将其粘贴到finder中的go To Folder中,方法是右键单击它,然后输入
在Xcode中打开文件
https://stackoverflow.com/questions/24055146
复制相似问题