Search code examples
swiftdropbox-apiswiftydropbox

How do i get a text files content with swift and the dropbox API


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.


Solution

  • 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 ...