9

ドキュメントディレクトリから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];
4

2 に答える 2

21

チェックファイルが存在します:

if([[NSFileManager defaultManager] fileExistsAtPath:filepath)
{
   NSData *data = [[NSFileManager defaultManager] contentsAtPath:filepath];
}
else
{
   NSLog(@"File not exits");
}
于 2012-11-05T10:36:52.757 に答える
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")
}
于 2016-11-02T07:20:53.650 に答える