iOS10文件系统 - 不再是app容器中的文件?

wil*_*ick 9 iphone xcode ios ios10

出于调试目的,我经常使用这样的代码将数据写入iOS上的文件...

NSString *docsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSString *filePath = [docsPath stringByAppendingPathComponent:testName];
FILE* resultsFile = fopen([filePath UTF8String],"w");
Run Code Online (Sandbox Code Playgroud)

...然后通过Xcode下载容器获取数据(通过在"Window-> Devices"屏幕上选择应用程序,然后从下面的"little gear"弹出式菜单中选择"Download container ..."应用列表.)

我记得这适用于iOS 9和之前的版本,但是在iPhone 6上的iOS 10上尝试这个,我发现它不再适用了.调用fopen返回成功,/var/mobile/Containers/Data/Application/[uuid]/Documents/testname但下载时文件不在容器中.

该文件不应该在容器中吗?在其他地方吗?或者是否根本无法将数据转储到文件中并将其从手机中取出?

Iva*_*nov 0

我尝试重现您的问题(在 iOS 10.3.3、Xcode 10.1 下),并且在 App 项目的上下文中这一切都对我有效。您遇到的问题可能与您对文件对象所做的操作有关resultFile,如果您可以共享一些包含代码下一行的代码(或者检查您是否正在调用 fclose() 例如),那么解决它可能会更容易。

另请注意,似乎不支持从控制应用程序扩展的代码写入 Docs 目录,如下所示:从扩展读取和写入 iOS 应用程序文档文件夹

在应用程序项目/目标上下文中工作的代码:

  • 在 Swift 中使用数据如下:

    guard let documentsPath = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).last else { return }
    
    let someData = "Hello world using swift".data(using: .utf8)
    
    do{
       try someData?.write(to: documentsPath.appendingPathComponent("hello-world.txt"))
    }catch{
        //handle the write error
    }
    
    Run Code Online (Sandbox Code Playgroud)
  • 将 NSData 与 Objective C 结合使用:

    NSString * hello = @"Hello world using NSData";
    NSData * helloData = [hello dataUsingEncoding: NSUTF8StringEncoding];
    
    NSString *docsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSString *filePath = [docsPath stringByAppendingPathComponent:@"fileNameObjcNSData.txt"];
    [helloData writeToFile:filePath atomically:true];
    
    Run Code Online (Sandbox Code Playgroud)
  • 使用 fopen:

    NSString *docsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSString *filePath = [docsPath stringByAppendingPathComponent:@"fileNameObjcFopen.txt"]; //
    FILE * fileHandle = fopen([filePath UTF8String], "w");
    
    if (fileHandle != NULL){
        fputs("Hello using fopen()", fileHandle);
        fclose(fileHandle);
    }
    
    Run Code Online (Sandbox Code Playgroud)

希望能帮助到你