出于调试目的,我经常使用这样的代码将数据写入iOS上的文件...
NSString *docsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSString *filePath = [docsPath stringByAppendingPathComponent:testName];
FILE* resultsFile = fopen([filePath UTF8String],"w");
...然后通过Xcode下载容器获取数据(通过在“Window-> Devices”屏幕上选择应用程序,然后从下面的“little gear”弹出式菜单中选择“Download container ...”应用列表。)
我记得这适用于iOS 9和之前的版本,但是在iPhone 6上的iOS 10上尝试这个,我发现它不再适用了。对fopen
的调用正在为/var/mobile/Containers/Data/Application/[uuid]/Documents/testname
返回成功,但是当我下载它时,该文件不在容器中。
该文件不应该在容器中吗?在其他地方吗?或者是否根本无法将数据转储到文件中并将其从手机中取出?
我试图重现你的问题(在iOS 10.3.3,Xcode 10.1下),它在App项目的上下文中完成了我的工作。您遇到的问题可能与您对文件对象resultFile
的处理有关,如果您可以共享包含代码的下一行的代码(或者检查您是否正在调用fclose()),则可能更容易解决它。
另请注意,似乎不支持从控制应用程序扩展的代码写入Docs目录,如下所示:reading and writing to an iOS application document folder from extension
在App项目/目标的上下文中工作的代码:
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
}
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];
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);
}
希望能帮助到你