目标C中的文件转换问题

时间:2012-11-30 11:18:20

标签: objective-c ios xcode file-upload

我在文件上传时使用此代码

        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *documentsDirectory = [paths objectAtIndex:0];
        filePath1 = [documentsDirectory stringByAppendingPathComponent:@"myVoice.caf"];// specify your audioname
        NSLog(@"***************************");
        NSLog(@"%@",filePath1);


        NSDictionary *fileAttributes1 = [fileManager attributesOfItemAtPath:filePath1 error: NULL];
        NSNumber *fileSize1 = [fileAttributes1 objectForKey:NSFileSize];
        NSLog(@"%@",fileSize1);
         NSLog(@"***************************");


        NSString *file2 = [[NSBundle mainBundle] pathForResource:filePath1 ofType:@"caf"];
        NSData *file1Data = [[NSData alloc] initWithContentsOfFile:file2];

        NSLog(@"**************&&&&&&&&&&&&&&&*************");
        NSLog(@"%@",file1Data);
        NSLog(@"**************&&&&&&&&&&&&&&&**************");

===============================================

现在o / p是

2012-11-30 16:39:39.719 Varsity[4802:1a303] /Users/Esolz/Library/Application Support/iPhone Simulator/5.1/Applications/FAED7832-392C-4BFE-9A9B-D18B749FDC9B/Documents/myVoice.caf
2012-11-30 16:39:39.719 Varsity[4802:1a303] 542752
2012-11-30 16:39:39.719 Varsity[4802:1a303] ***************************
2012-11-30 16:39:39.719 Varsity[4802:1a303] **************&&&&&&&&&&&&&&&*************
2012-11-30 16:39:39.719 Varsity[4802:1a303] (null)
2012-11-30 16:39:39.719 Varsity[4802:1a303] **************&&&&&&&&&&&&&&&**************

==============================

实际上主要问题在于这两行

NSString *file2 = [[NSBundle mainBundle] pathForResource:filePath1 ofType:@"caf"];
NSData *file1Data = [[NSData alloc] initWithContentsOfFile:file2];

无法转换文件。哪里出错了

1 个答案:

答案 0 :(得分:1)

该文件位于文档目录中的应用程序沙箱内,不存在于NSBundle中。简单来说,它不会像您包含图像等那样添加到项目中。因此,当您尝试从项目包中获取文件数据并使用文档目录的路径时,您将获取数据为null。试试这个NSData *file1Data = [[NSData alloc] initWithContentsOfFile:filePath1];