编辑代码

fun csessionDownloadImage(){
//下载地址
let url=URL(string: "http://hangge.com/blog/images/logo.png")//请求
let request = URLRequest(url: url!)
let session = URLSession.shared
//下载任务
let downloadTask = session.downloadTask(with: request, completionHandler:
(location:URL?, response:URLResponse?,error:Error?)
-> Void in
//输出下载文件原来的存放目录
print("location:\(String(describing: location))")//location位置转换
let locationPath = location?.path
//获取当前时间
let now = NSDate()
//当前时间的时间戳
let timeInterval:TimeInterval = now.timeIntervalSince1970let timeStamp = String(timeInterval)
//拷贝到用户目录
let documents:String =NSHomeDirectory()+"/Documents/ (timeStamp).png"
//创建文件管理器
let fileManager = FileManager.default
try! fileManager.moveItem(atPath: locationPath!, toPath: documents)
print("new location:\(documents)")
})
// 使用 resume 方法启动任务
downloadTask.resume()
}