如何检查文件是否在objective-c中成功保存

时间:2014-06-01 12:33:06

标签: ios objective-c download

在我的应用程序中,我使用以下代码将.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];

}
我错过了什么吗?我怎样才能学会成功写完文件?

1 个答案:

答案 0 :(得分:1)

我改为我的writeToFile

[[NSFileManager defaultManager] createFileAtPath:documentFile
                                contents:mydata
                                attributes:nil];

现在它可以工作,一切正常