如何使用 SwiftyDropbox 的 "destination" 下载

How to Use SwiftyDropbox's "destination" with a Download

在查看 v2 Dropbox API 中的 SwiftyDropbox tutorial 时,它展示了如何执行下载:

// 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: "/MyFile.db", 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!)
    }
}

我不清楚 destination 部分发生了什么。为什么我需要为文件名生成一个随机字符串?

当我尝试指定我自己的文件名时,下载似乎不起作用:

let destination : (NSURL, NSHTTPURLResponse) -> NSURL = { temporaryURL, response in
  let directoryURL = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0]
  return directoryURL.URLByAppendingPathComponent("MyFile.db")
}

我想从 Dropbox 下载一个名为 MyFile.db 的文件,我想将它放在我设备的文档目录中,名称为 MyFile.db 并覆盖它(如果它已经存在)。

我该怎么做?

当你说它似乎不起作用时,我想你的意思是你得到了这样的错误:

Error Domain=NSCocoaErrorDomain Code=516 "“CFNetworkDownload_bPYhu1.tmp” couldn’t be moved to “Documents” because an item with the same name already exists." UserInfo={NSSourceFilePathErrorKey=..., NSUserStringVariant=( Move ), NSDestinationFilePath=..., NSUnderlyingError=0x7fda0a67cea0 {Error Domain=NSPOSIXErrorDomain Code=17 "File exists"}}

SwiftyDropbox,由于使用 AlamoFire,目前不允许您使用 download 函数覆盖文件。

具体来说,SwiftyDropbox calls download in AlamoFire, and AlamoFire calls NSFileManager.moveItemAtURL. The documentation for NSFileManager.moveItemAtURL 说:

If an item with the same name already exists at dstURL, this method aborts the move attempt and returns an appropriate error.

所以,它似乎只是谨慎,让您的应用很难意外覆盖(广告可能会丢失)数据。如果您确定要覆盖特定文件,则需要在 Dropbox API 调用后明确地这样做。不过,我们会将此视为一项功能请求。


更新:SwiftyDropbox 现在提供从 version 3.1.0, e.g., using download(path:rev:overwrite:destination:) 开始直接覆盖文件的功能。