【问题标题】:How to get/print data after downloading them on device using URLSession downloadTask?使用 URLSession downloadTask 在设备上下载数据后如何获取/打印数据?
【发布时间】:2020-06-26 03:05:31
【问题描述】:

我从 Internet 下载了一个 JSON 文件并将其保存在文档目录中。然后我将临时文件位置移动到我的自定义文件位置。 现在我想从保存数据的自定义 URL/文件路径打印或访问。

这是下载文件的代码。

func downloadingContent() {

        let url = URL(string: "https://file-examples.com/wp-content/uploads/2017/02/file_example_JSON_1kb.json")

        URLSession.shared.downloadTask(with: url!) { (urlresponse, response, error) in

            guard let originalUrl = urlresponse else { return }

            do {
                let path = try FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false)

                self.newUrl = path.appendingPathComponent("jsonFile")

                try FileManager.default.moveItem(at: originalUrl, to: self.newUrl!)
                print(self.newUrl!)
            }
            catch {
                print(error.localizedDescription)
                return
            }
        }.resume()
    }

这是我下载文件后得到的自定义文件路径/URL。

file:///Users/fahimrahman/Library/Developer/CoreSimulator/Devices/4DA8E821-097A-4D66-BE95-CE51F3C52CD8/data/Containers/Data/Application/C7714D5E-6CBC-4E54-8619-C9C15EA739B3/Documents/jsonFile

【问题讨论】:

    标签: ios swift swift4 swift5 swift5.1


    【解决方案1】:

    两种选择:

    1. 使用String(contentsOf: self.newUrl) 加载数据。
    2. 而不是downloadTask使用dataTask那么可以将数据保存在Documents中直接使用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-28
      • 1970-01-01
      相关资源
      最近更新 更多