swift 獲取網絡接口數據 (今日新聞)newstoday

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];


? ? ? ? //把每次循環(huán)生成的one對象加入到數組中

? ? ? ? [newsArraddObject:one];


? ? }

? ? //在循環(huán)外,將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控件的觸發(fā)方法----------------

? ? //分段控制器的觸發(fā)方法

? ? @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")


? ? ? ? //創(chuàng)建請求對象,同時設置緩存策略策略及超時時長

? ? ? ? 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數據是錯誤的,你要及時和后臺開發(fā)人員去反應

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

? ? }

}

(開網----------------)

?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容