[swift] Swift로 파일 이동 시 날짜 및 시간 정보 유지 방법

파일을 Swift로 이동할 때 파일의 생성 날짜 및 시간 정보를 유지하려면 FileManager를 사용하여 파일의 속성을 유지해야 합니다.

이동전 파일 정보 가져오기

먼저, 원래 파일의 생성 날짜 및 시간을 가져와야 합니다. 다음은 해당 정보를 가져오는 방법입니다.

import Foundation

let fileManager = FileManager.default
let originalURL = URL(fileURLWithPath: "original_file_path")

do {
    let originalAttributes = try fileManager.attributesOfItem(atPath: originalURL.path)
    let originalCreationDate = originalAttributes[.creationDate] as? Date
    let originalModificationDate = originalAttributes[.modificationDate] as? Date
    
    // 가져온 정보를 출력하거나 다른 변수에 저장할 수 있습니다.
    
} catch {
    print("Error: \(error)")
}

파일 이동하기

이제 파일을 이동할 때 위에서 가져온 생성 날짜와 수정 날짜를 유지합니다.

let newURL = URL(fileURLWithPath: "new_file_path")

do {
    try fileManager.moveItem(at: originalURL, to: newURL)
    
    // 원래 생성 날짜 및 수정 날짜를 이동한 파일에 적용
    try fileManager.setAttributes(originalAttributes, ofItemAtPath: newURL.path)

    print("File moved successfully!")
} catch {
    print("Error: \(error)")
}

위 코드에서 “original_file_path” 및 “new_file_path”를 실제 파일 경로로 바꿔야 합니다.

이제 파일을 이동할 때 생성 날짜 및 수정 날짜 정보가 유지될 것입니다.

결론

Swift의 FileManager를 사용하여 파일을 이동하면서 파일의 생성 날짜 및 수정 날짜 정보를 유지하는 방법에 대해 알아보았습니다. 파일의 속성을 유지하는 방법을 이용하여 파일을 안전하게 이동할 수 있습니다.