본문 바로가기
SwiftUI

[SwiftUI] FileImporter 권한 요청

by eigen96 2023. 2. 9.
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

댓글