Swift网络接口笔记
主控制器中:
//屏幕的宽
var scrW = UIScreen.main.bounds.size.width
//屏幕的高
var scrH = UIScreen.main.bounds.size.height
class OneViewController: BaseViewController,UITableViewDelegate,UITableViewDataSource {
//MARK:--------------------属性的声明------------------
var tbv:UITableView?
var tbvData:[Student]?
var segment:UISegmentedControl?
var titles = ["推荐新闻","实时对话","行情分析","专栏"]
var onetitle = ["1","2","3","4"]
//下拉刷新控件
var mjHeader:MJRefreshHeaderView?
//MARK:--------------------UI创建------------------
func initUI() {
//创建segment分段控制器
self.segment = UISegmentedControl.init(items: titles)
//设置位置
self.segment?.frame=CGRect.init(x:0, y:0, width:scrW, height:40)
//设置默认选中的下标
self.segment?.selectedSegmentIndex = 0
//自动获取第一个标题的新闻数据
self.getURLData(titleIndex:onetitle[0])
//设置触发方法
self.segment?.addTarget(self, action:#selector(segmentDidChange(seg:)), for: .valueChanged)
self.segment?.tintColor = UIColor.black
//添加到view子视图
self.view.addSubview(self.segment!)
//实例化表格
self.tbv=UITableView.init(frame:CGRect.init(x:0, y:40, width:scrW, height:scrH-40), style: .plain)
//设置代理和数据源
self.tbv?.delegate=self
self.tbv?.dataSource=self
//添加到子视图
self.view.addSubview(self.tbv!)
//实例化下拉刷新的控件
self.mjHeader = MJRefreshHeaderView.init(scrollView: self.tbv!)
//设置刷新的回调的闭包
self.mjHeader?.beginRefreshingBlock = {refreshView in
self.getURLData(titleIndex:self.onetitle[(self.segment!.selectedSegmentIndex)])
}
self.tbv?.rowHeight=150
}
//MARK:--------------------UI控件的触发方法------------------
@objc func segmentDidChange(seg:UISegmentedControl) ->Void{
//根据选中的分段下标获取对应的标题,获取网络数据
self.getURLData(titleIndex:titles[seg.selectedSegmentIndex])
}
//MARK:-------------------viewDidLoad-------------------
override func viewDidLoad() {
super.viewDidLoad()
self.initUI()
}
//MARK:------------------代理和数据源的实现的方法-------------------
func tableView(_ tableView:UITableView, numberOfRowsInSection section:Int) ->Int{
if let count = self.tbvData?.count{
return count
}
return 0
}
func tableView(_ tableView:UITableView, cellForRowAt indexPath:IndexPath) ->UITableViewCell{
//定义一个标识符
let identifier = "Mycell"
var cell = tableView.dequeueReusableCell(withIdentifier: identifier) as? StudentTableViewCell
if cell == nil{
cell = StudentTableViewCell.init(style: .subtitle, reuseIdentifier: identifier)
}
if let oneNew = self.tbvData?[indexPath.row]{
//图片
cell?.imgview?.sd_setImage(with:URL.init(string: oneNew.img), completed:nil)
//标题
cell?.titleLabel?.text = oneNew.title
//作者
cell?.author?.text="作者\(oneNew.author)"
//阅读量
cell?.readNum?.text="阅读量:\(oneNew.read_num)"
}
return cell!
}
//MARK:--------------------获取网络请求数据------------------
func getURLData(titleIndex:String) -> Void{
//转动指示器
UIApplication.shared.isNetworkActivityIndicatorVisible = true
//网络请求,网址字符串拼接
let url = URL.init(string: "http://buluokes.huimor.com/api")
//创建请求对象,同时设置缓存策略及超时时长
var req = URLRequest.init(url: url!, cachePolicy: .reloadRevalidatingCacheData, timeoutInterval:5.0)
//设置POST请求
req.httpMethod="POST"
//把请求参数拼接成字符串
let paramStr = "method=app.news.getarticlelist&class_id\(titleIndex)&page=1&user_token="
//将参数字符串转换为二进制Data数据
let paramData = paramStr.data(using: .utf8)
//将参数二进制数据放入请求体中
req.httpBody = paramData
//正式请求网络数据,使用URLsession
let task = URLSession.shared.dataTask(with: req) { (data, response, error) in
//回到UI主线程停止转动指示器
DispatchQueue.main.async {
UIApplication.shared.isNetworkActivityIndicatorVisible = false
self.mjHeader?.endRefreshing()
}
//如果服务器错误,给客户提示
if error != nil{
DispatchQueue.main.async{
self.view.showMBAlert(msg:"服务器错误")
}
return
}
//如果连接成功,将二进制数据转换为数组或字典
let jsonData = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments)
//如果转换失败
if jsonData == nil{
DispatchQueue.main.async{
self.view.showMBAlert(msg:"json数据解析错误")
}
return
}
//t如果转换成功,将数据转换为字典类型
let jsonDic = jsonData as! NSDictionary
//获取code值
let oneCode = jsonDic["code"] as! Int
//如果code的值不为200 ,表示有错误发生,给出用户提示
if oneCode != 200{
DispatchQueue.main.async{
self.view.showMBAlert(msg:"code值不是200")
}
return
}
//如果数据都正确,做JSON解析
let resultDic = jsonDic["data"] as! NSDictionary
let dataArr = resultDic["list"] as! NSArray
print(dataArr)
//将dataArr转换为News数组,赋值给表格数据数组
self.tbvData = Student.createNewsArr(withDataArr: dataArr as! [Any])
//刷新表格
DispatchQueue.main.async {
self.tbv?.reloadData()
}
}
task.resume()
}
}
扩展中:
import UIKit
extension UIView {
//显示MB提示框
func showMBAlert(msg:String) ->Void{
//实例化MB
let alert = MBProgressHUD.init(view:self)
//设置提示为文本样式
alert?.mode = MBProgressHUDModeText
//设置隐藏时自动从父视图移除
alert?.removeFromSuperViewOnHide = true
//设置显示的提示文本
alert?.labelText = msg
//添加为子视图
self.addSubview(alert!)
//显示提示框
alert?.show(true)
//设置几秒自动隐藏
alert?.hide(true, afterDelay:3.0)
}
}
模型中:
@property(nonatomic,strong)NSString * type;
@property(nonatomic,strong)NSString * id;
@property(nonatomic,strong)NSString * img;
@property(nonatomic,strong)NSString * title;
@property(nonatomic,strong)NSString * read_num;
@property(nonatomic,strong)NSString * content;
@property(nonatomic,strong)NSString * author;
@property(nonatomic,strong)NSString * create_time;
//把得到的json数据中的data数组转换为Student数组
+(NSArray<Student *>*)createNewsArrWithDataArr:(NSArray*)dataArr;
+(NSArray<Student *>*)createNewsArrWithDataArr:(NSArray *)dataArr{
//定义可变数组,用于储存Student对象
NSMutableArray * newsArr = [[NSMutableArray alloc]init];
//遍历dataArr中的每个字典
for(NSDictionary* dic in dataArr){
//将每个dic转化为Student对象
Student* one = [[Student alloc]init];
//对one的属性赋值
[one setValuesForKeysWithDictionary:dic];
//把每次循环生成的one对象加入到数组中
[newsArr addObject:one];
}
//在循环外,将newsArr返回
return[newsArr copy];
}
自定义cell中:
import UIKit
class StudentTableViewCell:UITableViewCell{
//图片视图
var imgview:UIImageView?
//标题标签
var titleLabel:UILabel?
//作者标签
var author:UILabel?
//阅读量
var readNum:UILabel?
func initUI() {
//图片
self.imgview=UIImageView.init(frame:CGRect.init(x:5, y:5, width:140, height:140))
self.contentView.addSubview(self.imgview!)
//标题
self.titleLabel=UILabel.init(frame:CGRect.init(x:145, y:5, width:scrW-155, height:80))
self.titleLabel?.font=UIFont.systemFont(ofSize:20.0)
self.titleLabel?.numberOfLines=3
self.contentView.addSubview(self.titleLabel!)
//作者标签
self.author=UILabel.init(frame:CGRect.init(x:145, y:100, width:150, height:40))
self.author?.font=UIFont.systemFont(ofSize:17.0)
self.author?.textColor = UIColor.gray
self.contentView.addSubview(self.author!)
//阅读量
self.readNum=UILabel.init(frame:CGRect.init(x:300, y:100, width:150, height:40))
self.readNum?.font=UIFont.systemFont(ofSize:17.0)
self.readNum?.textColor = UIColor.gray
self.contentView.addSubview(self.readNum!)
}
override init(style:UITableViewCell.CellStyle, reuseIdentifier:String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
self.initUI()
}
required init?(coder aDecoder:NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected:Bool, animated:Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}