获取文件“xxx"无法打开,因为您在导入时没有查看权限 [英] Getting The file 'xxx" couldn't be opened because you don't have permission to view it when importing

查看:35
本文介绍了获取文件“xxx"无法打开,因为您在导入时没有查看权限的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是使用 Swift 和 SwiftUI 的新手,我正在尝试编写 iOS 应用程序来读取文件夹、计算每个文件的哈希值,然后将它们复制到外部驱动器.

I am very new using Swift and SwiftUI and I'm trying to write and iOS app that reads a folder, calculcate hash for each file, and then copy them to an external drive.

现在我正在尝试导入一个文件并计算其哈希值.但是,我总是收到同样的错误,说我没有权限查看它.

For now I'm trying to import one file and calculate its hash. However, I always get the same error, saying I don't have permission to view it.

这是我的代码:

    //
//  ContentView.swift
//  FileExporter
//
//  Created by adrien le falher on 27/09/2020.
//

import SwiftUI
import CryptoKit

struct ContentView: View {
    
    @State private var document: MessageDocument = MessageDocument(message: "Hello, World!")
    @State private var isImporting: Bool = false
    @State private var isExporting: Bool = false
    @State private var isMoving: Bool = false
    
    
    var body: some View {
        VStack {
            GroupBox(label: Text("Message:")) {
                TextEditor(text: $document.message)
            }
            GroupBox {
                HStack {
                    Spacer()
                    
                    Button(action: { isImporting = true }, label: {
                        Text("Import")
                    })
                    
                    Spacer()
                    
                    Button(action: { isExporting = true }, label: {
                        Text("Export")
                    })
                    
                    Spacer()
                    
                    Button(action: { isMoving = true }, label: {
                        Text("Export")
                    })
                    
                    Spacer()
                }
            }
        }
        .padding()
        .fileExporter(
              isPresented: $isExporting,
              document: document,
              contentType: .plainText,
              defaultFilename: "Message"
          ) { result in
              if case .success = result {
                  // Handle success.
              } else {
                  // Handle failure.
              }
          }
        .fileImporter(
            isPresented: $isImporting,
            allowedContentTypes: [.image],
            allowsMultipleSelection: false
        ) { result in
            do {
                
                print("ok")
                guard let selectedFile: URL = try result.get().first else { return }
                guard var fileBytes : String = try hashFile(selectedFile) else { return }
                //guard let message = String(data: try Data(contentsOf: selectedFile), encoding: .utf8) else { return }
                let message = fileBytes
                print(message)
                
                document.message = message
                
            } catch let error{
                print(error.localizedDescription)
                document.message = error.localizedDescription
            }
        }
        
        
    }
}
extension Data {
    init(reading input: InputStream) throws {
        self.init()
        input.open()
        defer {
            input.close()
        }

        let bufferSize = 1024
        let buffer = UnsafeMutablePointer<UInt8>.allocate(capacity: bufferSize)
        defer {
            buffer.deallocate()
        }
        while input.hasBytesAvailable {
            let read = input.read(buffer, maxLength: bufferSize)
            if read < 0 {
                //Stream error occured
                throw input.streamError!
            } else if read == 0 {
                //EOF
                break
            }
            self.append(buffer, count: read)
        }
    }
}


func hashFile (_ fileURL : URL)  -> String {
    print(fileURL)
    var hashed = ""
    
    do {
        var fileBytes =  try Data (contentsOf: fileURL)
        //OU reading : InputStream(url: fileURL)!
            print("Filebytes is \(fileBytes)")
        print("Bytes" + String(fileBytes.base64EncodedString()))
            let hashed = SHA256.hash(data: fileBytes)
            return String(hashed.description)
       
        } catch let error {
            hashed = error.localizedDescription
        }
    
    
            
    return hashed
    
}


struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        /*@START_MENU_TOKEN@*/Text("Hello, World!")/*@END_MENU_TOKEN@*/
    }
}

.fileImporter() 似乎是新的,我无法找到有关它的信息.我不知道我是否应该(或如何)请求 iOS 访问文件的权限;文件选择器工作正常,所以我不确定我做错了什么.

It seems that .fileImporter() is new and I am having trouble finding info on it. I don't know if I should (or how) ask permissions to iOS to access files ; the file picker works so I'm not sure what I did wrong.

任何帮助将不胜感激.

谢谢.

推荐答案

在读取文件内容之前,您必须先在 URL 上调用方法 startAccessingSecurityScopedResource().注意:不要忘记在完成后调用stopAccessingSecurityScopedResource()

You have to call the method startAccessingSecurityScopedResource() on the URL first, before reading the content of the file. Note: don't forget to call stopAccessingSecurityScopedResource() after you're finished!

您可以在 Apple 文档中找到更多信息.

You can find more information in the Apple documentation.

这是对我有用的代码:

.fileImporter(
        isPresented: $isImporting,
        allowedContentTypes: [.plainText],
        allowsMultipleSelection: false
    ) { result in
        do {
            guard let selectedFile: URL = try result.get().first else { return }
            if selectedFile.startAccessingSecurityScopedResource() {
                guard let fileContent = String(data: try Data(contentsOf: selectedFile), encoding: .utf8) else { return }
                defer { selectedFile.stopAccessingSecurityScopedResource() }
            } else {
                // Handle denied access
            }
        } catch {
            // Handle failure.
            print("Unable to read file contents")
            print(error.localizedDescription)
        }
    }

这篇关于获取文件“xxx"无法打开,因为您在导入时没有查看权限的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆