SwiftyDropbox 下载进度

标签 swift dropbox-api

我正在使用此代码下载一个文件,它工作正常。

// Download a file

let destination : (NSURL, NSHTTPURLResponse) -> NSURL = { temporaryURL, response in
    let fileManager = NSFileManager.defaultManager()
    let directoryURL = fileManager.URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0]
    // generate a unique name for this file in case we've seen it before
    let UUID = NSUUID().UUIDString
    let pathComponent = "\(UUID)-\(response.suggestedFilename!)"
    return directoryURL.URLByAppendingPathComponent(pathComponent)
}

client.files.download(path: "/hello.txt", destination: destination).response { response, error in
    if let (metadata, url) = response {
        print("*** Download file ***")
        let data = NSData(contentsOfURL: url)
        print("Downloaded file name: \(metadata.name)")
        print("Downloaded file url: \(url)")
        print("Downloaded file data: \(data)")
    } else {
        print(error!)
    }
}

我的问题是如何获取下载进度以显示给用户?

最佳答案

改编自tutorial , 你可以在 download 方法上添加一个 progress 回调来获取进度信息:

// Download a file
let destination : (NSURL, NSHTTPURLResponse) -> NSURL = { temporaryURL, response in
    let fileManager = NSFileManager.defaultManager()
    let directoryURL = fileManager.URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0]
    // generate a unique name for this file in case we've seen it before
    let UUID = NSUUID().UUIDString
    let pathComponent = "\(UUID)-\(response.suggestedFilename!)"
    return directoryURL.URLByAppendingPathComponent(pathComponent)
}

Dropbox.authorizedClient!.files.download(path: "/path/to/Dropbox/file", destination: destination)

    .progress { bytesRead, totalBytesRead, totalBytesExpectedToRead in

        print("bytesRead: \(bytesRead)")
        print("totalBytesRead: \(totalBytesRead)")
        print("totalBytesExpectedToRead: \(totalBytesExpectedToRead)")

    }

    .response { response, error in

        if let (metadata, url) = response {
            print("*** Download file ***")
            print("Downloaded file name: \(metadata.name)")
            print("Downloaded file url: \(url)")
        } else {
            print(error!)
        }

    }

然后您可以使用该原始进度信息来支持您应用中的进度 UI。

关于SwiftyDropbox 下载进度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35659454/

相关文章:

ios - 如何为 Swift 应用程序中的每个 View 编写不同的键盘处理?

ios - Swift - Firebase 获取所有键并将它们存储到数组中

ios - 在 iOS 上集成 Amazon Payments(Swift 或 Objective-C)

arrays - 我可以从 View Controller 文件访问 dataArray 但出现错误 Fatal error : Index out of range?

android - 在 Android 版 Dropbox 中从哪里可以找到 App Secret?

ios - 调度组通知似乎被调用得太早

ios - 直接获取当前/delta光标

android - 为什么使用 dropbox 的 Core Api 而不是 Sync API

node.js - 如何修复 Dropbox Node API 错误 400 请求 header 或 Cookie 太大

java - 如何读取 读取/获取 Dropbox 文件