AFNetWorking
创建AFHTTPSessionManager管理者对象
let afnManager = AFHTTPSessionManager()
Get请求
func getRequest() {
afnManager.get("http://120.25.226.186:32812/login?username=520it&pwd=520it&type=JSON", parameters: nil, progress: { (progress:Progress) in
print(progress)
}, success: { (task:URLSessionDataTask, resposeObject:Any?) in
print(task)
print(resposeObject ?? "no respose object")
print(Thread.current)
}) { (task:URLSessionDataTask?, error:Error) in
print(task ?? "no task")
print(error)
print(Thread.current)
}
}
Post请求
func postRequest() {
let param = [
"username" : "520it",
"pwd" : "520it",
"type" : "JSON"
]
afnManager.post("http://120.25.226.186:32812/login", parameters: param, progress: { (progress:Progress) in
print(progress)
}, success: { (task:URLSessionDataTask, resposeObject:Any?) in
print(task)
print(resposeObject ?? "no respose object")
print(Thread.current)
}) { (task:URLSessionDataTask?, error:Error) in
print(task ?? "no task")
print(error)
print(Thread.current)
}
}
Download下载
func download() {
let request = URLRequest(url: URL(string: "http://120.25.226.186:32812/resources/videos/minion_01.mp4")!)
//从afnManager中得到一个URLSessionDownloadTask任务对象
let downloadTask = afnManager.downloadTask(with: request, progress: { (progress:Progress) in
//监视进度,progress.completedUnitCount:已下载数据大小,progress.totalUnitCount文件总数据大小
print("\(Int(CGFloat(progress.completedUnitCount) * 1.0 / (CGFloat(progress.totalUnitCount) * 1.0) * 100))%")
}, destination: { (targetPath:URL, response:URLResponse) -> URL in
//如果不指定存储目录,下载的数据会被当做是一个临时对象缓存在tmp目录下,随时可能被系统清理
print(targetPath)
print(response)
//所以我们要重新指定目录Document,如果希望文件长久保留。可以使用响应对象response中建议的文件名,
let downloadPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).last?.appending("/\(response.suggestedFilename!)")
//然后把这个重新指定的目录告诉AFN,文件就会指定存在这里了
return URL(fileURLWithPath: downloadPath!)
}) { (response:URLResponse, url:URL?, error:Error?) in
print(response)
print(url ?? "no url")
if error != nil {
print(error!)
}
}
//最后记得让任务执行哦
downloadTask.resume()
}
upload上传
func upload(){
afnManager.post("http://120.25.226.186:32812/upload", parameters: nil, constructingBodyWith: { (formData:AFMultipartFormData) in
//constructingBodyWith是一个AFMultipartFormData对象,可以将要上传的文件放在这里,比如一个文件或是一个二进制数据等
try? formData.appendPart(withFileURL: URL.init(fileURLWithPath: "/Users/zhangfan/Pictures/2.jpg"), name: "file")
}, progress: { (progress:Progress) in
print("\(Int(CGFloat(progress.completedUnitCount) * 1.0 / (CGFloat(progress.totalUnitCount) * 1.0) * 100))%")
}, success: { (task:URLSessionDataTask, responseObject:Any?) in
print(task)
print(responseObject ?? "no respose object")
print((responseObject as! [String : Any])["success"]!)
print(Thread.current)
}) { (task:URLSessionDataTask?, error:Error) in
print(task ?? "no task")
print(error)
print(Thread.current)
}
}