swift 获取网络接口数据 (今日新闻)newstoday

2019-03-07  本文已影响0人  财奴

AppDelegate.swift--------------------------------------------------

import UIKit

importCoreData

@UIApplicationMain

class AppDelegate: UIResponder, UIApplicationDelegate {

    varwindow:UIWindow?

    funcapplication(_application:UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey:Any]?) ->Bool{

        //新闻

        letnewsVC =NewsViewController()

        letnewsNav =UINavigationController.init(rootViewController: newsVC)

        newsVC.navigationItem.title = "今日头条"

        //收藏

        letcollectVC =CollectViewController()

        letcollectNav =UINavigationController.init(rootViewController:collectVC )

        collectVC.navigationItem.title="我的收藏"

        //标签栏控制器

        lettabbar =UITabBarController()

        tabbar.viewControllers= [newsNav,collectNav]

        newsNav.tabBarItem.title="新闻"

        collectNav.tabBarItem.title="收藏"

        //窗口根视图控制器

        self.window?.rootViewController= tabbar

        return true

    }

UIViewExtension.swift----------------------------------------------

importFoundation

import UIKit

extension UIView{

    funcshowMBAlert(msg:String) ->Void{

        //实例化

        lethud = MBProgressHUD.init(view:self)

        //设置为文本样式

        hud?.mode = MBProgressHUDModeText

        //设置隐藏时自动从父视图移除

        hud?.removeFromSuperViewOnHide =true

        //设置显示的文本

        hud?.labelText = msg

        //添加为view子视图

        self.addSubview(hud!)

        //显示

        hud?.show(true)

        //隐藏

        hud?.hide(true, afterDelay:2.0)

    }

}

NewsTableViewCell.swift--------------------------------------------

import UIKit

classNewsTableViewCell:UITableViewCell{

    //图片视图

    varimgView:UIImageView?

    //标题标签

    vartitleLable:UILabel?

    //时间标签

    vartimeLabel:UILabel?

    //作者标签

    varauthorLabel:UILabel?

    funcinitUI() {

        //图片视图

        self.imgView=UIImageView.init(frame:CGRect.init(x:5, y:5, width:50, height:50))

        //设置内容样式为fit样式

        self.imageView?.contentMode = .scaleAspectFit

        //加为cell的子视图

        self.contentView.addSubview(self.imgView!)

        //标题标签

        self.titleLable=UILabel.init(frame:CGRect.init(x:60, y:5, width:scrW-65, height:35))

        self.titleLable?.font=UIFont.systemFont(ofSize:18.0)

        self.contentView.addSubview(self.titleLable!)

        //时间标签

        self.timeLabel=UILabel.init(frame:CGRect.init(x:60, y:42, width:100, height:13))

        self.timeLabel?.font=UIFont.systemFont(ofSize:14.0)

        self.timeLabel?.textColor = UIColor.lightGray

        self.contentView.addSubview(self.timeLabel!)

        //作者标签

        self.authorLabel=UILabel.init(frame:CGRect.init(x:170, y:42, width:scrW-175, height:13))

        self.authorLabel?.font=UIFont.systemFont(ofSize:14.0)

        self.authorLabel?.textColor = UIColor.lightGray

        self.contentView.addSubview(self.authorLabel!)

    }

    overrideinit(style:UITableViewCell.CellStyle, reuseIdentifier:String?) {

      super.init(style: style, reuseIdentifier: reuseIdentifier)

        self.initUI()

    }

    requiredinit?(coder aDecoder:NSCoder) {

        fatalError("init(coder:) has not been implemented")

    }

    overridefuncawakeFromNib() {

        super.awakeFromNib()

        // Initialization code

    }

    overridefuncsetSelected(_selected:Bool, animated:Bool) {

        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state

    }

}

News.h---------------------------------------------------

#import

NS_ASSUME_NONNULL_BEGIN

@interface News : NSObject

@property(nonatomic,copy)NSString * uniquekey;

@property(nonatomic,copy)NSString * title;

@property(nonatomic,copy)NSString * date;

@property(nonatomic,copy)NSString * category;

@property(nonatomic,copy)NSString * author_name;

@property(nonatomic,copy)NSString * url;

@property(nonatomic,copy)NSString * thumbnail_pic_s;

@property(nonatomic,copy)NSString* thumbnail_pic_s02;

@property(nonatomic,copy)NSString* thumbnail_pic_s03;

//把得到的json数据中的data数组转化为News数组

+(NSArray * )createNewsArrWithDataArr:(NSArray*)dataArr;

@end

NS_ASSUME_NONNULL_END

News.m--------------------------------------------------

#import"News.h"

@implementation News

+(NSArray*)createNewsArrWithDataArr:(NSArray*)dataArr{

    //定义可变数组,用于储存News对象

    NSMutableArray * newsArr = [[NSMutableArray alloc]init];

    //遍历dataArr中的每个字典

    for(NSDictionary* dicindataArr){

        //将每个dic转换为News对象

        News* one = [[Newsalloc]init];

        //对one的属性赋值

        [onesetValuesForKeysWithDictionary:dic];

        //把每次循环生成的one对象加入到数组中

        [newsArraddObject:one];

    }

    //在循环外,将NewsArr返回

    return[newsArrcopy];

}

@end

NewsToday-Bridging-Header.h-----------------------------------------

#import"News.h"

#import "MJRefresh.h"

#import "MBProgressHUD.h"

#import "UIImageView+WebCache.h"

NewsViewController.swift-----------------------------------------------

import UIKit

///屏幕宽

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

///屏幕高

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

class NewsViewController: UIViewController,UITableViewDelegate,UITableViewDataSource {

    //MARK:---------------------------属性----------------------------

      //全局表格

    var tbv:UITableView?

    //表格数据

    vartbvData:[News]?

    //新闻标题

    let titlesShow = ["头条","社会","国内","国际","娱乐","体育","军事"]

    let titles = ["top","shehui","guonei","guoji","yule","tiyu","junshi"]

    //分段控件

    var titleSeg:UISegmentedControl?

    //下拉刷新控件

    var mjHeader:MJRefreshBaseView?

    //MARK:----------------------viewDidLoad-----------------------

    overridefuncviewDidLoad() {

        super.viewDidLoad()

        self.view.backgroundColor = UIColor.white

        //实例化分段控件

        self.titleSeg = UISegmentedControl.init(items: titlesShow)

        self.titleSeg?.frame=CGRect.init(x:0, y:64, width:scrW, height:40)

        self.titleSeg?.selectedSegmentIndex = 0

        self.titleSeg?.addTarget(self, action:#selector(titleSegDidChanged(seg:)), for:UIControl.Event.valueChanged)

        self.titleSeg?.tintColor = UIColor.black

        self.view.addSubview(self.titleSeg!)

        //自动获取第一个标题的新闻数据

        self.getURLData(title:titles[0])

        //实例化表格

       self.tbv=UITableView.init(frame:CGRect.init(x:0, y:64+40, width:scrW, height:scrH-64-40), style: .plain)

        self.tbv?.delegate=self

        self.tbv?.dataSource=self

        self.tbv?.rowHeight=60

        self.view.addSubview(self.tbv!)

        //实例化下拉刷新控件

        self.mjHeader = MJRefreshHeaderView.init(scrollView:self.tbv!)

        self.mjHeader?.beginRefreshingBlock = {headViewin

            self.getURLData(title:self.titles[(self.titleSeg!.selectedSegmentIndex)])

        }

    }

    //MARK:----------------UI控件的触发方法----------------

    //分段控制器的触发方法

    @objcfunctitleSegDidChanged(seg:UISegmentedControl) ->Void{

        //根据选中的分段下标获取对应的标题,获取网络数据

        self.getURLData(title:titles[seg.selectedSegmentIndex])

    }

    //MARK:--------------------代理方法和数据源的实现--------------

    functableView(_tableView:UITableView, numberOfRowsInSection section:Int) ->Int{

        ifletcount =self.tbvData?.count{

            returncount

        }

        return0

    }

    functableView(_tableView:UITableView, cellForRowAt indexPath:IndexPath) ->UITableViewCell{

        letidentifier ="newsCell"

        varcell = tableView.dequeueReusableCell(withIdentifier: identifier)as?NewsTableViewCell

        ifcell ==nil{

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

        }

        //根据行下标获取对应的News对象

        if  letoneNew =self.tbvData?[indexPath.row]{

            //图片

            cell?.imgView?.sd_setImage(with:URL.init(string: oneNew.thumbnail_pic_s))

            //标题

            cell?.titleLable?.text = oneNew.title

            //时间

            cell?.timeLabel?.text ="时间:\(oneNew.date)"

            //作者

            cell?.textLabel?.text ="作者:\(oneNew.author_name)"

        }

        returncell!

    }

    //MARK:-----------------获取网络数据的方法-------------------

    funcgetURLData(title:String) ->Void{

        //转动菊花等待指示器

        UIApplication.shared.isNetworkActivityIndicatorVisible = true

        //-------------------获取网络数据----------------

        //将请求网址字符串做成URL对象

        let url = URL.init(string: "http://v.juhe.cn/toutiao/index")

        //创建请求对象,同时设置缓存策略策略及超时时长

        varreq =URLRequest.init(url: url!, cachePolicy: .reloadRevalidatingCacheData, timeoutInterval:8.0)

        //设置POST请求

        req.httpMethod="POST"

        //把请求参数拼成字符串

        let appKey = "67968aeebf1f4e3b6170f7217b6f3cdb"

        letparamStr ="key=\(appKey)&type=\(title)"

        //将参数字符串转换为二进制Data数据

        letparamData = paramStr.data(using: .utf8)

        //将参数二进制数据放入请求体中

        req.httpBody= paramData

        //正式请求网络数据,使用URLSession

        lettask =URLSession.shared.dataTask(with: req) { (data, response, error)in

            //回到UI主线程停止转动指示器

            DispatchQueue.main.async {

                UIApplication.shared.isNetworkActivityIndicatorVisible = false

                self.mjHeader?.endRefreshing()

            }

            //如果服务器错误,给客户提示

            iferror  !=nil{

                DispatchQueue.main.async{

                    self.view.showMBAlert(msg:"服务器错误")

                }

                return

            }

            //如果没有错误,把得到的二进制数据转换为swift数组或字典数据,allowFragments表示使用一个不可变容器来存储

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

            //如果jsonData为nil表示转换失败,后天提供的json数据是错误的,你要及时和后台开发人员去反应

            guardletrightJsonData = jsonDataelse{

                DispatchQueue.main.async{

                    self.view.showMBAlert(msg:"网络数据错误")

                }

                return

            }

            //json数据解析,先获取error_code字段的值

            letjsonDataDic = rightJsonDataas!NSDictionary

            leterror_code = jsonDataDic["error_code"]as!Int

            //如果值不是0 ,表示错误,把reason获取展示给用户

            iferror_code !=0{

                letreason = jsonDataDic["reason"]as!String

                DispatchQueue.main.async{

                    self.view.showMBAlert(msg: reason)

                }

                return

            }

            //如果是0,把result字典中的data数据取出

            letresultDic = jsonDataDic["result"]as!NSDictionary

            letdataArr = resultDic["data"]  as!NSArray

            print(dataArr)

            //将dataArr转换为News数组,赋值给表格数据数组

            self.tbvData = News.createNewsArr(withDataArr: dataArras! [Any]) 

             //回到UI主线程,刷新表格

            DispatchQueue.main.async {

                self.tbv?.reloadData()

            }

        }

        task .resume()

    }

}

(开网----------------)

上一篇下一篇

猜你喜欢

热点阅读