如何在 swift 的文档目录中复制远程服务器文件

How to copy remote server file in document directory in swift

我知道如何在 Swift

中获得遥控器 URL
let remoteURL = NSURL(string: "https://myserver/file.txt")!

我知道如何在 Swift

获得本地 URL
let localURL = NSURL(fileURLWithPath: documentsFolder + "/my_local_file.txt")

不幸的是这不起作用

NSFileManager.defaultManager().copyItemAtURL(remoteURL, toURL: localURL)

出现以下错误

The file “file.txt” couldn’t be opened because URL type https isn’t supported.

有没有办法执行此操作?

您应该先下载它,然后将其保存到本地文件。

代码示例可在此处找到:(使用 AFNetworking

您可以使用 NSURLSessionDownloadTask 下载文件:

func downloadFile(url: URL) {
    let downloadRequest = URLRequest(url: url)
    URLSession.shared.downloadTask(with: downloadRequest) { location, response, error in
        // To do check resoponse before saving
        guard  let tempLocation = location where error == nil else { return }
        let documentDirectory = FileManager.default.urlsForDirectory(.documentDirectory, inDomains: .userDomainMask).last
        do {
            let fullURL = try documentDirectory?.appendingPathComponent((response?.suggestedFilename!)!)
            try FileManager.default.moveItem(at: tempLocation, to: fullURL!)
            print("saved at \(fullURL) ")
        } catch NSCocoaError.fileReadNoSuchFileError {
            print("No such file")
        } catch {
            // other errors
            print("Error downloading file : \(error)")
        }
    }.resume()
}

let stringURL = "https://wordpress.org/plugins/about/readme.txt"
downloadImage(url: URL(string: stringURL)!)

更新:SWIFT 2.2

func downloadFile(url: NSURL) {
    let downloadRequest = NSURLRequest(URL: url)
    NSURLSession.sharedSession().downloadTaskWithRequest(downloadRequest){ (location, response, error) in

        guard  let tempLocation = location where error == nil else { return }
        let documentDirectory = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).first
        let fullURL = documentDirectory?.URLByAppendingPathComponent((response?.suggestedFilename)!)

        do {
            try NSFileManager.defaultManager().moveItemAtURL(tempLocation, toURL: fullURL!)
        } catch NSCocoaError.FileReadNoSuchFileError {
            print("No such file")
        } catch {
            print("Error downloading file : \(error)")
        }

        }.resume()
}

 let stringURL = "https://wordpress.org/plugins/about/readme.txt"
 let url = NSURL.init(string: stringURL)
 downloadFile(url!)