从Documents到NSData的文件

时间:2012-11-05 10:28:01

标签: iphone objective-c

我想将文档目录中的文件抓取到NSData对象中,但如果我这样做,我的NSData始终为NIL

filepath = [[NSString alloc] init];
filepath = [self.GetDocumentDirectory stringByAppendingPathComponent:fileNameUpload];
NSData *data = [[NSFileManager defaultManager] contentsAtPath:filepath];

-(NSString *)GetDocumentDirectory{
fileMgr = [NSFileManager defaultManager];
homeDir = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];

return homeDir;

}

此时,我总是得到一个例外,我的数据是NIL

[request addRequestHeader:@"Md5Hash" value:[data MD5]];

我检查过,没有文件,但我不知道为什么!我之前创建了该文件:

NSMutableString *xml = [[NSMutableString alloc] initWithString:[xmlWriter toString]];

NSArray *paths = NSSearchPathForDirectoriesInDomains
(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];

//make a file name to write the data to using the documents directory:
NSMutableString *fileName = [NSMutableString stringWithFormat:@"%@/7-speed-",
                      documentsDirectory];

[xml writeToFile:fileName
          atomically:NO
            encoding:NSStringEncodingConversionAllowLossy
               error:nil];

通过以下方式解决:

[xml writeToFile:fileName
          atomically:YES
            encoding:NSUTF8StringEncoding
               error:nil];

2 个答案:

答案 0 :(得分:20)

检查文件存在:

if([[NSFileManager defaultManager] fileExistsAtPath:filepath)
{
   NSData *data = [[NSFileManager defaultManager] contentsAtPath:filepath];
}
else
{
   NSLog(@"File not exits");
}

答案 1 :(得分:3)

Swift 3版本

let filePath = fileURL.path
if FileManager.default.fileExists(atPath: filePath) {
    if let fileData = FileManager.default.contents(atPath: filePath) {
        // process the file data
    } else {
        print("Could not parse the file")
    }
} else {
    print("File not exists")
}