(还需要创建桥接文件例:须写$(SRCROOT)/Swift -- 交通违章/Bridging-Header.h)
首先设置第一界面的视图
let SCR_W = UIScreen.main.bounds.size.width
let SCR_H = 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 VerbViewController: UIViewController,UITextFieldDelegate {
varverbTF:UITextField?
varsearchBtn:UIButton?
overridefuncviewDidLoad() {
super.viewDidLoad()
//设置视图背景色
self.view.backgroundColor = UIColor.groupTableViewBackground
verbTF=UITextField(frame:CGRect(x:0, y:0, width:200, height:50))
verbTF?.center=CGPoint(x:SCR_W/2, y:SCR_H/2-150)
verbTF?.borderStyle= .line
verbTF?.placeholder="请输入违章的城市"
verbTF?.textColor = UIColor.red
verbTF?.textAlignment= .center
verbTF?.delegate=self
self.view.addSubview(verbTF!)
searchBtn=UIButton(frame:CGRect(x:0, y:0, width:100, height:45))
searchBtn?.center=CGPoint(x:SCR_W/2, y:SCR_H/2-45)
searchBtn?.setTitle("点击查询", for: .normal)
searchBtn?.backgroundColor = UIColor.blue
searchBtn?.addTarget(self, action:#selector(searchBtnPress(sender:)), for: .touchUpInside)
self.view.addSubview(searchBtn!)
}
@objcfuncsearchBtnPress(sender:UIButton) {
if(verbTF?.text?.isEmpty)! {
self.showAlert(msg:"信息不可为空", sec:2.0)
return
}
//实例化控制器
let resultVC = VerbResultViewController()
//传递数据
resultVC.passString=verbTF?.text
//控制器跳转
self.navigationController?.pushViewController(resultVC, animated:true)
}
//点击return按钮触摸回调
functextFieldShouldReturn(_textField:UITextField) ->Bool{
//放弃第一响应
textField.resignFirstResponder()
return true
}
//触摸View回调
overridefunctouchesBegan(_touches:Set, with event:UIEvent?) {
super.touchesBegan(touches, with: event)
verbTF?.resignFirstResponder()
//将View及其子视图都放弃编辑
self.view.endEditing(true)
}
}
第二界面的视图设置
class VerbResultViewController: UIViewController,UITableViewDelegate,UITableViewDataSource {
varpassString:String? =""
vartableData:[Verb]?
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(style: .subtitle, reuseIdentifier: identifier)
}
letone =self.tableData![indexPath.row]as?Verb
cell?.textLabel?.text= one?.province
cell?.detailTextLabel?.text= one?.content
returncell!
}
vartable:UITableView?
overridefuncviewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.groupTableViewBackground
self.navigationItem.title = "\"\(passString!)\"搜索的结果"
table=UITableView(frame:CGRect(x:0, y:0, width:SCR_W, height:SCR_H), style: .plain)
table?.delegate=self
table?.dataSource=self
table?.rowHeight=65
self.view.addSubview(table!)
}
overridefuncviewWillAppear(_animated:Bool) {
leturlSer =URLService()
urlSer.searchVarbs(search:self.passString!, vc:self) { (data, success)in
if!success {
return
}
self.tableData= dataas? [Verb]
DispatchQueue.main.async {
self.table?.reloadData()
}
}
}
}
model封装网络请求
classURLService:NSObject{
//请求搜索的数据
funcsearchVarbs(search:String,vc:UIViewController,compleiton:@escaping(Any,Bool)->Void) {
//判断是否有网络连接
if Reachability.forLocalWiFi().currentReachabilityStatus() == NotReachable && Reachability.forInternetConnection().currentReachabilityStatus() == NotReachable {
vc.showAlert(msg:"网络错误", sec:2.0)
compleiton("error",false)
return
}
//状态栏菊花开始转动
UIApplication.shared.isNetworkActivityIndicatorVisible = true
//网址字符串封装
let url = URL.init(string: "http://api.jisuapi.com/illegaladdr/city")
//创建请求对象
varreq =URLRequest.init(url: url!, cachePolicy: .reloadIgnoringLocalAndRemoteCacheData, timeoutInterval:15.0)
//设置请求方式POST
req.httpMethod="POST"
//将所有参数拼接成一个字符串
let str = "city=\(search)&num=40&appkey=de394933e1a3e2db"
//设置请求对象的请求体
req.httpBody= str.data(using: .utf8)
//回话对象请求服务器数据
URLSession.shared.dataTask(with: req) { (data, response, error)in
//停止菊花
DispatchQueue.main.async {
UIApplication.shared.isNetworkActivityIndicatorVisible = false
}
//如果服务器连接失败
iferror !=nil{
DispatchQueue.main.async{
vc.showAlert(msg:"服务器连接失败", sec:2.0)
}
return
}
//json解析
letjsonData =try?JSONSerialization.jsonObject(with: data!, options: .allowFragments)
ifjsonData ==nil{
DispatchQueue.main.async{
vc.showAlert(msg:"网络数据错误", sec:2.0)
}
return
}
//如果正确,将解析的json数据回传给Controller
letjsonDic = jsonDataas!NSDictionary
letstatus = jsonDic.value(forKey:"status")as!NSString
letmsg = jsonDic.value(forKey:"msg")as!String
ifstatus.intValue!=0{
DispatchQueue.main.async{
vc.showAlert(msg: msg, sec:2.0)
}
return
}
letresultArr = jsonDic.value(forKey:"result")as!NSArray
//model封装
varmodelArr:[Verb] = []
//遍历数组中的每一个字典
foriteminresultArr {
letitemDic = itemas!NSDictionary
letone =Verb()
one.province= itemDic.value(forKey:"province")as?String
one.content= itemDic.value(forKey:"content")as?String
modelArr.append(one)
}
compleiton(modelArr,true)
}.resume()
}
}
model类中添加属性
varprovince:String?
varcity:String?
vartown:String?
varaddress:String?
varcontent:String?
varnum:String?
varlat:String?
varlng:String?