swift超級 獲取網(wǎng)絡接口展示(平遠)

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


importFoundation

import UIKit

extension UIView{

? ? //顯示MB提示框

? ? funcshowMBAlert(msg:String) ->Void{

? ? ? ? //實例化MB

? ? ? ? letalert = MBProgressHUD.init(view:self)


? ? ? ? //設置為文本提示樣式

? ? ? ? alert?.mode = MBProgressHUDModeText


? ? ? ? //設置隱藏時自動從父視圖移除

? ? ? ? alert?.removeFromSuperViewOnHide =true


? ? ? ? //設置顯示的提示文本

? ? ? ? alert?.labelText = msg


? ? ? ? //添加為子視圖

? ? ? ? self.addSubview(alert!)


? ? ? ? //顯示提示框

? ? ? ? alert?.show(true)


? ? ? ? //2.5秒后自動隱藏

? ? ? ? alert?.hide(true, afterDelay:2.5)

? ? }

}

News.swift----------------------------------------------


import UIKit

importFoundation

class News:NSObject {

?? varaccountid =""? ? //用戶

?? varcreateDate =0? ? //創(chuàng)建時間

?? varcreateName =""? ? //創(chuàng)建人名稱

?? varid =""? ? ? ? ? ? //新聞的ID

?? varstyle =""? ? ? ? //新聞的總分類

?? varstyle2 =""? ? ? ? //新聞的二級分類

?? vartitle =""? ? ? ? //標題

?? vartxturl =""? ? ? ? //詳情地址

?? varupdateName =""? ? //更新時間

?? varuploadimgurl =""? //圖片地址


? ? ///類方法,用于把一個字典數(shù)組轉(zhuǎn)換為News數(shù)組

? ? static? funccreateNewsArray(arr:[[String:Any]]) -> [News] {

? ? ? ? //創(chuàng)建一個可變的News數(shù)組

? ? ? ? varnewsArr:[News] = []

? ? ? ? fordicinarr{

? ? ? ? ? ? letone =News()


//? ? ? ? ? ? one.setValuesForKeys(dic)

? ? ? ? ? ? one.title= dic["title"]!as!String

? ? ? ? ? ? one.txturl= dic["txturl"]!as!String

? ? ? ? ? ? one.createDate= dic["createDate"]as!Int

? ? ? ? ? ? one.createName= dic["createName"]as!String

? ? ? ? ? ? one.uploadimgurl= dic["uploadimgurl"]as!String

? ? ? ? ? ? newsArr.append(one)

? ? ? ? }

? ? ? ? returnnewsArr

? ? }

? ? overridefuncsetValue(_value:Any?, forUndefinedKey key:String) {

? ? ? ? print("沒有定義的屬性\(key),值\(value)")

? ? }

}

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


import UIKit

classNewsTableViewCell:UITableViewCell{

? ? //MARK:------------------UI控件-----------------------

? ? varimgView:UIImageView?//圖片視圖

? ? vartitlelabel:UILabel?? //標題標簽

? ? vardateLabel:UILabel?? ? //時間標簽

? ? varauthorLable:UILabel?? //作者標簽


? ? //創(chuàng)建UI控件

? ? funcinitUI() {

? ? ? ? //圖片視圖

? ? ? ? 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:150, y:5, width:srcW-155, height:100))


? ? ? ? self.titlelabel?.font=UIFont.systemFont(ofSize:20.0)


? ? ? ? self.titlelabel?.numberOfLines=3


? ? ? ? self.contentView.addSubview(self.titlelabel!)



? ? ? ? //時間標簽

? ? ? ? self.dateLabel=UILabel.init(frame:CGRect.init(x:250, y:125, width:srcW-200, height:13))


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


? ? ? ? self.dateLabel?.textColor = UIColor.lightGray


? ? ? ? self.contentView.addSubview(self.dateLabel!)


? ? ? ? //作者標簽

? ? ? ? self.authorLable=UILabel.init(frame:CGRect.init(x:150, y:125, width:150, height:13))


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


? ? ? ? self.authorLable?.textColor = UIColor.lightGray


? ? ? ? self.contentView.addSubview(self.authorLable!)

? ? }


? ? //MARK:------------------init-----------------------

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

? ? }

}

BaseViewController.swift------------------------------------------


import UIKit

classBaseViewController:UIViewController{

? ? overridefuncviewDidLoad() {

? ? ? ? super.viewDidLoad()

?? ? ? self.view.backgroundColor = UIColor.white


?? ? ? ? self.navigationController?.navigationBar.titleTextAttributes = [NSAttributedString.Key.foregroundColor:UIColor.white,NSAttributedString.Key.font : UIFont.systemFont(ofSize: 20)]



? ? }

? ? overridefuncviewWillAppear(_animated:Bool) {

? ? ? ? super.viewWillAppear(animated)


? ? ? ? //如果該控制器對象是導航的根控制器,顯示標簽欄

? ? ? ? if self.navigationController?.viewControllers[0] == self{

? ? ? ? ? ? self.navigationController?.tabBarController?.tabBar.isHidden = false

? ? ? ? }

? ? ? ? else{

? ? ? ? ? ? //如果不是,隱藏標簽欄

? ? ? ? ? ? self.navigationController?.tabBarController?.tabBar.isHidden = true

? ? ? ? }

? ? }

}

DetailViewController.swift-------------------------------------------

import UIKit

importWebKit

classDetailViewController:BaseViewController{

? ? //定義接收傳遞過來的對象

?? ? varpassNews:News?


? ? //網(wǎng)頁視圖控件

? ? varwebView:WKWebView?

? ? overridefuncviewDidLoad() {

? ? ? ? super.viewDidLoad()

? ? ? self.webView=WKWebView.init(frame:CGRect.init(x:0, y:64, width:srcW, height:srcH-64))

? ? ? ? self.webView=WKWebView.init(frame:self.view.frame)


? ? ? ? self.view.addSubview(self.webView!)



? ? ? ? //

?? ? ? ifletnews =self.passNews{

? ? ? ? ? ? leturl =URL.init(string: news.txturl)

? ? ? ? ? ? letreq =URLRequest.init(url: url!)

? ? ? ? //用網(wǎng)頁視圖加載網(wǎng)頁

? ? ? ? self.webView?.load(req)

? ? ? ? }

?? ? ? else{

? ? ? ? self.view.showMBAlert(msg:"數(shù)據(jù)錯誤")

????????}

? ? }

}

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


import UIKit

var srcW = UIScreen.main.bounds.size.width

var srcH = UIScreen.main.bounds.size.height

class NewsViewController:BaseViewController,UITableViewDelegate,UITableViewDataSource {



? ? //MARK:-----------------定義屬性----------------

? ? //表格

? ? var tbv:UITableView?


? ? //表格的數(shù)組

? ? vartbvData:[News]?


? ? //分段控制器

? ? var segment:UISegmentedControl?


? ? //標題數(shù)據(jù)

? ? var titles = ["商會動態(tài)","時政動態(tài)","平遠新聞","博風雅頌"]


? ? //下拉刷新控件

? ? var mjHeader:MJRefreshHeaderView?


? ? //MARK:-----------------------UI創(chuàng)建-----------------------------

? ? funcinitUI() ->Void{

? ? ? ? //標題分段控件

? ? ? ? self.segment = UISegmentedControl.init(items: titles)


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


? ? ? ? //設置默認分段控制器的下標

? ? ? ? self.segment?.selectedSegmentIndex = 0


? ? ? ? self.segment?.tintColor = UIColor.gray


? ? ? ? //添加事件

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


? ? ? ? //將分段控制器器添加為view的子視圖

? ? ? ? self.view.addSubview(self.segment!)



? ? ? ? //表格視圖

? ? ? ? self.tbv=UITableView.init(frame:CGRect.init(x:0, y:104, width:srcW, height:srcH-104), style: .plain)


? ? ? ? self.tbv?.delegate=self

? ? ? ? self.tbv?.dataSource=self


? ? ? ? self.view.addSubview(self.tbv!)




? ? }

?? ? //MARK:-----------------------UITableView-----------------------------

? ? functableView(_tableView:UITableView, didSelectRowAt indexPath:IndexPath) {

? ? ? ? //創(chuàng)建一個詳情控制器

? ? ? ? letdetailVC =DetailViewController()


? ? ? ? //通過選中的單元格的下標獲取對應的News對象

? ? ? ? ifletselectNew =self.tbvData?[indexPath.row]{

? ? ? ? ? ? detailVC.passNews= selectNew

? ? ? ? }


? ? ? ? //跳轉(zhuǎn)至詳情控制器

? ? ? ? self.navigationController?.pushViewController(detailVC, animated:true)

? ? }


?? ? //MARK:-----------------------UI觸發(fā)事件-----------------------------

? ? @objcfunctitleSegDidChange(seg:UISegmentedControl) ->Void{

? ? ? ? //要根據(jù)選中的標題的下標獲取不同的新聞數(shù)據(jù)

? ? ? ? self.getURLData(titleIndex: seg.selectedSegmentIndex)

? ? }

? ? //MARK:-----------------------獲取網(wǎng)絡數(shù)據(jù)-----------------------------

? ? funcgetURLData(titleIndex:Int) ->Void{

? ? ? ? //轉(zhuǎn)動指示器

? ? ? ? UIApplication.shared.isNetworkActivityIndicatorVisible = true


? ? ? ? //網(wǎng)絡請求,網(wǎng)址字符串拼接

? ? ? ? let urlStr = "http://py.cmshop.net/tPyshNewnoticController.do?godongtai2&style2=\(titleIndex)"


? ? ? ? //轉(zhuǎn)換URL地址

? ? ? ? leturl =URL.init(string: urlStr)


? ? ? ? //請求對象,并設置緩存策略和超時時長

? ? ? ? letreq =URLRequest.init(url: url!, cachePolicy: .reloadIgnoringLocalAndRemoteCacheData, timeoutInterval:8.0)


? ? ? ? //連接服務器任務

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

? ? ? ? ? ? //停止轉(zhuǎn)動等待指示器

? ? ? ? ? ? DispatchQueue.main.async {

? ? ? ? ? ? ? ? UIApplication.shared.isNetworkActivityIndicatorVisible = false


? ? ? ? ? ? //停止下拉刷新控件

? ? ? ? ? ? ? ? self.mjHeader?.endRefreshing()

? ? ? ? ? ? }


? ? ? ? ? ? //如果服務器連接失敗或超時

? ? ? ? ? ? iferror !=nil{

? ? ? ? ? ? ? ? DispatchQueue.main.async{

? ? ? ? ? ? ? ? ? ? self.view.showMBAlert(msg:"服務器錯誤")

? ? ? ? ? ? ? ? }

? ? ? ? ? ? ? ? return

? ? ? ? ? ? }


? ? ? ? ? ? //如果連接成功,將二進制數(shù)據(jù)轉(zhuǎn)換為數(shù)組或字典

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



? ? ? ? ? ? //如果轉(zhuǎn)換失敗

? ? ? ? ? ? ifjsonData ==nil{

? ? ? ? ? ? ? ? DispatchQueue.main.async{

? ? ? ? ? ? ? ? ? ? self.view.showMBAlert(msg:"網(wǎng)絡數(shù)據(jù)錯誤")

? ? ? ? ? ? ? ? }

? ? ? ? ? ? ? ? return

? ? ? ? ? ? }


? ? ? ? ? ? //轉(zhuǎn)換成功,將數(shù)據(jù)強轉(zhuǎn)為字典類型

? ? ? ? ? ? letjsonDic = jsonData!as!NSDictionary


? ? ? ? ? ? //獲取resultcode值

? ? ? ? ? ? letresultcode = jsonDic["resultcode"]as!String

? ? ? ? ? ? //如果resultcode值不為0,表示有錯誤發(fā)生,給出用戶提示

? ? ? ? ? ? ifresultcode !="0"{

? ? ? ? ? ? ? ? leterrmsg = jsonDic["errmsg"]as!String

? ? ? ? ? ? ? ? DispatchQueue.main.async{

? ? ? ? ? ? ? ? ? ? self.view.showMBAlert(msg: errmsg)

? ? ? ? ? ? ? ? }

? ? ? ? ? ? ? ? return

? ? ? ? ? ? }


? ? ? ? ? ? //如果數(shù)據(jù)都正確,做json解析

? ? ? ? ? ? letdataArr = jsonDic["data"]as! [[String:Any]]


? ? ? ? ? ? self.tbvData=News.createNewsArray(arr: dataArr)


? ? ? ? ? ? //回到UI主線程刷新表格

? ? ? ? ? ? DispatchQueue.main.async {

? ? ? ? ? ? ? ? self.tbv?.reloadData()

? ? ? ? ? ? }






? ? ? ? }



? ? ? ? task.resume()


? ? }


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

? ? overridefuncviewDidLoad() {

? ? ? ? super.viewDidLoad()

? ? ? ? //創(chuàng)建UI

? ? ? self.initUI()


? ? ? ? //獲取網(wǎng)絡數(shù)據(jù),字典獲取第一個標題的新聞數(shù)據(jù)

? ? ? ? self.getURLData(titleIndex:0)



? ? ? ? //下拉刷新控件

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


? ? ? ? //設置刷新回調(diào)的閉包

? ? ? ? self.mjHeader?.beginRefreshingBlock = {refreshViewin

? ? ? ? ? ? self.getURLData(titleIndex:self.segment!.selectedSegmentIndex)

? ? ? ? }


? ? ? ? self.tbv?.rowHeight=150





? ? }


? ? //MARK:--------------實現(xiàn)代理和數(shù)據(jù)源-----------------------

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

? ? ? ? ifletcount =self.tbvData?.count{

? ? ? ? ? ? returncount

? ? ? ? }

? ? ? ? return0

? ? }


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

? ? ? ? letidentifier ="MyCell"


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


? ? ? ? ifcell ==nil{

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

? ? ? ? }

? ? ? ? //根據(jù)下標獲取該行對應的News對象

? ? ? ? ifletone =self.tbvData?[indexPath.row]{

? ? ? ? ? ? cell?.imgView?.sd_setImage(with:URL.init(string:"http://py.cmshop.net/\(one.uploadimgurl)"), completed:nil)


? ? ? ? ? ? cell?.titlelabel?.text= one.title


? ? ? ? ? ? cell?.authorLable?.text="作者:\(one.createName)"



? ? ? ? ? ? //把時間戳值獲取

? ? ? ? ? ? letseconds = one.createDate


? ? ? ? ? ? //把時間戳轉(zhuǎn)換為時間對象

? ? ? ? ? ? letdate =Date.init(timeIntervalSince1970:TimeInterval(seconds/1000))


? ? ? ? ? ? //實力換一個日期格式器對象

? ? ? ? ? ? letdateFormate =DateFormatter.init()

? ? ? ? ? ? dateFormate.dateFormat="yyyy-MM-dd HH:mm:ss"

? ? ? ? ? ? //把日期按照格式器樣式轉(zhuǎn)換為字符串

? ? ? ? ? ? let dateStr = dateFormate.string(from: date)

? ? ? ? ? ? cell?.dateLabel?.text= dateStr

? ? ? ? }

? ? ? ? return cell!

? ? }

}

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)

? ? ? ? newsNav.tabBarItem=UITabBarItem.init(title:"新聞", image:UIImage.init(), tag:1)

? ? ? ? newsNav.navigationBar.barTintColor = UIColor.orange

? ? ? ? newsVC.navigationItem.title = "我的新聞"



? ? ? ? let collVC = CollectViewController()

? ? ? ? letcollNav =UINavigationController.init(rootViewController: collVC)

? ? ? ? collNav.tabBarItem=UITabBarItem.init(title:"收藏", image:UIImage.init(named:""), tag:1)

? ? ? ? collNav.navigationBar.barTintColor = UIColor.orange

? ? ? ? collVC.navigationItem.title = "我的收藏"


? ? ? ? let tbc = UITabBarController()

? ? ? ? tbc.viewControllers= [newsNav,collNav]


? ? ? ? self.window?.rootViewController = tbc

? ? ? ? return true

? ? }

平遠新聞-Bridging-Header.h---------------------------------------

#import "UIImageView+WebCache.h"

#import "MJRefresh.h"

#import "MBProgressHUD.h"

(開網(wǎng)哦)

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

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容