iOS REST Web Service(3)Alamofire

GET请求
// An highlighted block
func startRequest(){
	let strURL="http://www.a.com"
	//设置请求参数,类型是字典
	let params=["id":"1"]
	//调用Alamofire命名空间(Alamofire.framework)中的request()函数,返回值是Request对象
	Alamofire.request(strURL,method:.get,parameters:params).responseJSON{ response in
	self.reloadView(response.result.value as! NSDictionary);
	}
}
POST请求
// An highlighted block
func startRequest(){
	let strURL="http://www.a.com"
	//设置请求参数,类型是字典
	let params=["id":"1"]
	//调用Alamofire命名空间(Alamofire.framework)中的request()函数,返回值是Request对象
	Alamofire.request(strURL,method:.post,parameters:params).responseJSON{ 
	response in
	self.reloadView(response.result.value as! NSDictionary);
	}
}
下载数据
// An highlighted block
@IBAction func onClick(_ sender:AnyObject){
	let strURl=String(format:"http://www.a.com?fileName=%@","test1.jpg")
	//DwonloadRequest是Alamofire提供的下载请求类。suggestedDownloadDestination()方法返回Alamofire推荐的下载目标文件的闭包。
	let destination=DownloadRequest.suggestedDownloadDestination()
	Alamofire.download(strURL,method:.post,to: destination).downloadProgress{
		progress in
		//progress方法能够获取下载进度,progress.fractionCompleted用于获得下载进度的小树表示方式。
		print("下载进度:%f",progress.fractionCompleted}
		sefl.progressView.setProgress(Float(progress.fractionCompleted),animated:true)
	}
	.responseJSON{
		response in 
		//response.destinationURL表达式用户返回下载目标的文件路径。
		print("下载成功,保存文件%@",response.destinationURL!)
		//通过文件路径创建NSData缓存对象
		let data=NSData(contentsOf:response.destinationURL!)
		//创建图片对象
		let img=UIImage(data:data as!Data)
		self.imageView1.image=img
	}
}

上传数据
// An highlighted block
@IBAction func onClick(_ sender:AnyObject){
	let uploadStrURL=String(format:"http://www.a.com?id=%@","1")
	let fileURL=Bundle.main.url(forResource:"test2",withExtension:"jpg")!
	//使用Alamofire.upload函数上传数据。
	Alamofire.upload(
		//封装multipart/form-data格式的表单数据
		multipartFormData:{
			multipartFormData in
			//通过append方法向表单数据中添加数据。
			multipartFormData.append(fileURL,withName:"file",fileName:"1.jpg",mimeType:"image/jpeg")
		},
		//设置内存占用阈值
		usingThreshold:UIn64(1024),
		to:uploadStrURL,
		//表单数据编码完成后调用的闭包。
		encodingCompletion:{
			switch result{
			//成功返回数据的情况
			case .success(let upload, _, _):
				upload.uploadProgress{
					print("上传进度=\(progress.fractionCompleted)")
					self.progressVeiw.setProgress(Float(progress.fractionCompleted), animated:true)
				//上传成功的回调闭包
				}.response{
					print("上传成功")
				}
			case .failure(let encodingError):
				print("上传失败\(encodingError)")
			}
		}
	)
}

参考资料
《IOS开发指南 从HELLO WORLD到APP STORE上架 第5版》

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值