正在从 Dropbox 加载/读取 txt 文件到 swift

Loading / Reading a txt file from dropbox into swift

我正在尝试加载具有以下格式的 .txt 文件

人物 位置 数据 平均 目标
人一董事 37 45 80
人二助理 23 56 34
第三个人 CEO 34 45 67

有五列,第一行是 header。下面是我在 viewDidLoad:

中使用的代码
override func viewDidLoad() {
    super.viewDidLoad()
    // load txt file from dropbox
    let url = URL(string: "https://www.dropbox.com/s/pr0ldvdeab48mpp/prueba.txt?dl=0")
    let task = URLSession.shared.downloadTask(with: url!) {(urlresponse, response, error) in
        guard let originalURL = urlresponse else { return }
        do {
            // get path to directory
            let path = try FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false)
            // giving name to file
            let newUrl = path.appendingPathComponent("myTextFile")
            // move file from old to new url
            try FileManager.default.moveItem(at: originalURL, to: newUrl)
        } catch { 
            print(error.localizedDescription)
            return
        }
    }
    task.resume()
    //reading the file
    let path = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first
    do {
        let fileUrls = try FileManager.default.contentsOfDirectory(at: path!, includingPropertiesForKeys: nil)
        //read the text
        let textContent = try String(contentsOf: fileUrls[0], encoding: .utf8)
        print(textContent)
    } catch {
        print("ERROR")
    }
}

但是,我在行中收到以下错误

let textContent = try String(contentsOf: fileUrls[0], encoding: .utf8)

Thread 1: Fatal error: Index out of range

我的目标是能够在需要时单独读取文件和访问每个 column/row 的元素,但无法识别问题的根源。感谢任何帮助。

注意:如果有帮助,我可以灵活地将文件加载为 .csv 或其他更容易的格式。

您的问题是 dl=0 没有指向该文件。它将指向一个 html 文件。您需要使用 dl=1 才能直接下载文件。您还应该将加载代码移到下载任务的完成闭包中。您还可以从 url 响应中获取文件名。像这样尝试:

// load txt file from dropbox (make sure you change the string suffix from dl=0 to dl=1)
let url = URL(string: "https://www.dropbox.com/s/pr0ldvdeab48mpp/prueba.txt?dl=1")!
let task = URLSession.shared.downloadTask(with: url) { location, response, error in
    guard let location = location else { return }
    do {
        // get the documentDirectory url
        let documentDirectory = try FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false)
        print(documentDirectory.path)
        // get the suggested name fro the url response or the url last path component
        let name = (response as? HTTPURLResponse)?.suggestedFilename ?? location.lastPathComponent
        // create a destination url
        let destination = documentDirectory.appendingPathComponent(name)
        // check if the file already exists
        if FileManager.default.fileExists(atPath: destination.path) {
            // remove the file (if you would like to use the new one)
            try FileManager.default.removeItem(at: destination)
        }
        // move file from the temporary location to the destination
        try FileManager.default.moveItem(at: location, to: destination)
        // reading the downloaded file
        let textContent = try String(contentsOf: destination, encoding: .utf8)
        print(textContent)
    } catch {
        print("ERROR")
    }
}
task.resume()