카테고리 없음

[ Swift ] 파일 쓰고 읽기

박빅백 2020. 10. 19. 16:54
import UIKit
import Foundation
//FileManager 인스턴스 생성
let fileManager = FileManager()

let desktopPath:String = "/Users/bighand/Desktop"

do{
    let contents = try fileManager.contentsOfDirectory(atPath: desktopPath)
    
    let deeperContents = try fileManager.subpaths(atPath: desktopPath)
    
    print(contents)
    print(deeperContents)
    
} catch let error as NSError {
    print("Error access directory: \(error)")
}

이렇게 하면 

Error access directory: Error Domain=NSCocoaErrorDomain Code=257 "The file “Desktop” couldn’t be opened because you don’t have permission to view it." UserInfo={NSUserStringVariant=(Folder), NSFilePath=/Users/bighand/Desktop, NSUnderlyingError=0x6000012248d0 {Error Domain=NSPOSIXErrorDomain Code=1 "Operation not permitted"}}

 

The file “Desktop” couldn’t be opened because you don’t have permission to view it."

이러한 에러가 뜬다.

 

 

 

//DocumentsDirectory로 디렉토리의 경로 저장
let documentsDirectory = fileManager.urls(for: .documentDirectory, in: .userDomainMask).first
//해당 디렉토리 이름 지정
let dataPath = documentsDirectory?.appendingPathComponent("FileManager Directory")

do {
    //디렉토리 생성  (atPath: dataPath!.path)에서 dataPath를 언래핑 해줘야 한다.
    try fileManager.createDirectory(atPath: dataPath!.path, withIntermediateDirectories: false, attributes: nil)
} catch let error as NSError {
    print("Error creating directory: \(error.localizedDescription)")
}

//FileManagerTest.swift에 추가
do {
    //파일 이름을 기존의 경로에 추가
    let helloPath = dataPath?.appendingPathComponent("Hello.txt")
    //쓸 내용
    let text = "Hello File From Swift blabla"
    do {
        //쓰기 작업
        try text.write(to: helloPath!, atomically: false, encoding: .utf8)
    }
} catch let error as NSError {
    print("Error Writing File : \(error.localizedDescription)")
}

저장이 잘 된다.