Swift使用Alamofire
Posted 香草物语
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Swift使用Alamofire相关的知识,希望对你有一定的参考价值。
Alamofire简介
AFNetworking 是 ios 和 macOS 上最受欢迎的第三方库之一。它曾在我们的2012年的读者评选中荣获2012年度最佳 iOS 库称号。它同样也在 Github 上面获得了27000 多个 stars 和 8000 多个 forks,是使用最广的开源项目之一。
自2014年 Swift 推出之后,AFNetworking 的作者 Mattt Thompson 便提交了一个新的类似于 AFNetworking 的网络基础框架,并且是专门使用最新的 Swift 语言来编写的,其名为:Alamofire。AFNetwork 的前缀 AF 是 Alamofire 的缩写,因为这个新的框架名称是根据 Swift 的约定来进行命名的。
Alamofirea安装
本人是小白一枚,也是刚刚学习swift,所以安装过程不是使用的cocoapod,我是直接在GitHub把代码clone到本地,然后附加项目进行配置的。具体如下:
- 将Alamofire代码clone或者下载到本地,加压之后将项目附加到自己项目中
- 添加项目依赖
添加完成后,项目信息如下:
界面搭建
为了演示效果,简单的做了一个演示的界面,主要包含向后台请求json数据以及下载、上传文件功能,具体界面如下:
以下是创建页面的代码
- var label:UILabel!
- var imageView:UIImageView!
- var txtUserCode:UITextField!
- var txtUserName:UITextField!
- var btn : UIButton!
- let wWidth = UIScreen.main.bounds.size.width
- let hHeight = UIScreen.main.bounds.size.height
- var btnDownPic:UIButton!
- var btnUploadPic:UIButton!
- override func viewDidLoad() {
- super.viewDidLoad()
- //初始化Label
- label = UILabel(frame: CGRect(x: 20, y: 20, width: wWidth, height: 30))
- label.center.x = self.view.center.x
- label.adjustsFontSizeToFitWidth = true
- label.font = UIFont(name: "Arial", size: 14)
- label.lineBreakMode = .byTruncatingTail
- label.numberOfLines = 1
- label.text = "请输入用户编号"
- self.view.addSubview(label)
- //初始化UITextField
- txtUserCode = UITextField(frame: CGRect(x: 20, y: 50, width: wWidth-40, height: 30))
- txtUserCode.placeholder = "请输入用户编号"
- txtUserCode.allowsEditingTextAttributes = true
- txtUserCode.layer.cornerRadius = 3
- txtUserCode.borderStyle = .roundedRect
- txtUserCode.layer.borderWidth = 2
- txtUserCode.layer.borderColor = UIColor.black.cgColor
- self.view.addSubview(txtUserCode)
- txtUserName = UITextField(frame: CGRect(x: 20, y: 80, width: wWidth-40, height: 30))
- txtUserName.placeholder = ""
- txtUserName.allowsEditingTextAttributes = true
- txtUserName.layer.cornerRadius = 3
- txtUserName.borderStyle = .roundedRect
- txtUserName.layer.borderWidth = 2
- txtUserName.layer.borderColor = UIColor.black.cgColor
- self.view.addSubview(txtUserName)
- //初始化UIButton
- btn = UIButton(type: .system)
- btn.frame = CGRect(x: 20, y: 110, width: 100, height: 35)
- btn.setTitle("获取用户信息", for: .normal)
- btn.setTitle("正在获取", for: .highlighted)
- btn.addTarget(self, action:#selector(btnClick), for: .touchUpInside)
- self.view.addSubview(btn)
- //DownLoad picture
- btnDownPic = UIButton(type: .system)
- btnDownPic.frame = CGRect(x: 120, y: 110, width: 200, height: 35)
- btnDownPic.setTitle("DownLoadPic", for: .normal)
- btnDownPic.setTitle("正在获取", for: .highlighted)
- btnDownPic.addTarget(self, action:#selector(AlamofireDownLoad), for: .touchUpInside)
- self.view.addSubview(btnDownPic)
- //Upload Picture
- btnUploadPic = UIButton(type: .system)
- btnUploadPic.frame = CGRect(x: 220, y: 110, width: 200, height: 35)
- btnUploadPic.setTitle("UpLoadPic", for: .normal)
- btnUploadPic.setTitle("正在上传", for: .highlighted)
- btnUploadPic.addTarget(self, action:#selector(AlamofireUpLoad), for: .touchUpInside)
- self.view.addSubview(btnUploadPic)
- //初始化UIImageView
- imageView = UIImageView(frame: CGRect(x: 20, y: 140, width: 440, height: 275))
- self.view.addSubview(imageView)
- // Do any additional setup after loading the view, typically from a nib.
- }
后台代码
由于小编是搞.Net的,所以就写了个一般处理程序(ashx),作为简单的演示,具体代码如下:
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using CYQ.Data;
- using Swift.Entity;
- using Newtonsoft.Json;
- using System.Text;
- namespace Swift.Web.Handler
- {
- /// <summary>
- /// ajaxHandler 的摘要说明
- /// </summary>
- public class ajaxHandler : IHttpHandler
- {
- public void ProcessRequest(HttpContext context)
- {
- context.Response.ContentType = "text/plain";
- context.Response.ContentEncoding = Encoding.UTF8;
- //context.Response.Write("Hello World");
- if (context.Request.Params.AllKeys.Contains("upload"))
- {
- ProcessUpload(context);
- }
- else
- {
- var userCode = context.Request.Params["UserCode"];
- List<T_User> lstUsers = new List<T_User>();
- using (T_User user = new T_User())
- {
- lstUsers = user.Select<T_User>("Code = ‘" + userCode + "‘").ToList();
- }
- context.Response.Write(JsonConvert.SerializeObject(lstUsers));
- }
- }
- public void ProcessUpload(HttpContext context)
- {
- var data = context.Request.Form["beauty"];
- string str = string.Empty;
- }
- public bool IsReusable
- {
- get
- {
- return false;
- }
- }
- }
- }
请求后台数据
这里我使用用户编号获取用户姓名,往后台传递用户编号,后台返回一个序列化的json字符串,方法使用的responseString,类似的还有responseJSON、response等
- @objc func btnClick(){
- if(self.txtUserCode.text!.isEmpty){
- let alertControl = UIAlertController(title: "提示", message: "请输入用户编号", preferredStyle: .alert)
- let alertAction = UIAlertAction(title: "确定", style: .default, handler: nil)
- alertControl.addAction(alertAction)
- self.present(alertControl, animated: true, completion: {
- })
- return
- }
- let para:[String:Any] = ["UserCode":self.txtUserCode.text!]
- let url:String = "http://114.115.214.130/Handler/ajaxHandler.ashx"
- Alamofire.request(url, method: .post, parameters: para, encoding: URLEncoding.default, headers: nil).responseString { (response) in
- if(response.result.isSuccess){
- let str = response.result.value
- let data = str?.data(using: .utf8)
- let jsonResult = try? JSON(data: data!, options: JSONSerialization.ReadingOptions.allowFragments)
- let userName = jsonResult![0]["Name"].string
- self.txtUserName.text = userName
- }else{
- self.txtUserName.text = "获取数据失败"
- }
- }
- }
下载文件
下载图片的URL
必须遵循文件协议,即以file://
开头
- //下载图片
- @objc func AlamofireDownLoad(){
- let imageUrl = "http://114.115.214.130/images/1.jpg"
- Alamofire.download(imageUrl) { (url, response) -> (destinationURL: URL, options: DownloadRequest.DownloadOptions) in
- let fileUrl = "file:///" + NSHomeDirectory() + "/Documents/1.jpg"
- let options = DownloadRequest.DownloadOptions.removePreviousFile
- return(URL(string: fileUrl)!,options)
- }.downloadProgress { (progress) in
- }.response { (response1) in
- if response1.error == nil{
- self.imageView.image = UIImage(named: NSHomeDirectory() + "/Documents/1.jpg")
- }else{
- print(response1.error)
- }
- }
- }
上传文件
- @objc func AlamofireUpLoad(){
- let urlUpload = "http://192.168.2.101/Handler/ajaxHandler.ashx"
- let headers = ["content-type":"multipart/form-data"]
- Alamofire.upload(multipartFormData: { (multidata) in
- multidata.append("lisen".data(using: String.Encoding.utf8)!, withName: "upload")
- let image = #imageLiteral(resourceName: "timg.jpeg")
- multidata.append(UIImageJPEGRepresentation(image, 1.00)!, withName: "beauty", mimeType: "mage/*")
- }, to: URL(string: urlUpload)!) { (result) in
- switch result{
- case .success(let upload, streamingFromDisk: _, streamFileURL: _):
- upload.response(completionHandler: { (response) in
- if(response.error == nil){
- print("upload success")
- }else{
- print(response.error)
- }
- })
- case .failure(let encodingError):
- print(encodingError.localizedDescription)
- }
- }
- }
以上是关于Swift使用Alamofire的主要内容,如果未能解决你的问题,请参考以下文章