在我的应用程序中,我使用以下代码将 .db 文件写入文档目录,然后想使用它
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"%@",str);
NSMutableDictionary *retval = [json objectWithString:str];
if ([[retval objectForKey:@"Success"] boolValue])
{
NSString *downloadedData=[[retval objectForKey:@"Value"] objectForKey:@"SqLiteFileArray"];
NSData *mydata=[NSData dataWithBase64EncodedString :downloadedData];
NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentDir=[paths objectAtIndex:0];
NSString *documentFile=[documentDir stringByAppendingPathComponent:@"4_program.db"];
NSString * yourAppendingText=[[NSString alloc]initWithData:mydata encoding:NSUTF8StringEncoding];
[yourAppendingText writeToFile:documentFile atomically:YES encoding:NSUTF8StringEncoding error:nil];
NSLog(@"finish");
//[self getfile];
//NSLog(@"data %@",downloadedData);
}
else
{
NSLog(@"aaa");
}
self.view.userInteractionEnabled = TRUE;
}];
在 nslog 中我看到了 finish 语句所以我认为文件写入成功
但是当我重新进入应用程序并检查文档目录中是否存在文件时,它说它不存在
这是我的文件存在代码:
NSString *docsDir;
NSString *realpath;
NSArray *dirPaths;
dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
docsDir = dirPaths[0];
realpath=[[NSString alloc] initWithString:
[docsDir stringByAppendingPathComponent: @"4_program.db"]];
NSFileManager *filemgr = [NSFileManager defaultManager];
if ([filemgr fileExistsAtPath: realpath ] == NO)
{
NSLog(@"no file");
}
else
{
NSLog(@"file found");
[self getdata];
}
我错过了什么吗?我怎样才能知道文件写入成功完成?
最佳答案
我把我的writeToFile改成了
[[NSFileManager defaultManager] createFileAtPath:documentFile
contents:mydata
attributes:nil];
现在一切正常
关于ios - 如何检查文件是否在 objective-c 中成功保存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23979904/