[swift] Swift로 파일 이동 시 파일 크기 검사를 추가하는 방법

파일을 이동할 때 파일 크기를 확인하여 특정 크기 이상의 파일만 이동하도록 하는 것은 보안 및 성능 측면에서 중요합니다. Swift에서는 다음과 같은 방법으로 파일 크기 검사를 추가할 수 있습니다.

1. 파일 크기 가져오기

먼저, 파일의 크기를 가져오는 방법을 알아봅시다. Swift에서는 FileManager 클래스를 사용하여 파일 크기를 가져올 수 있습니다.

import Foundation

func getFileSize(atPath path: String) -> Int? {
    do {
        let attributes = try FileManager.default.attributesOfItem(atPath: path)
        if let fileSize = attributes[.size] as? Int {
            return fileSize
        }
    } catch {
        print("Error: \(error)")
    }
    return nil
}

위 코드는 지정된 경로의 파일 크기를 반환하는 함수를 정의한 것입니다.

2. 파일 이동 시 크기 검사 추가

이제 파일을 이동할 때 파일 크기를 검사하여 특정 크기 이상의 파일만 이동할 수 있도록 하는 방법을 살펴봅시다.

func moveFile(fromPath sourcePath: String, toPath destinationPath: String, minSize: Int) {
    if let fileSize = getFileSize(atPath: sourcePath), fileSize >= minSize {
        do {
            try FileManager.default.moveItem(atPath: sourcePath, toPath: destinationPath)
            print("File moved successfully")
        } catch {
            print("Error: \(error)")
        }
    } else {
        print("File size is not within the specified range")
    }
}

위 코드는 파일을 이동할 때 지정된 최소 크기에 맞는지를 검사하는 함수를 정의한 것입니다. 파일 크기가 지정된 최소 크기보다 크다면 파일을 이동하고, 그렇지 않다면 오류 메시지를 출력합니다.

이제 위의 두 방법을 사용하여 파일 이동 시 파일 크기 검사를 추가할 수 있습니다.

참고 자료: Apple Developer Documentation - FileManager

위의 코드는 파일 크기를 확인하고, 이동하는 과정을 단순화한 것이며, 실제 프로젝트에 적용할 때에는 보다 신중하게 처리해야 합니다.