在transmitData方法中,NSArray文件即将出现。我的代码中的问题在哪里?我保存了一个文件(我们点击[文件writeToURL:fileURL atomically:YES])然后我们调用transmitData,但无法检索文件。
#import "FileManagerService.h"
#import "SynthesizeSingleton.h"
@implementation FileManagerService
SYNTHESIZE_SINGLETON_FOR_CLASS(FileManagerService);
#define SAVEVOTER @"SV"
#define SAVESCRIPT @"SS"
- (NSURL *)applicationDocumentsDirectory
{
return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}
-(void)saveFile:(NSData*)file:(NSString*)dataType
{
NSFileManager *manager = [NSFileManager defaultManager];
NSURL *fileURL;
NSString *fileName;
if (dataType == DATA_SAVE_VOTER)
{
fileName = [NSString stringWithFormat:@"%@01",SAVEVOTER];
fileURL = [[self applicationDocumentsDirectory]URLByAppendingPathComponent:fileName];
int fID = 0;
while ([manager fileExistsAtPath:[fileURL absoluteString]])
{
fID++;
fileName = [NSString stringWithFormat:@"%@%d",SAVEVOTER,fID];
fileURL = [[self applicationDocumentsDirectory]URLByAppendingPathComponent:fileName];
}
}
else if (dataType == DATA_SAVE_SCRIPT)
{
fileName = [NSString stringWithFormat:@"%@01",SAVESCRIPT];
fileURL = [[self applicationDocumentsDirectory]URLByAppendingPathComponent:fileName];
int fID = 0;
while ([manager fileExistsAtPath:[fileURL absoluteString]])
{
fID++;
fileName = [NSString stringWithFormat:@"%@%d",SAVESCRIPT,fID];
fileURL = [[self applicationDocumentsDirectory]URLByAppendingPathComponent:fileName];
}
}
[file writeToURL:fileURL atomically:YES];
}
-(void)transmitData
{
NSArray *files = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:[[self applicationDocumentsDirectory]absoluteString] error:NULL];
if (files == nil || [files count] <= 0)
{
NSLog(@"No files to transmit");
return;
}
for (id file in files)
{
NSData * dt = file;
NSString *str = [[NSString alloc]initWithData:dt encoding:NSUTF8StringEncoding];
NSLog(@"DataContents: %@",str);
}
}
@end
编辑: 经过更多测试:
fileName = @"testfile";
fileURL = [[self applicationDocumentsDirectory]URLByAppendingPathComponent:fileName];
NSLog(@"URL1: %@",[fileURL absoluteString]);
我的日志即将出现。所以我无法检索文件,因为我显然是使用空文件位置保存....为什么会发生这种情况?
FIXED:
所以我不知道为什么,但[文件writeToURL:fileURL atomically:YES]不起作用,[[NSFileManager defaultManager] createFileAtPath:fileURL 内容:文件 属性:无]; 确实有效。
答案 0 :(得分:0)
使用
- (NSURL *)applicationDocumentsDirectory
{
NSArray *searchPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentPath = [searchPaths objectAtIndex:0];
return [NSURL fileURLWithPath:documentPath];
}
和
NSArray *files = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:[[self applicationDocumentsDirectory]path] error:NULL];