Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ios/105.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios 从路径获取文件内容_Ios_Swift_Nsdata_Uidocument - Fatal编程技术网

Ios 从路径获取文件内容

Ios 从路径获取文件内容,ios,swift,nsdata,uidocument,Ios,Swift,Nsdata,Uidocument,我正在为几行令人尴尬的代码而挣扎。我读了很多答案,但似乎没有一个有效。在我的函数中,我从拾取的文档中获取文件路径: func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentAt url: URL) { let urlString = url.path let fileName = url.lastPathComponent let ref =

我正在为几行令人尴尬的代码而挣扎。我读了很多答案,但似乎没有一个有效。在我的函数中,我从拾取的文档中获取文件路径:

func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentAt url: URL) {

        let urlString = url.path
        let fileName = url.lastPathComponent
        let ref = DataService.instance.imagesStorageRef.child("\(fileName)")
         var contents = try? Data(contentsOf: url)
         print("contents: \(contents)")



        let uploadTask = ref.putData(contents! as Data, metadata: nil, completion: { (metadata, error) in ...}
}
file:///private/var/mobile/Library/Mobile%20Documents/com~apple~CloudDocs/nutella.jpg 目录:无


然后我尝试获取该文件路径的内容,以便将其传递给上载函数,该函数将其上载到firebase。然而,无论我如何尝试获得这些内容,我总是得到零值。请引导我进入正确的方向

还有一种可能对你有帮助的方法。为此,您需要将该文档转换为数据形式,然后将其发送到服务器

我在这里粘贴示例代码

 func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentAt url: URL) {
        let fileURL = url as URL
        print("The Url is : \(fileURL)")
        let fileNameWithoutExtension = fileURL.pathExtension
        print("fileNameWithoutExtension: \(fileNameWithoutExtension)")
        do {
            let data = try Data(contentsOf: fileURL)
            print("data=\(data)")
            //TODO: call upload API
            self.sendAttachments()
        }
        catch {/* error handling here */}
    }

使用
do/catch
查看尝试获取URL内容时出现的错误。文档选择器使用了什么模式?是“导入”还是“打开”?我将尝试执行/捕获。我使用“打开”模式。使用“导入”,而不是“打开”。阅读文档了解两者之间的区别。“导入”和do/catch工作得非常完美。非常感谢你。我还遇到了错误:[DocumentManager]视图服务确实因错误而终止:错误域=\u UIViewServiceErrorDomain Code=1“(null)”用户信息={Terminated=disconnect method}您知道为什么吗?我试图解决这个问题,但没有成功。