[iOS] URL이 넷 주소뿐만이 아니라 파일 주소를 나타내는데에도 쓰인다?!

RudinP·2일 전
0

Study

목록 보기
260/267

URL 속성에 대하여

  • (흔히 아는) 네트워크 주소 나타내기
  • 파일 주소를 나타내기

파일 위치를 나타낼 때 URL의 생성자

//문자열로 나타낼 때. 파일, 네트워크 주소 모두 사용 가능하지만, 주로 네트워크 주소 생성시 사용
URL(string: String) 

//파일주소를 나타낼 때 사용
URL(fileURLWithPath: String) //구버전

URL(filePath: String, 
	directoryHint: URL.DirectoryHint = .inferFromPath, 
    relativeTo base: URL? = nil) //신버전
    
//path: 문자열 형태의 파일 경로, 상대 경로 혹은 절대 경로
//directoryHint: 생성자에게 줄 수 있는 정보값으로 주소가 디렉토리인지 알려주기 위한 값. 기본값은 .notDirectory
//base: 상대 경로를 기준으로 삼을 기본 URL을 지정하는 역할

사용자의 홈 디렉토리를 리턴하기

  • NSHomeDirectory() 생성자를 이용한다.
// currentDirecotyrUrl이 nil일 경우 홈 디렉터리로 설정하기
var currentDirectoryUrl: URL?

override func viewDidLoad() {
	super.viewDidLoad()
    
    if currentDirectoryUrl == nil {
    	setCurrentDirectoryUrlHomeDirectory()
    }
}

func setCurrentDirectoryUrlHomeDirectory() {
	currentDirectoryUrl = URL(fileURLWithPath: NSHomeDirectory())
}

사용자의 홈 디렉토리 이름

  • 16진수의 유효 아이디를 사용한다.

url에서 속성을 가져오기

  • keys : 리턴해줬으면 하는 url의 속성

url에 파일이나 디렉토리가 존재하는지 확인하기

  • url이 정상적이고 접근 가능하다면 true를 리턴

현재 url이 directory일때, 부속 directory 추가하기

  • 이전 버전에서는 appendingPathComponent를 사용
  • 현재 디렉토리에서 새로운 디렉토리를 만들고, 그 새로운 url을 리턴해준다.

이후 createDirectory 메소드로 해당하는 url의 디렉토리를 생성하면 된다.

  • withIntermediateDirectories를 true로 하면 경로에 포함된 디렉토리중에서 아직 존재하지 않는 디렉토리가 있다면 자동으로 만들어줌
    • ex) /A 인 상태에서 url이 /A/B/C일 때, true일시 B를 자동 생성. false일시 자동생성되지 않고 에러 발생
func addDirectory(named: String) {
	guard let url = currentDirectoryUrl?.appending(named, .isDirectory) else {
    	return
    }
    
    do {
    	try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true, attributes: nil)
    } catch {
    	print(error)
    }
    
    refreshContents() //사용자정의함수. 여기서는 디렉토리 생성 후 tableView를 리로드 하는 방식
}

현재 url에 파일 추가하기

1. directory 추가와 동일하게 appending함수 사용

2. (선택) extension 추가

func addTExtFile() {
	guard let targetUrl = 
    	currentDirectoryUrl?.appending("텍스트파일")
        .appendingPathExtension("txt") else {
        	return
    }
        
   	do {
    //atomically가 true일시 임시파일을 만들고, 정상완료시 최종경로로 자동 이동
    //error발생 시 파일 깨짐 방지
    	try content.write(to: targetUrl, atomically: true, encoding: .utf8)
    } catch {
    	print(error)
    }
    
    refreshContents()
}
profile
iOS 개발자가 되기 위한 스터디룸...

0개의 댓글