【问题标题】:Path to mobile documents folder?移动文档文件夹的路径?
【发布时间】:2012-11-29 21:44:36
【问题描述】:

要访问我的应用程序文档文件夹,我使用以下代码:

[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];

我想访问这个文件夹,但是:

~/Library/Mobile Documents

如何轻松访问它作为路径值?我可以用类似的方式吗?

【问题讨论】:

    标签: iphone objective-c ios core-data icloud


    【解决方案1】:

    使用常量访问系统提供的目录的好处是,如果 Apple 决定更改结构,您的应用程序仍然可以工作。像~/Library/Mobile Documents 这样的硬编码很脆弱。

    但是,您可以使用相同的 NSSearchPathForDirectoriesInDomainNSLibraryDirectory 常量访问库目录。然后,您应该只附加Mobile Documents 目录路径。

    // Set the NO to YES to get the full path, not the ~ version.
    NSString *path = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, NO) lastObject]; 
    path = [path stringByAppendingPathComponent:@"Mobile Documents"];
    

    查看http://developer.apple.com/library/ios/#documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_Constants/Reference/reference.html#//apple_ref/doc/c_ref/NSSearchPathDirectory 中的常量值,Mobile Documents 目录似乎没有特定常量,因此硬编码方法可能是您唯一的选择。

    【讨论】:

      【解决方案2】:

      移动文档是 iCloud 文档。因此,您想将文档存储在 iCloud 中。

      在 OS X 上,它们肯定在 ~/Library/Mobile Documents(10.7 和 10.8)中,但在 iOS 上,您不应该查看。

       "All documents of an application are stored either in the local sandbox or in an iCloud container directory."...
      
        "A user should not be able to select individual documents for storage in iCloud. "
      

      http://developer.apple.com/library/ios/#documentation/DataManagement/Conceptual/DocumentBasedAppPGiOS/ManageDocumentLifeCycle/ManageDocumentLifeCycle.html

      因此,如果您的用户选择 iCloud,那么您应该使用 iCloud。

      iCloud 文档模型能持续多久,谁都猜不透,但这就是它今天的工作方式。整个事情似乎是糟糕的 UI 设计的杰作,正如对您问题的直接回答所示:

       -(NSURL*)ubiquitousContainerURL {
      
           return [[NSFileManager defaultManager] URLForUbiquityContainerIdentifier:nil];
      
       } 
      

      【讨论】:

      • 这一行的问题是,如果用户没有启用 iCloud,它就不起作用,为了简单起见,我想使用移动文档进行存储。
      【解决方案3】:

      在我最近的 macOS 应用程序中,我有同样的需求:如何访问 iCloud 目录的根文件夹。

      重要! 这是为非沙盒版本编写的,因为该应用程序仅适用于我自己。如果您计划在 Mac App Store 上发布应用,请不要关闭沙盒版本。

      1. 我在应用的权利文件中关闭了沙盒。
      2. 此代码将访问您的 iCloud 根文件夹:

        let pathToiCloudFolder = NSString(string: "com~apple~CloudDocs").expandingTildeInPath
        
        let backUpFolderUrl = FileManager.default.urls(for: .libraryDirectory, in:.userDomainMask).first!
        let backupUrl = backUpFolderUrl.appendingPathComponent("Mobile Documents/" + pathToiCloudFolder)
        
        print("Backup Folder:", backupUrl)
        

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-01-27
        • 2018-07-15
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多