jaco-g
8/11/2017 - 5:27 AM

add files to subfolders

func addFiles() {
        let openPanel = NSOpenPanel()
        openPanel.canChooseFiles = true
        openPanel.allowedFileTypes = ["jpg","nef","nrw","psd","png"]
        openPanel.allowsMultipleSelection = true
        openPanel.allowsOtherFileTypes = false
        if openPanel.runModal() == NSModalResponseOK {
            files = openPanel.urls
            for i in 0..<files.count {
                var pathItem = [String]()
                do {
                    let fileAttributes = try FileManager.default.attributesOfItem(atPath: (files[i] as AnyObject).path)
                    let modificationDate = fileAttributes[FileAttributeKey.modificationDate] as! Date
                    
                    let dateFormatter = DateFormatter()
                    dateFormatter.timeStyle = DateFormatter.Style.none
                    dateFormatter.dateStyle = DateFormatter.Style.short
                    dateFormatter.dateFormat = "YYYY-MM-dd"
                    dateString = dateFormatter.string(from: modificationDate)
                    pathItem.append(dateString)
                }
                catch let error {
                    print(error.localizedDescription)
                }
                
                let imageSource = CGImageSourceCreateWithURL(files[i] as CFURL, nil)
                let imageProperties = CGImageSourceCopyPropertiesAtIndex(imageSource!, 0, nil) as Dictionary?
                let tiffDictionary = imageProperties?[kCGImagePropertyTIFFDictionary]
                if let cameraModelName = tiffDictionary?[kCGImagePropertyTIFFModel] as? String {
                    pathItem.append(cameraModelName)
                }
                
                let extention = NSURL(fileURLWithPath: (files[i] as AnyObject).path).pathExtension
                pathItem.append((extention?.uppercased())!)
                let newPath = pathItem.joined(separator:"/")
                
                let fileName = (files[i].path as NSString).lastPathComponent
                
                let fileManager = FileManager.default
                let home = fileManager.homeDirectoryForCurrentUser
                let sortedURL = home.appendingPathComponent("Desktop/\(newPath)")
                let sortedPath = sortedURL.path
                let filePath = files[i].path
    
                do {
                    try fileManager.createDirectory(atPath: sortedPath, withIntermediateDirectories: true, attributes: nil)
                } catch let error as NSError {
                    print(error.localizedDescription);
                }
                
                do {
                    try fileManager.copyItem(atPath: filePath, toPath: "\(sortedPath)/\(fileName)")
                }
                catch let error as NSError {
                    print(error.localizedDescription)
                }
            }
        }
    }