0

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

职位 数据 平均 目标
人 1 董事 37 45 80
人 2 助理 23 56 34
人 3 CEO 34 45 67

有五列,第一行是标题。下面是我在 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)

线程 1:致命错误:索引超出范围

我的目标是能够在需要时单独读取文件并访问每列/行的元素,但无法确定问题的根源。感谢任何帮助。

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

4

1 回答 1

2

您的问题是 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()
于 2020-09-21T23:08:09.453 回答