siwft_上传和下载

siwft_上传和下载

下载文件,并将文件存储到指定的文件中

func simpleDownload() {

let  destination = DownloadRequest.suggestedDownloadDestination(for: FileManager.SearchPathDirectory.documentDirectory, in: FileManager.SearchPathDomainMask.userDomainMask)

//打印存储文件的沙盒路径

print( NSHomeDirectory() + "/Documents")

//下载然后查看下载文件

let result = Alamofire.download("https://httpbin.org/stream/1", to: destination)

print(result)

}

更复杂一点的用

func complexDownLoad() {

let  param = ["foo":"bar"]

let  destination = DownloadRequest.suggestedDownloadDestination(for: FileManager.SearchPathDirectory.documentDirectory, in: FileManager.SearchPathDomainMask.userDomainMask)

Alamofire.download("http://img.sccnn.com/bimg/313/507.jpg", method: .get, parameters: param, encoding:JSONEncoding.default, headers: nil, to: destination).downloadProgress(queue: DispatchQueue.global()) { (progress) in

//进度的完成比例

print("Progress1:\(progress.fractionCompleted)")

//已经下载的字节数

print("Progress2:\(progress.completedUnitCount)")

//全部的字节数

print("Progress3:\(progress.totalUnitCount)")

}.validate { (request, respon, temporaryURL, destinationURL) -> Request.ValidationResult in

//完成图片下载后执行验证方法,此处返回成功标识

print("请求成功")

return .success

}.responseJSON { (response) in

//依次输出返回对象,图片下载临时存放位置,以及下载位置后的存储位置

debugPrint("response:\(response)")

print("response.temporaryURL:\(String(describing: response.temporaryURL))")

print("destinationURL:\(String(describing: response.destinationURL))")

}

}

可以自己添加一个下载进度条

上传

我将图片添加到工程中了,实际中应该取自相册或者相机拍照

func simpleUpload() {

//此处一定要有图片,因为我下边用的

let fileURL = Bundle.main.url(forResource: "507", withExtension: "jpg")

Alamofire.upload(fileURL!, to:"http://httpbin.org/post").uploadProgress(queue: DispatchQueue.global(), closure: { (progress) in

print("Progress1:\(progress.fractionCompleted)")

}).validate().responseJSON { (response) in

DispatchQueue.main.async {

print("result:\(response.result)")

}

}

}