![](/img/trans.png)
[英]How to store NSData from NSURLConnection sendSynchronousRequest as a pdf file to documents directory in iOS?
[英]File from Documents into NSData
我想从文档目录中获取一个文件到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];
检查文件存在:
if([[NSFileManager defaultManager] fileExistsAtPath:filepath)
{
NSData *data = [[NSFileManager defaultManager] contentsAtPath:filepath];
}
else
{
NSLog(@"File not exits");
}
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")
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.