首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何在Swift中找到NSDocumentDirectory?

如何在Swift中找到NSDocumentDirectory?
EN

Stack Overflow用户
提问于 2014-06-05 16:23:09
回答 2查看 135.9K关注 0票数 163

我正在尝试使用代码获取Documents文件夹的路径:

代码语言:javascript
复制
var documentsPath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory:0,NSSearchPathDomainMask:0,true)

但是Xcode给出了错误:Cannot convert expression's type 'AnyObject[]!' to type 'NSSearchPathDirectory'

我正在尝试理解代码中的错误之处。

EN

回答 2

Stack Overflow用户

发布于 2014-12-26 21:11:57

最新的建议是对文件和目录使用NSURL,而不是基于NSString的路径:

因此,要以NSURL的形式获取应用程序的文档目录:

代码语言:javascript
复制
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。

票数 33
EN

Stack Overflow用户

发布于 2021-08-04 18:39:36

将此行复制并粘贴到App delegate中,如下所示打印路径

代码语言:javascript
复制
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中打开文件

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/24055146

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档