728x90


아래와 같은 코드로 파일을 import하여 csv파일의 데이터를 단어장으로 가져오려고 하였다.

하지만 아래와 같은 에러가 발생하게 된다.
The file “TestCSVFiles.csv” couldn’t be opened because you don’t have permission to view it.

권한이 없다는 문제였으며 아래 함수를 사용하여 권한 접근 문제를 해결할 수 있다.
let fileURL = URL(fileURLWithPath: "/path/to/file")
if fileURL.startAccessingSecurityScopedResource() {
// Access the file
// ...
fileURL.stopAccessingSecurityScopedResource()
} else {
// Access was not granted
}
startAccessingSecurityScopedResource() 는 NSURL 클래스의 함수이며,
Security-Scoped 리소스의 접근 권한을 요청할때 사용되는 함수입니다.
startAccessingSecurityScopedResource() 을(를) 호출 한 후에는 리소스 액세스를 완료한 후 리소스 보안이 다시 활성화되도록
stopAccessingSecurityScopedResource() 호출해야 한다고 합니다.
결과:
.fileImporter(isPresented: $openFile, allowedContentTypes: [.commaSeparatedText]) { result in
do {
fileURL = try result.get()
//that's used to request access to a security-scoped resource.
if fileURL!.startAccessingSecurityScopedResource() {
guard String(data: try Data(contentsOf: fileURL!), encoding: .utf8) != nil else { return }
fileName = fileURL?.lastPathComponent ?? ""
if let fileURL {
csvData = DataFrame.loadCSV(fileURL: fileURL)
}
do { fileURL!.stopAccessingSecurityScopedResource() }
} else {
// Handle denied access
print("denied access")
}
} catch {
print("error reading docs", error.localizedDescription)
}
728x90
'SwiftUI' 카테고리의 다른 글
[SwiftUI] View scene window이란? UIKit에서도 본 거 같은데? (0) | 2022.12.18 |
---|---|
[SwiftUI] SwiftUI의 특징을 살펴보면서(2) - 데이터 주도적(Data driven) (0) | 2022.10.21 |
[SwiftUI] SwiftUI의 특징을 살펴보면서(1) - 선언적 구문 (0) | 2022.10.19 |
[SwiftUI] SwiftUI를 처음 만나서... 개요 (2) | 2022.10.18 |
댓글