iOS.Swift使用 POST请求

URLService

 

 

 

import UIKit

 

class URLService: NSObject {

 

    func POST(url:String,pass:@escaping (Any,Bool)->Void) {

        let urlStr = URL.init(string: "http://api.jisuapi.com/illegaladdr/city")

        var req = URLRequest.init(url: urlStr!, cachePolicy: .reloadIgnoringLocalCacheData, timeoutInterval: 10)

        // 设置请求方式为POST

        req.httpMethod = "POST"

        // 将所有的参数拼接成一个字符串

        let str = "city=\(url)&num=10&appkey=de394933e1a3e2db"

        req.httpBody = str.data(using: .utf8)

        

        URLSession.shared.dataTask(with: req) { (data, response:URLResponse?, error) in

            

            let jsonData = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments)

 

            let jsonDic = jsonData as! NSDictionary

            let status = jsonDic.value(forKey: "status") as! NSString

            let msg = jsonDic.value(forKey: "msg") as! String

            if status.intValue != 0 {

                print(msg)

                return

            }

            

            // 得到json数据中result字段对应的字典

            

            let resultDic = jsonDic.value(forKey: "result") as! NSArray

//            // 得到result字典中list数组

//            let listArr = resultDic.value(forKey: "list") as! NSArray

            // Model封装

            var modelArr:[gfd] = []

            for item in resultDic {

                let itemDic = item as! NSDictionary

                let one = gfd()

                

                

                one.province = (itemDic.value(forKey: "province") as! String)

                one.content = (itemDic.value(forKey: "content") as! String)

                

                

                modelArr.append(one)

            }

            print(modelArr)

            pass(modelArr,true)

        }.resume()

        

    }

   

}

===========================================GfdViewController==============================

 

 

import UIKit

 

let scrWidth = UIScreen.main.bounds.size.width

let scrHeight = UIScreen.main.bounds.size.height

 

 

class GfdViewController: UIViewController,UITextFieldDelegate {

 

    var recipeTF:UITextField?   // 菜谱输入框

    var searchBtn:UIButton// 搜索按钮

    

    override func viewDidLoad() {

        super.viewDidLoad()

 

        self.view.backgroundColor = UIColor.yellow

        recipeTF = UITextField(frame: CGRect.init(x: 0, y: 0, width: 200, height: 50))

        recipeTF?.center = CGPoint(x: scrWidth / 2, y: 200)

        recipeTF?.borderStyle = .line

        recipeTF?.placeholder = "请输入查询"

        

        recipeTF?.textColor = UIColor.blue

        recipeTF?.textAlignment = .center

        recipeTF?.clearButtonMode = .whileEditing

        recipeTF?.keyboardType = .namePhonePad

        recipeTF?.delegate = self

        self.view.addSubview(recipeTF!)

        

        

        searchBtn = UIButton(frame: CGRect(x: 0, y: 0, width: 100, height: 50))

        searchBtn?.center = CGPoint(x: scrWidth / 2, y: 300)

        searchBtn?.setTitle("点击查询", for: .normal)

        searchBtn?.backgroundColor = UIColor.black

        searchBtn?.setTitleColor(UIColor.white, for: .normal)

        searchBtn?.addTarget(self, action: #selector(btnDidPress(sender:)), for: .touchUpInside)

        self.view.addSubview(searchBtn!)

        

        // Do any additional setup after loading the view.

    }

 

    @objc func btnDidPress(sender:UIButton) -> Void {

        

        if (recipeTF?.text?.isEmpty)! {

           

            return

        }

        // 实例化控制器对象

        let resultVC = GfdResultViewController()

        // 传递数据

        resultVC.passString = (recipeTF?.text)!

        // 控制器跳转

        self.navigationController?.pushViewController(resultVC, animated: true)

        

        

        

        

        

    }

    

    override func didReceiveMemoryWarning() {

        super.didReceiveMemoryWarning()

        // Dispose of any resources that can be recreated.

    }

    

 

}

==========================================GfdResultViewController =======================

 

 

 

import UIKit

 

class GfdResultViewController: UIViewController,UITableViewDelegate,UITableViewDataSource {

   

 

    var passString:String = ""

 

    var tableData:[gfd]?

    var table:UITableView?

    

    override func viewDidLoad() {

        super.viewDidLoad()

        // 实例化表格视图

        table = UITableView.init(frame: self.view.frame, style: .plain)

        table?.dataSource  = self

        table?.delegate = self

        table?.rowHeight = 100

        self.view.addSubview(table!)

        

        

        self.view.backgroundColor = UIColor.white

        self.navigationItem.title = "\"\(passString)\"的搜索结果"        // Do any additional setup after loading the view.

    }

    

    

    override func viewWillAppear(_ animated: Bool) {

        // 请求网络数据

        let urlSer = URLService()

        urlSer.POST(url: self.passString) { (data, success) in

            if !success {

                return

            }

            self.tableData = data as? [gfd]

            DispatchQueue.main.async {

                self.table?.reloadData()

            }

        }

        

    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        if let count = tableData?.count {

            return count

        }

        return 0

    }

    

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let identifier = "cell"

        var cell = tableView.dequeueReusableCell(withIdentifier: identifier)

        if cell == nil {

            cell = UITableViewCell.init(style: .subtitle, reuseIdentifier: identifier)

        }

        

        let one = self.tableData![indexPath.row] as? gfd

        cell?.textLabel?.text = one?.province

        cell?.detailTextLabel?.text = one?.content

        

        return cell!

    }

    

    override func didReceiveMemoryWarning() {

        super.didReceiveMemoryWarning()

        // Dispose of any resources that can be recreated.

    }

    

 

   

}

============================gfd==========================

 

 

 

import UIKit

 

class gfd: NSObject {

    var province:String?

    var content:String?

    

}

 

 

 

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值