簡體   English   中英

從Documents到NSData的文件

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM