NewsViewController 页面
import UIKit
let scrWidth = UIScreen.main.bounds.size.width // 宽度
let scrHeight = UIScreen.main.bounds.size.height // 高度
// 给UIViewController 类添加扩展
extension UIViewController {
funcshowAlert(msg:String,sec:TimeInterval) {
// 实例化弹出控制器
letalertVC =UIAlertController(title:nil, message: msg, preferredStyle: .alert)
// 从vc 控制器弹出提示控制器
self.present(alertVC, animated:true, completion:nil)
// 延时执行隐藏操作
self.perform(#selector(hideAlertVC(sender:)), with: alertVC, afterDelay: sec)
}
@objcfunchideAlertVC(sender:UIAlertController) {
sender.dismiss(animated:true, completion:nil)
}
}
class NewsViewController: UIViewController,UITextFieldDelegate {
varnewsTF:UITextField? // 菜谱输入框
varsearchBtn:UIButton? // 搜索按钮
overridefuncviewDidLoad() {
super.viewDidLoad()
// 设置背景颜色
self.view.backgroundColor = UIColor.white
newsTF=UITextField(frame:CGRect(x:0, y:0, width:200, height:50))
newsTF?.center=CGPoint(x:scrWidth/2, y:200)
newsTF?.borderStyle= .line
newsTF?.placeholder="请输入查询的新闻"
newsTF?.textColor = UIColor.blue
newsTF?.textAlignment= .center
newsTF?.clearButtonMode = .whileEditing
newsTF?.delegate=self
self.view.addSubview(newsTF!)
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.yellow
searchBtn?.setTitleColor(UIColor.black, for: .normal)
searchBtn?.addTarget(self, action:#selector(btnDidPress(sender:)), for: .touchUpInside)
self.view.addSubview(searchBtn!)
}
@objcfuncbtnDidPress(sender:UIButton) {
if(newsTF?.text?.isEmpty)! {
self.showAlert(msg:"信息不可为空", sec:2.5)
return
}
// 实例化控制器对象
let resultVC = NewsResultViewController()
// 传递数据
resultVC.passString=newsTF!.text!
self.navigationController?.pushViewController(resultVC, animated:true)
}
// MARK -----------UITextFiledDelegate -------
// 点击return 隐藏键盘
functextFieldShouldReturn(_textField:UITextField) ->Bool{
// 放弃第一响应这
textField.resignFirstResponder()
return true
}
// ------ touches Method ------
overridefunctouchesEnded(_touches:Set, with event:UIEvent?) {
super.touchesEnded(touches, with: event)
newsTF?.resignFirstResponder()
self.view.endEditing(true)
}
}
NewsResultViewController 页面
import UIKit
class NewsResultViewController: UIViewController,UITableViewDataSource,UITableViewDelegate {
vartable:UITableView?
vartableData:[News]?
varpassString:String=""
overridefuncviewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.white
self.navigationItem.title = "\"\(passString)\"的搜索结果"
table=UITableView(frame:CGRect(x:0, y:0, width:scrWidth, height:scrHeight),style: .plain)
table?.rowHeight=260.0
table?.delegate=self
table?.dataSource=self
self.view.addSubview(table!)
}
overridefuncviewWillAppear(_animated:Bool) {
// 请求网络数据
leturlSer =URLService()
urlSer.getNewsBySearch(search:self.passString, vc:self) { (data, success)in
if!success {
return
}
print(data)
self.tableData= dataas? [News]
DispatchQueue.main.async {
self.table?.reloadData()
}
}
}
functableView(_tableView:UITableView, numberOfRowsInSection section:Int) ->Int{
ifletcount =tableData?.count{
returncount
}
return0
}
functableView(_tableView:UITableView, cellForRowAt indexPath:IndexPath) ->UITableViewCell{
letidentifier ="cell"
varcell = tableView.dequeueReusableCell(withIdentifier: identifier)
ifcell ==nil{
cell =UITableViewCell.init(style: .value1, reuseIdentifier: identifier)
letlab =UILabel(frame:CGRect(x:0, y:0, width:scrWidth, height:30))
cell?.addSubview(lab)
letlab2 =UILabel(frame:CGRect(x:0, y:40, width:scrWidth, height:30))
cell?.addSubview(lab2)
letlab3 =UILabel(frame:CGRect(x:0, y:80, width:scrWidth, height:80))
lab3.numberOfLines=2
cell?.addSubview(lab3)
letone =self.tableData![indexPath.row]as?News
lab.text= one?.city
lab2.text= one?.address
lab3.text= one?.content
}
returncell!
}
}
Model类:
创建一些属性:比如
import UIKit
classNews:NSObject{
varprovince:String?
vartown:String?
varcity:String?
varaddress:String?
varnum:Int?
varcontent:String?
}
URLSeivice类:
import UIKit
classURLService:NSObject{
// 请求搜索的数据
funcgetNewsBySearch(search:String,vc:UIViewController,completion:@escaping(Any,Bool) ->Void) {
// 判断无网状态
if Reachability.forLocalWiFi().currentReachabilityStatus() == NotReachable && Reachability.forInternetConnection().currentReachabilityStatus() == NotReachable {
vc.showAlert(msg:"网络错误,请检查网络", sec:2.5)
completion("error",false)
return
}
// (2) 状态栏中的菊花开始转
UIApplication.shared.isNetworkActivityIndicatorVisible = true
// (3) 网址字符串封装
let url = URL.init(string: "http://api.jisuapi.com/illegaladdr/city")
// 创建请求对象
varreq =URLRequest.init(url: url!, cachePolicy: .reloadIgnoringCacheData, timeoutInterval:15.0)
// 设置请求方式为POST
req.httpMethod="POST"
// 将所有的参数拼接成一个字符串
let str = "city=\(search)&num=10&appkey=de394933e1a3e2db"
// 设置请求对象的请求体
req.httpBody= str.data(using: .utf8)
//(5) 会话对象请求网络数据
URLSession.shared.dataTask(with: req) { (data:Data?, success:URLResponse?, error:Error?)in
// 回到UI主线程停止菊花
DispatchQueue.main.async {
UIApplication.shared.isNetworkActivityIndicatorVisible = false
}
// 如果服务器连接失败
iferror != nil{
DispatchQueue.main.async{
vc.showAlert(msg:"服务器连接失败", sec:2.5)
}
return
}
// JSON解析
letjsonData =try?JSONSerialization.jsonObject(with: data!, options: .allowFragments)
ifjsonData ==nil{
DispatchQueue.main.async{
vc.showAlert(msg:"网络数据错误", sec:2.5)
}
return
}
// 如果正确将json解析数据回传个controller
letjsonDic = jsonDataas!NSDictionary
letstatus = jsonDic.value(forKeyPath:"status")as!NSString
letmsg = jsonDic.value(forKeyPath:"msg")as!String
ifstatus.intValue!=0{
DispatchQueue.main.async{
vc.showAlert(msg: msg, sec:2.5)
}
return
}
// 得到json数据中result字段对应的字典
letresultDic = jsonDic.value(forKeyPath:"result")as!NSArray
// Model封装
varmodelArr:[News] = []
// 遍历数组中的每个字典
foriteminresultDic {
letitemDic = itemas!NSDictionary
letone =News()
one.province= itemDic.value(forKey:"province")as?String
one.city= itemDic.value(forKey:"city")as?String
one.town= itemDic.value(forKey:"town")as?String
one.address= itemDic.value(forKey:"address")as?String
one.num= itemDic.value(forKey:"num")as?Int
one.content= itemDic.value(forKey:"content")as?String
modelArr.append(one)
}
completion(modelArr,true)
}.resume()
}
}