zoukankan      html  css  js  c++  java
  • 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数据以及下载、上传文件功能,具体界面如下:

    以下是创建页面的代码

     
    1. var label:UILabel!  
    2.   var imageView:UIImageView!  
    3.   var txtUserCode:UITextField!  
    4.   var txtUserName:UITextField!  
    5.   var btn : UIButton!  
    6.   let wWidth = UIScreen.main.bounds.size.width  
    7.   let hHeight = UIScreen.main.bounds.size.height  
    8.   var btnDownPic:UIButton!  
    9.   var btnUploadPic:UIButton!  
    10.     
    11.   override func viewDidLoad() {  
    12.       super.viewDidLoad()  
    13.       //初始化Label  
    14.       label = UILabel(frame: CGRect(x: 20, y: 20,  wWidth, height: 30))  
    15.       label.center.x = self.view.center.x  
    16.       label.adjustsFontSizeToFitWidth = true  
    17.       label.font = UIFont(name: "Arial", size: 14)  
    18.       label.lineBreakMode = .byTruncatingTail  
    19.       label.numberOfLines = 1  
    20.       label.text = "请输入用户编号"  
    21.       self.view.addSubview(label)  
    22.       //初始化UITextField  
    23.       txtUserCode = UITextField(frame: CGRect(x: 20, y: 50,  wWidth-40, height: 30))  
    24.       txtUserCode.placeholder = "请输入用户编号"  
    25.       txtUserCode.allowsEditingTextAttributes = true  
    26.       txtUserCode.layer.cornerRadius = 3  
    27.       txtUserCode.borderStyle = .roundedRect  
    28.       txtUserCode.layer.borderWidth = 2  
    29.       txtUserCode.layer.borderColor = UIColor.black.cgColor  
    30.       self.view.addSubview(txtUserCode)  
    31.       txtUserName = UITextField(frame: CGRect(x: 20, y: 80,  wWidth-40, height: 30))  
    32.       txtUserName.placeholder = ""  
    33.       txtUserName.allowsEditingTextAttributes = true  
    34.       txtUserName.layer.cornerRadius = 3  
    35.       txtUserName.borderStyle = .roundedRect  
    36.       txtUserName.layer.borderWidth = 2  
    37.       txtUserName.layer.borderColor = UIColor.black.cgColor  
    38.       self.view.addSubview(txtUserName)  
    39.       //初始化UIButton  
    40.       btn = UIButton(type: .system)  
    41.       btn.frame = CGRect(x: 20, y: 110,  100, height: 35)  
    42.       btn.setTitle("获取用户信息", for: .normal)  
    43.       btn.setTitle("正在获取", for: .highlighted)  
    44.       btn.addTarget(self, action:#selector(btnClick), for: .touchUpInside)  
    45.       self.view.addSubview(btn)  
    46.       //DownLoad picture  
    47.       btnDownPic = UIButton(type: .system)  
    48.       btnDownPic.frame = CGRect(x: 120, y: 110,  200, height: 35)  
    49.       btnDownPic.setTitle("DownLoadPic", for: .normal)  
    50.       btnDownPic.setTitle("正在获取", for: .highlighted)  
    51.       btnDownPic.addTarget(self, action:#selector(AlamofireDownLoad), for: .touchUpInside)  
    52.       self.view.addSubview(btnDownPic)  
    53.       //Upload Picture  
    54.       btnUploadPic = UIButton(type: .system)  
    55.       btnUploadPic.frame = CGRect(x: 220, y: 110,  200, height: 35)  
    56.       btnUploadPic.setTitle("UpLoadPic", for: .normal)  
    57.       btnUploadPic.setTitle("正在上传", for: .highlighted)  
    58.       btnUploadPic.addTarget(self, action:#selector(AlamofireUpLoad), for: .touchUpInside)  
    59.       self.view.addSubview(btnUploadPic)  
    60.       //初始化UIImageView  
    61.       imageView = UIImageView(frame: CGRect(x: 20, y: 140,  440, height: 275))  
    62.       self.view.addSubview(imageView)  
    63.       // Do any additional setup after loading the view, typically from a nib.  
    64.   }  

    后台代码

    由于小编是搞.Net的,所以就写了个一般处理程序(ashx),作为简单的演示,具体代码如下:

     
    1. using System;  
    2. using System.Collections.Generic;  
    3. using System.Linq;  
    4. using System.Web;  
    5. using CYQ.Data;  
    6. using Swift.Entity;  
    7. using Newtonsoft.Json;  
    8. using System.Text;  
    9.   
    10. namespace Swift.Web.Handler  
    11. {  
    12.     /// <summary>  
    13.     /// ajaxHandler 的摘要说明  
    14.     /// </summary>  
    15.     public class ajaxHandler : IHttpHandler  
    16.     {  
    17.   
    18.         public void ProcessRequest(HttpContext context)  
    19.         {  
    20.             context.Response.ContentType = "text/plain";  
    21.             context.Response.ContentEncoding = Encoding.UTF8;  
    22.             //context.Response.Write("Hello World");  
    23.             if (context.Request.Params.AllKeys.Contains("upload"))  
    24.             {  
    25.                 ProcessUpload(context);  
    26.             }  
    27.             else  
    28.             {  
    29.                 var userCode = context.Request.Params["UserCode"];  
    30.                 List<T_User> lstUsers = new List<T_User>();  
    31.                 using (T_User user = new T_User())  
    32.                 {  
    33.                     lstUsers = user.Select<T_User>("Code = '" + userCode + "'").ToList();  
    34.                 }  
    35.                 context.Response.Write(JsonConvert.SerializeObject(lstUsers));  
    36.             }  
    37.         }  
    38.   
    39.         public void ProcessUpload(HttpContext context)  
    40.         {  
    41.             var data = context.Request.Form["beauty"];  
    42.             string str = string.Empty;  
    43.         }  
    44.   
    45.         public bool IsReusable  
    46.         {  
    47.             get  
    48.             {  
    49.                 return false;  
    50.             }  
    51.         }  
    52.     }  
    53. }  

    请求后台数据

    这里我使用用户编号获取用户姓名,往后台传递用户编号,后台返回一个序列化的json字符串,方法使用的responseString,类似的还有responseJSON、response等

     
    1. @objc func btnClick(){  
    2.         if(self.txtUserCode.text!.isEmpty){  
    3.             let alertControl = UIAlertController(title: "提示", message: "请输入用户编号", preferredStyle: .alert)  
    4.             let alertAction = UIAlertAction(title: "确定", style: .default, handler: nil)  
    5.             alertControl.addAction(alertAction)  
    6.             self.present(alertControl, animated: true, completion: {  
    7.                   
    8.             })  
    9.             return  
    10.         }  
    11.         let para:[String:Any] = ["UserCode":self.txtUserCode.text!]  
    12.         let url:String = "http://114.115.214.130/Handler/ajaxHandler.ashx"  
    13.         Alamofire.request(url, method: .post, parameters: para, encoding: URLEncoding.default, headers: nil).responseString { (response) in  
    14.             if(response.result.isSuccess){  
    15.                 let str = response.result.value  
    16.                 let data = str?.data(using: .utf8)  
    17.                 let jsonResult = try? JSON(data: data!, options: JSONSerialization.ReadingOptions.allowFragments)  
    18.                 let userName = jsonResult![0]["Name"].string  
    19.                 self.txtUserName.text = userName  
    20.             }else{  
    21.                 self.txtUserName.text = "获取数据失败"  
    22.             }  
    23.         }  
    24.     }  

    下载文件


    下载图片的URL必须遵循文件协议,即以file://开头

     
    1. //下载图片  
    2.     @objc func AlamofireDownLoad(){  
    3.         let imageUrl = "http://114.115.214.130/images/1.jpg"  
    4.         Alamofire.download(imageUrl) { (url, response) -> (destinationURL: URL, options: DownloadRequest.DownloadOptions) in  
    5.             let fileUrl = "file:///" + NSHomeDirectory() + "/Documents/1.jpg"  
    6.             let options = DownloadRequest.DownloadOptions.removePreviousFile  
    7.             return(URL(string: fileUrl)!,options)  
    8.             }.downloadProgress { (progress) in  
    9.                   
    10.             }.response { (response1) in  
    11.                 if response1.error == nil{  
    12.                     self.imageView.image = UIImage(named: NSHomeDirectory() + "/Documents/1.jpg")  
    13.                 }else{  
    14.                     print(response1.error)  
    15.                 }  
    16.         }  
    17.     }  

    上传文件

     
    1. @objc func AlamofireUpLoad(){  
    2.        let urlUpload = "http://192.168.2.101/Handler/ajaxHandler.ashx"  
    3.        let headers = ["content-type":"multipart/form-data"]  
    4.        Alamofire.upload(multipartFormData: { (multidata) in  
    5.            multidata.append("lisen".data(using: String.Encoding.utf8)!, withName: "upload")  
    6.            let image = #imageLiteral(resourceName: "timg.jpeg")  
    7.            multidata.append(UIImageJPEGRepresentation(image, 1.00)!, withName: "beauty", mimeType: "mage/*")  
    8.        }, to: URL(string: urlUpload)!) { (result) in  
    9.            switch result{  
    10.            case .success(let upload, streamingFromDisk: _, streamFileURL: _):  
    11.                upload.response(completionHandler: { (response) in  
    12.                    if(response.error == nil){  
    13.                        print("upload success")  
    14.                    }else{  
    15.                        print(response.error)  
    16.                    }  
    17.                })  
    18.            case .failure(let encodingError):  
    19.                print(encodingError.localizedDescription)  
    20.            }  
    21.        }  
    22.          
    23.          
    24.    }  
     
    本文地址:https://www.lisen.me/263.html
    版权声明:本文为原创文章,版权归 李森的博客 所有,欢迎分享本文,转载请保留出处!
  • 相关阅读:
    es6学习笔记
    vue.js项目目录结构说明
    js 数组操作总结
    js 数组去重方法
    HTTP协议三次握手过程
    MVC与MVVM模式对比
    谱面编辑器
    LL谱面分析和难度标定
    SLP的模块结构
    LL基本姿势
  • 原文地址:https://www.cnblogs.com/ilisen/p/7103103.html
Copyright © 2011-2022 走看看