以前在swift3的时候,写过类似的,那个时候还没有很成熟的网络请求类库,在这里,还是衷心感谢大神们的付出!

具体效果如下,先上图:

swift开发之--简单封装Alamofire请求类以及简单使用SnapKit_3d

点击按钮的时候,请求数据,数据结构如下:

{
    "error_code" = 0;
    reason = successed;
    result =     (
                {
            des = "\U68a6\U89c1\U9ec4\U91d1\Uff0c\U9884\U793a\U4f1a\U906d\U9047\U632b\U6298\U3002\U68a6\U89c1\U6709\U4eba\U9001\U9ec4\U91d1\U7ed9\U81ea\U5df1\Uff0c\U53ef\U80fd\U4f1a\U8499\U53d7\U635f\U5931\U3002\U5973\U4eba\U68a6\U89c1\U4e22\U4e86\U9ec4\U91d1\Uff0c\U9884\U793a\U6dfb\U7f6e\U65b0\U9996\U9970\U3002";
            id = 873e943d1bcb40cd4b289e0809803343;
            title = "\U9ec4\U91d1 \U91d1\U5b50";
        },
                {
            des = "\U68a6\U89c1\U9ec4\U91d1\Uff0c\U9884\U793a\U4f1a\U906d\U9047\U632b\U6298\U3002\U68a6\U89c1\U6709\U4eba\U9001\U9ec4\U91d1\U7ed9\U81ea\U5df1\Uff0c\U53ef\U80fd\U4f1a\U8499\U53d7\U635f\U5931\U3002\U5973\U4eba\U68a6\U89c1\U4e22\U4e86\U9ec4\U91d1\Uff0c\U9884\U793a\U6dfb\U7f6e\U65b0\U9996\U9970\U3002";
            id = 237169518a0ff81aec29b80a546aa7ac;
            title = "\U9ec4\U91d1";
        },
                {
            des = "\U68a6\U89c1\U6361\U9ec4\U91d1\Uff0c\U4f60\U8981\U53d1\U5927\U8d22\Uff0c\U4f46\U8981\U52aa\U529b\U4e89\U53d6\U3002\U53d1\U8d22\U4e5f\U8981\U4ed8\U51fa\U52aa\U529b\Uff0c\U4e0d\U4f1a\U81ea\U52a8\U6389\U5728\U4f60\U7684\U53e3\U888b\U91cc\U3002";
            id = 315f055cfbae60064e07427321e6a722;
            title = "\U6361\U9ec4\U91d1";
        }
    );
}

具体代码如下:

1、目录结构

因为是在oc项目里面直接写的swift,所以桥接文件相关的知识点,可以参考这篇博客:

https://www.jianshu.com/p/754396e7e1bd,还用到了公共类,可以参考我的另一篇博客

swift开发之--简单封装Alamofire请求类以及简单使用SnapKit_3d_02

 

2、先布局,最上面是个textfield,中间是个buutton,最下层是个tableview,使用的事自定义的cell(xib),代码如下:

func setUI() {
        self.textField = UITextField()
        self.textField.placeholder = "请输入你梦境中梦到的人、事或者物"
        self.view.addSubview(self.textField)
        self.textField.snp.makeConstraints { (make) in
            make.centerX.equalTo(self.view)
            make.top.equalTo(100)
            make.left.equalTo(16)
            make.height.equalTo(40)
        }
        
        let button:UIButton = UIButton(type: .custom)
        button.setTitle("点击", for: .normal)
        button.backgroundColor = UIColor.red
        self.view.addSubview(button)
        button.addTarget(self, action: #selector(sendAction), for: .touchUpInside)
        
        button.snp.makeConstraints { (make) in
            make.centerX.equalTo(self.view)
            make.top.equalTo(self.textField.snp.bottom).offset(10)
            make.left.equalTo(16)
            make.height.equalTo(45)
        }
        
        
        self.table = UITableView(frame: CGRect(x: 0, y: 200, width:ScrnWidth , height: ScrnHeight-100),style: .plain)
        self.table.delegate = self
        self.table.dataSource = self
        self.table.register(UINib(nibName: "MyCell", bundle: nil), forCellReuseIdentifier: "mycell")
        self.view.addSubview(self.table)
        self.table.estimatedRowHeight = UITableView.automaticDimension
        self.table.tableFooterView = UIView()
    }

3、工具类:网络请求类Alamofire,这里简单封装了下:

import UIKit
import Alamofire
import SwiftyJSON

enum MethodType {
    case get
    case post
}

class SwiftRequest {
    class func requestData(_ type : MethodType, URLString : String, parameters : [String : Any]? = nil, finishedCallback :  @escaping (_ result : Any) -> ()) {
        
        // 1.获取类型
        let method = type == .get ? HTTPMethod.get : HTTPMethod.post
        
        // 2.发送网络请求
        Alamofire.request(URLString, method: method, parameters: parameters).responseJSON { (response) in
            
            // 3.获取结果
            guard let result = response.result.value else {
                print(response.result.error!)
                return
            }
            
            // 4.将结果回调出去
            finishedCallback(result)
        }
    }
}

全部代码如下:

import UIKit
import SnapKit
import SwiftyJSON

class OpenDreamViewController: UIViewController,UITableViewDelegate,UITableViewDataSource {

    lazy var table = UITableView()
    var textField = UITextField()
    lazy var dataArray = NSArray()
    
    
    override func viewDidLoad() {
        super.viewDidLoad()

        self.view.backgroundColor = UIColor.white
        self.setUI()
    }
    
    func setUI() {
        self.textField = UITextField()
        self.textField.placeholder = "请输入你梦境中梦到的人、事或者物"
        self.view.addSubview(self.textField)
        self.textField.snp.makeConstraints { (make) in
            make.centerX.equalTo(self.view)
            make.top.equalTo(100)
            make.left.equalTo(16)
            make.height.equalTo(40)
        }
        
        let button:UIButton = UIButton(type: .custom)
        button.setTitle("点击", for: .normal)
        button.backgroundColor = UIColor.red
        self.view.addSubview(button)
        button.addTarget(self, action: #selector(sendAction), for: .touchUpInside)
        
        button.snp.makeConstraints { (make) in
            make.centerX.equalTo(self.view)
            make.top.equalTo(self.textField.snp.bottom).offset(10)
            make.left.equalTo(16)
            make.height.equalTo(45)
        }
        
        
        self.table = UITableView(frame: CGRect(x: 0, y: 200, width:ScrnWidth , height: ScrnHeight-100),style: .plain)
        self.table.delegate = self
        self.table.dataSource = self
        self.table.register(UINib(nibName: "MyCell", bundle: nil), forCellReuseIdentifier: "mycell")
        self.view.addSubview(self.table)
        self.table.estimatedRowHeight = UITableView.automaticDimension
        self.table.tableFooterView = UIView()
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.dataArray.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell:MyCell = tableView.dequeueReusableCell(withIdentifier: "mycell") as! MyCell
        
        let dict = self.dataArray[indexPath.row] as! NSDictionary
        
        
        cell.titleLab.text = dict["title"] as? String
        cell.contentLab.text = (dict["des"] as? String)
        
        return cell
    }
    
    func setData() {
        
        let parameters : [String : String] = ["q" : self.textField.text!,"key":key]
        
        SwiftRequest.requestData(.get, URLString: "http://zhouxunwang.cn/data/?id=60", parameters: parameters) { (result) in
            
            print(result)
            
            let Dict = result as! NSDictionary
            let error = Dict["error_code"] as! Int64
            
            if error == 0{
                self.dataArray = Dict["result"] as! NSArray
            }else{
                print("请求失败")
            }

            self.table.reloadData()
        }
        
    }

    @objc func sendAction() {
        
        self.textField.endEditing(true)
        
        print("点击了")
        
        if (self.textField.text?.isEmpty ?? nil)! {
            print("不能为空")

            return
        }else{
        
            self.setData()
        }
    }

}

以上就是简单封装一个请求类,请求数据的的一个简单demo,上面的接口是免费的可以直接用!

仅做记录!后期会陆续加上swiftjson和model


作者:稻草人11223