Rob*_*ert 16 xcode objective-c last-modified ios nsdocumentdirectory
我正在使用这段代码来尝试检索文件的最后修改日期:
NSError *error = nil;
NSDictionary *attributes = [[NSFileManager defaultManager] attributesOfItemAtPath: myFilePath error:&error];
if (attributes != nil) {
NSDate *date = (NSDate*)[attributes objectForKey: NSFileModificationDate];
NSLog(@"Date modiifed: %@", [date description]);
}
else {
NSLog(@"Not found");
}
Run Code Online (Sandbox Code Playgroud)
这适用于主包中的文件,但如果文件位于应用程序文档文件夹的子目录中,则不适用,myFilePath
如下所示:
/Users/User/Library/Application Support/iPhone Simulator/6.0/Applications/The App ID Number/Documents/mySubdirectory/My Saved File
Run Code Online (Sandbox Code Playgroud)
它不断返回"未找到".
我知道文件在那里,因为我可以用finder查看它.我也尝试删除文件名中的空格,但这没有任何效果.
错误日志说没有这样的文件或目录,所以当我尝试将文件复制到文档目录时,看起来肯定出错了.
奇怪的是,迭代文档子目录,contentsOfDirectoryAtPath
显示文件存在.
我已尝试对路径进行硬编码并以编程方式检索它,其中:
*myFolder = [documentsDirectory stringByAppendingPathComponent:@"myFolder"];
*myFilePath = [myFolder stringByAppendingPathComponent:theFileName];
Run Code Online (Sandbox Code Playgroud)
谁能看到我哪里出错了?
zvj*_*a24 20
试试这个.我有同样的问题,并解决了下一个问题:
NSURL *fileUrl = [NSURL fileURLWithPath:myFilePath];
NSDate *fileDate;
[fileUrl getResourceValue:&fileDate forKey:NSURLContentModificationDateKey error:&error];
if (!error)
{
//here you should be able to read valid date from fileDate variable
}
Run Code Online (Sandbox Code Playgroud)
希望它有所帮助;)
col*_*ire 13
Swift 3解决方案:
func fileModificationDate(url: URL) -> Date? {
do {
let attr = try FileManager.default.attributesOfItem(atPath: url.path)
return attr[FileAttributeKey.modificationDate] as? Date
} catch {
return nil
}
}
Run Code Online (Sandbox Code Playgroud)
这是一个类似Swift的@ zvjerka24解决方案:
func lastModified(path: String) -> NSDate? {
let fileUrl = NSURL(fileURLWithPath: path)
var modified: AnyObject?
do {
try fileUrl.getResourceValue(&modified, forKey: NSURLContentModificationDateKey)
return modified as? NSDate
} catch let error as NSError {
print("\(#function) Error: \(error)")
return nil
}
}
Run Code Online (Sandbox Code Playgroud)