0

I'm trying to download a regular .txt file from my dropbox account which i have linked with a token, but i dont know how to get the content. The only thing ive been able to find is this:

            // Download a file
            client.filesDownload(path: "/hello.txt").response { response, error in
                if let (metadata, data) = response {
                    println("Dowloaded file name: \(metadata.name)")
                    println("Downloaded file data: \(data)")
                } else {
                    println(error!)
                }

Which gives me nothing but a bunch of information about the file, but not its content.

Lojas
  • 195
  • 3
  • 13
  • I don't even have a filesDownload method o.O is it the same as `client.files.download(path:...)`? In that case, your `data` variable should have the contents of the file. – Alex Wally Nov 06 '17 at 07:06
  • @Alex The data variable contains the size of the file for me – Lojas Nov 06 '17 at 07:48
  • Ooh I see what the problem is. The type of data is `Data`, which only shows the size if you `print` it. You'll have to turn it into a string via: `if let fileContents = String(data: data, encoding: .utf8) { print(fileContents) }` – Alex Wally Nov 06 '17 at 07:58
  • Once you download the file to your device, you need to use the FileManager class to process it. See this answer to help get started: [How do you read data from a text file in Swift 3 (XCode 8)](https://stackoverflow.com/questions/41822966/how-do-you-read-data-from-a-text-file-in-swift-3-xcode-8) – Roland Kinsman Jan 06 '19 at 13:14

1 Answers1

2

The reason it prints the file size is that your data variable is of type Data. To print the actual contents, you'll have to convert it to a String first:

if let fileContents = String(data: data, encoding: .utf8) {
    print("Downloaded file data: \(fileContents)")
}

Swift 1

Based on your using println, you might be using an older version of Swift. In that case, the code should look like this:

if let fileContents = NSString(data: data, encoding: NSUTF8StringEncoding) {
    println("Downloaded file data: \(fileContents)")
}

The good thing about the Data type is that you can convert it straight, for example, JSON:

guard let json = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] else {
    return
}
//... do something with json ...
Alex Wally
  • 2,299
  • 1
  • 20
  • 18