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

时间:2016-08-05 07:56:42

标签: ios swift copy-paste nsfilemanager remote-server

我知道如何在Swift中获取远程URL

let remoteURL = NSURL(string: "https://myserver/file.txt")!

我知道如何在Swift中获取本地网址

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.

有没有办法如何执行此操作?

2 个答案:

答案 0 :(得分:3)

您可以使用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!)

答案 1 :(得分:1)

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

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

How I properly setup an AFNetworking Get Request?