[swift] Swift으로 디렉토리 생성 후 파일 목록 가져오기

Swift을 사용하여 디렉토리를 생성하고 그 안에 있는 파일 목록을 가져오는 방법에 대해 알아보겠습니다.

디렉토리 생성

Swift에서 디렉토리를 생성하기 위해서는 FileManager를 사용합니다. 아래는 디렉토리를 생성하는 간단한 예제 코드입니다.

import Foundation

let fileManager = FileManager.default
let directoryURL = fileManager.urls(for: .documentDirectory, in: .userDomainMask)[0].appendingPathComponent("MyDirectory")

do {
    try fileManager.createDirectory(at: directoryURL, withIntermediateDirectories: true, attributes: nil)
} catch {
    print("Error creating directory: \(error)")
}

위 코드에서는 FileManager를 사용하여 documentDirectory에 “MyDirectory”라는 이름의 디렉토리를 생성하고 있습니다.

파일 목록 가져오기

이제 생성한 디렉토리 안에 있는 파일 목록을 가져오는 방법을 알아봅시다. 아래는 해당 작업을 수행하는 예제 코드입니다.

do {
    let fileURLs = try fileManager.contentsOfDirectory(at: directoryURL, includingPropertiesForKeys: nil)
    for fileURL in fileURLs {
        print(fileURL.lastPathComponent)
    }
} catch {
    print("Error getting the contents of the directory: \(error)")
}

위 코드는 contentsOfDirectory(at:includingPropertiesForKeys:) 메서드를 사용하여 디렉토리 내의 파일 목록을 가져옵니다. 가져온 파일 목록은 fileURLs에 저장되며, 각 파일의 경로는 fileURL.lastPathComponent를 통해 얻을 수 있습니다.

이제 위의 코드를 사용하여 Swift에서 디렉토리를 생성하고 그 안에 있는 파일 목록을 가져오는 방법에 대해 알게 되었습니다.

참고 문서: Apple Developer Documentation - FileManager, Apple Developer Documentation - URL