用户从UIDocumentPickerViewController中挑选文档,我将在稍后使用。文档选择器委托调用并给我文件的url,但根本没有文件。
这就是我如何创建documentPicker。我使用supportedFiles,因为手动输入扩展名对我不起作用
let supportedFiles: [UTType] = [UTType.data]
let documentPicker = UIDocumentPickerViewController(forOpeningContentTypes: supportedFiles)
documentPicker.delegate = self
documentPicker.modalPresentationStyle = .fullScreen
present(documentPicker, animated: true, completion: nil)
有一个带有所有检查的documentPicker委托
func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {
var path = urls.first!.path
let stream = InputStream(url: URL(fileURLWithPath: path))
print(path)
print(FileManager.default.fileExists(atPath: path))
do {
let items = try FileManager.default.contentsOfDirectory(atPath: path)
print(items.count)
for item in items {
print("Found (item)")
}
} catch {
print(error)
}
do {
let csv = try CSVReader(stream: stream!)
print("Everything is ok")
while let row = csv.next() {
print(row)
}
} catch {
print(error)
}
}
console show me this
/private/var/mobile/Containers/Shared/AppGroup/3232A257-B8F6-4F39-A12B-A7192EBF9524/File Provider Storage/Games.csv
false
Error Domain=NSCocoaErrorDomain Code=256 "The file “Games.csv” couldn’t be opened." UserInfo={NSUserStringVariant=(
Folder
), NSFilePath=/private/var/mobile/Containers/Shared/AppGroup/3232A257-B8F6-4F39-A12B-A7192EBF9524/File Provider Storage/Games.csv, NSUnderlyingError=0x282a277e0 {Error Domain=NSPOSIXErrorDomain Code=20 "Not a directory"}}
cannotOpenFile
据我所知,我得到了不存在的文件的url ?那么为什么fileManager给我一个错误,这个文件不是一个目录,而不是说在这个url没有什么?还有一个错误,我没有权限读取这个文件,所以我把它改为可读的。也就是说它能看到,但又看不见?我就是不明白。
还尝试通过删除/private来更改路径,但不成功
更新:
当试图获得项目列表在文件夹中的游戏。svc被定位,我得到另一个错误
Error Domain=NSCocoaErrorDomain Code=257 "The file “File Provider Storage” couldn’t be opened because you don’t have permission to view it." UserInfo={NSUserStringVariant=(
Folder
), NSFilePath=/private/var/mobile/Containers/Shared/AppGroup/3232A257-B8F6-4F39-A12B-A7192EBF9524/File Provider Storage/, NSUnderlyingError=0x2819254d0 {Error Domain=NSPOSIXErrorDomain Code=1 "Operation not permitted"}}
找到关于访问目录的apple文档。编辑我的代码到这个,现在它正在工作
guard urls.first!.startAccessingSecurityScopedResource() else {
print("Error getting access")
return
}
defer { urls.first!.stopAccessingSecurityScopedResource() }
let path = urls.first!.path
let stream = InputStream(url: URL(fileURLWithPath: path))
do {
let csv = try CSVReader(stream: stream!)
print("Everything is ok")
while let row = csv.next() {
print(row)
}
URL(fileURLWithPath: path).stopAccessingSecurityScopedResource()
} catch {
print(error)
}
基本上在处理URL之前,你通过这个函数获得使用安全URL的请求
guard urls.first!.startAccessingSecurityScopedResource() else {
print("Error getting access")
return
}
defer { urls.first!.stopAccessingSecurityScopedResource() }
和结束与安全连接的工作,写入以下行
URL(fileURLWithPath: path).stopAccessingSecurityScopedResource()
然而,在文档中编写的代码不为我工作,错误检查(我删除)仍然给我一个错误
更新如果代码不工作,您可以删除这一行
defer { urls.first!.stopAccessingSecurityScopedResource() }