美文网首页Swifty CodingiOS Developer
Swift 获取文件(目录)属性(大小、创建/修改日期等)

Swift 获取文件(目录)属性(大小、创建/修改日期等)

作者: WonderChang | 来源:发表于2016-09-22 15:52 被阅读134次

    获取文件属性主要用到FileManager的实例方法attributesOfItem(atPath:)

    let filePath = "xxx"
    
    do {
        let fileAttributes = try FileManager.default.attributesOfItem(atPath: filePath)
        if let fileSize:NSNumber = fileAttributes[FileAttributeKey.size] as! NSNumber? {
            print("File Size: \(fileSize.uint32Value)")
        }
        
        if let ownerName = fileAttributes[FileAttributeKey.ownerAccountName] {
            print("File Owner: \(ownerName)")
        }
     
        if let creationDate = fileAttributes[FileAttributeKey.creationDate] {
            print("File Creation Date: \(creationDate)")
        }
        
        if let modificationDate = fileAttributes[FileAttributeKey.modificationDate] {
            print("File Modification Date: \(modificationDate)")
        }
        
    } catch let error as NSError {
        print("Get attributes errer: \(error)")
    }
    
    

    发现以上时间为GMT时间,需要转换为本地时间。附上将转换时区的方法,将以上方法替换为:

    //将GMT时间转换为本地时间
    
    //获取本地时区及与GMT的时间间隔
    let timeZone = NSTimeZone.system
    let interval: TimeInterval = TimeInterval(timeZone.secondsFromGMT())
    
    if let creationDate = fileAttributes[FileAttributeKey.creationDate] {
        let localCreateDate = (creationDate as! NSDate).addingTimeInterval(interval)
        print("File Creation Date: \(localCreateDate)")
    }
    
    if let modificationDate = fileAttributes[FileAttributeKey.modificationDate] {
        let localModDate = (modificationDate as! NSDate).addingTimeInterval(interval)
        print("File Modification Date: \(localModDate)")
    }
    

    相关文章

      网友评论

        本文标题:Swift 获取文件(目录)属性(大小、创建/修改日期等)

        本文链接:https://www.haomeiwen.com/subject/hubjettx.html