본문 바로가기

학습활동

iOS FileSystem 실습

 

 

코드 실습

// FileManager을 이용해 파일 저장하기
let fileManager = FileManager.default
// fileManager가 documentDirectory의 **url 경로**를 생성
let documentPath: URL = fileManager.urls(for: .documentDirectory, in: .userDomainMask)[0]
// documentDirectory의 새 하위 디렉토리 **url 경로**를 생성
let studyDirectory = documentPath.appendingPathComponent("studyDirectory")

// withIntermediateDirectories .true : 해당 디렉토리 경로가 있으면 만들지 않음
// studyDirectory **디렉토리 생성**
do {
    try fileManager.createDirectory(at: studyDirectory, withIntermediateDirectories: true)
} catch {
    print(error)
}

// 경로 안 새 파일 **url 경로** 생성
let studyTXT = studyDirectory.appendingPathComponent("study.txt")

// 파일 안에 데이터 쓰고, **txt 파일 생성**
	if let data: Data = "10:20분 스터디 중".data(using: .utf8) {
    do {
				// .atomic : 덮어쓰기 /.withOutOverriding : 파일이 존재하면 에러 던짐
        try data.write(to: studyTXT, options: .atomic)
    } catch {
        print(error)
    }
}
------------------------------------------------------------
// 생성한 파일 데이터 내용 확인해보기
do {
    let data = try Data(contentsOf: studyTXT)
    let string = String(data: data, encoding: .utf8) ?? "문서를 찾을 수 없음"
    
    print(string)
} catch {
    print("데이터를 읽을 수 없음.")
}

// studyTXT**.path()** : studyTXT의 **URL을 string**으로 리턴
// 해당 디렉토리&파일이 존재하는지 여부를 리턴
if fileManager.fileExists(atPath: studyTXT.path()) {
    print("존재함")
} else {
    print("존재하지 않음")
}

//파일인지 디렉토리인지 검사
if studyTXT.hasDirectoryPath {
    print("studyTXT는 디렉토리다.")
} else {
    print("studyTXT는 디렉토리가 아니다.")
}
------------------------------------------------------------
// 특정 디렉토리, 파일 **조건 없이! 삭제**
do {
    try fileManager.removeItem(at: studyTXT)
} catch {
    print("삭제를 할 수 없다.!")
}
------------------------------------------------------------
// root에서부터 해당 디렉토리까지의 경로를 각각의 배열 요소로 리턴함
// -> root부터 해당 디렉토리까지의 *모든 디렉토리 확인 가능*
// ["/", "Users", "minseong", "Library", "Developer", "CoreSimulator", "Devices", "C5DD0025-E957-4792-AE5A-C5FC9D3F69D0", "data", "Containers", "Data", "Application", "DCEAF9E7-4E2E-4A67-925C-BF96AEA59BA9", "Documents", "studyDirectory"]
print(studyDirectory.pathComponents)

// 해당 디렉토리 기준, **하위 디렉토리의 모든 디렉토리&파일 확인 가능**
// ["studyDirectory", "studyDirectory/study.txt"]
print(fileManager.subpaths(atPath: documentPath.path()) ?? [])

//**해당 디렉토리의 안**에 들어있는 내용의 **전체 경로**를 배열로 리턴
print(try? fileManager.contentsOfDirectory(at: documentPath, includingPropertiesForKeys: nil))
------------------------------------------------------------
// 특정 디렉토리, 파일 **조건 확인 후 삭제**
// 하위 디렉토리에 디렉토리&파일이 있는지 검사
if let subPaths = fileManager.subpaths(atPath: studyDirectory.path()), subPaths.isEmpty {
    do {
        try fileManager.removeItem(at: studyDirectory)
        print("디렉토리를 삭제하였습니다.")
    } catch {
        print("삭제를 할 수 없다.!")
    }
} else {
  
    if fileManager.fileExists(atPath: studyDirectory.path()) {
        print("디렉토리 내에 파일이 존재하므로 삭제할 수 없습니다.")
    } else {
        print("디렉토리가 존재하지 않습니다.")
    }
}

[Swift tip] File, Directory Manager

iOS ) FileManager를 이용해 파일/폴더 만드는 법

[Swift/iOS] FileManager로 파일 생성(쓰기), 읽기, 삭제하기

728x90

'학습활동' 카테고리의 다른 글

APFS-iOS File System  (0) 2024.01.08
KeyChain  (0) 2023.12.11
Swift Performance (2)  (0) 2023.12.11
Swift Performance (1)  (0) 2023.12.11
URL Loading System  (0) 2023.11.30