Json解析与数据请求

AppDelegate.swift

import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

var window: UIWindow?


func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    // Override point for customization after application launch.
    
    let newsVC = DetailViewController()
    let newNav = UINavigationController.init(rootViewController: newsVC)
    newsVC.navigationItem.title = "今日头条"
    
    let collectVC = TowViewController()
    let collectNav = UINavigationController.init(rootViewController: collectVC)
    collectVC.navigationItem.title = "今日头条"
    
    let tabar = UITabBarController()
    tabar.viewControllers = [newNav,collectNav]
    
    newNav.tabBarItem.title = "今日头条"

    collectNav.tabBarItem.title = "今日头条"

    self.window?.rootViewController = tabar
    
    
    return true
}

ViewController.swift

NewsTableViewCell.swift

import UIKit

class NewsTableViewCell: UITableViewCell {

// 图片视图
var imView:UIImageView?

// 标签视图
var titleLable:UILabel?

var timeLabel:UILabel?

var autrdLabel:UILabel?

func initUI() {
    // 图片
    self.imView = UIImageView.init(frame: CGRect.init(x: 5, y: 5, width: 30, height: 30))
    self.imView?.contentMode = .scaleAspectFit
    
    // 加为cell的子视图
    self.contentView.addSubview(self.imView!)
    
    self.titleLable = UILabel.init(frame: CGRect.init(x: 60, y: 5, width: scrW - 65, height: 35))
    
    self.titleLable?.numberOfLines = 2
    
    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.contentView.addSubview(self.timeLabel!)
    
    self.autrdLabel = UILabel.init(frame: CGRect.init(x: 170, y: 42, width: scrW - 175 , height: 13))
    
    self.autrdLabel?.font  = UIFont.systemFont(ofSize: 14.0)
    
    self.contentView.addSubview(self.autrdLabel!)

}

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()
    
}

override func setSelected(_ selected: Bool, animated: Bool) {
    super.setSelected(selected, animated: animated)

}

}

DetailViewController.swift

import UIKit

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

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

class DetailViewController: UIViewController,UITableViewDelegate,UITableViewDataSource {

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    if let count = self.tableData?.count{
        return count
    }
    return 0
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    
    let cellID = "Newscell"
    
    var cell = tableView.dequeueReusableCell(withIdentifier: cellID) as? NewsTableViewCell
    if cell == nil
    {
        cell = NewsTableViewCell.init(style: .subtitle, reuseIdentifier: cellID)
    }
    
    // 根据行下标获取对应得Model对象
    if let oneNew = self.tableData?[indexPath.row]
    {

// cell?.textLabel?.text = oneNew.title
// cell?.textLabel?.numberOfLines = 0
// cell?.detailTextLabel?.text = oneNew.date
// cell?.imageView?.sd_setImage(with: URL.init(string: oneNew.thumbnail_pic_s))

        cell?.imageView?.sd_setImage(with: URL.init(string: oneNew.thumbnail_pic_s))
        
        cell?.textLabel?.text = oneNew.title
        
        cell?.timeLabel?.text  = "时间:\(oneNew.date)"
        
        cell?.autrdLabel?.text = "作者:\(oneNew.author_name)"
        
        
        
    }
    
    return cell!
}



// MARK: ------------- 属性 ----------
// 表格
var tabel:UITableView?

// 表格数据
var tableData:[Modl]?

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


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

// 分段控件
var titleSeg:UISegmentedControl?

// 下拉
var mjHeader:MJRefreshHeaderView?

override func viewDidLoad() {
    super.viewDidLoad()

    // Do any additional setup after loading the view.
    
    //
    self.view.backgroundColor = .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(titlesSegDid(seg:)), for: .valueChanged)
    
    
    
    self.view.addSubview(self.titleSeg!)
    
    self.tabel = UITableView.init(frame: CGRect.init(x: 0, y: 64 + 40, width: scrW, height: scrH - 64 - 40), style: .plain)
    self.tabel?.dataSource = self
    self.tabel?.delegate = self
    self.view.addSubview(self.tabel!)
    
    
    // 实例化下拉控件
    self.mjHeader = MJRefreshHeaderView.init(scrollView: self.tabel!)
    self.mjHeader?.beginRefreshingBlock = {
        headView in
        self.getURLData(title: self.titles[self.titleSeg!.selectedSegmentIndex])
    }
    
    self.getURLData(title: titles[0])
}

// 获取网络数据
func getURLData(title:String) -> Void {
    
    // 让菊花转起来
    UIApplication.shared.isNetworkActivityIndicatorVisible = true
    
    // 获取网络数据
    // 将j请求网站字符串做成URL对象
    let  url = URL.init(string: "http://v.juhe.cn/toutiao/index")
    
    // 创建请求对象
    var req = URLRequest.init(url: url!, cachePolicy: .reloadIgnoringLocalAndRemoteCacheData, timeoutInterval: 5.0)
    
    // 设置post请求
    req.httpMethod = "POST"
    
    
    let appKey = "67968aeebf1f4e3b6170f7217b6f3cdb"
    
    // 把请求参数拼成一个字符串
    let paramStr = "key=\(appKey)&type=\(title)"
    // 将参数字符串转换Data数据
    let paramData = paramStr.data(using: .utf8)
    
    req.httpBody = paramData
    
    // 使用URL
    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
        }
        
        // 如果没有错误,吧得到的二进制数据转换为swift数组或字典数据
        let jsonData = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments)
        // 如果jsondata为niln表示转换失败,后天提供的json数据是错误的
        guard let reightJsonData = jsonData else
        {
            DispatchQueue.main.async {
                self.view.showMBAlert(msg: "网络数据错误")
            }
            return
        }
        // JSON解析 获取error_code字段的值
        let jsonDataDic = reightJsonData as! NSDictionary
        let error_code = jsonDataDic["error_code"] as! Int
        
        // 如果值不是零 表示错误 把reason展示给用户
        if error_code != 0
        {
            let reason = jsonDataDic["reason"]as! String
            DispatchQueue.main.async {
                self.view.showMBAlert(msg: reason)
            }
            return
        }
        
        // 如果为0的话 把result字典中的data数组取出
        let resultDic = jsonDataDic["result"] as! NSDictionary
        let dataArr = resultDic["data"] as! NSArray
        
        self.tableData = Modl.creataNewsArr(withDataArr: dataArr as! [Any])
        
        DispatchQueue.main.async {
            self.tabel?.reloadData()
        }
        
    }
    
    task.resume()
    
}


@objc func titlesSegDid(seg:UISegmentedControl) -> Void {
    
    self.getURLData(title: titles[seg.selectedSegmentIndex])
}

TowViewController.swift

ThreeViewController.swift

Modl.h

#import <Foundation/Foundation.h>

NS_ASSUME_NONNULL_BEGIN

@interface Modl : 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<Modl*> *)creataNewsArrWithDataArr:(NSArray *)dataArr;

@end

NS_ASSUME_NONNULL_END

Modl.m

#import “Modl.h”

@implementation Modl
+(NSArray <Modl >)creataNewsArrWithDataArr:(NSArray *)dataArr
{
// 定义可变数组,用于储存News对象
NSMutableArray *newsArr = [[NSMutableArray alloc]init];

for (NSDictionary *dic in dataArr) {
    
    Modl *one = [[Modl alloc]init];
    
    [one setValuesForKeysWithDictionary:dic];
    // 把每次循环生成的one对象加入到数组中
    [newsArr addObject:one];
}
// 在循环外 将newsArr返回
return [newsArr copy];

}
@end

NewsToday-Bridging-Header.h

#import “Modl.h”
#import “MBProgressHUD.h”
#import “MJRefresh.h”
#import “UIImageView+WebCache.h”

UIviewExtension.swift

import Foundation

import UIKit

extension UIView{
func showMBAlert(msg:String) -> Void {
let hud = MBProgressHUD.init(view: self)

    hud?.mode = MBProgressHUDModeText
    
    hud?.removeFromSuperViewOnHide = true
    
    hud?.labelText = msg
    
    self.addSubview(hud!)
    
    hud?.show(true)
    
    hud?.hide(true, afterDelay: 2.0)
}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值