diff --git a/ParentAssistant/ParentAssistant.xcodeproj/project.pbxproj b/ParentAssistant/ParentAssistant.xcodeproj/project.pbxproj index 1ee8025..5930899 100644 --- a/ParentAssistant/ParentAssistant.xcodeproj/project.pbxproj +++ b/ParentAssistant/ParentAssistant.xcodeproj/project.pbxproj @@ -105,8 +105,8 @@ BF406CDC2057C110000A6681 /* OrderDetailViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = BF406CDB2057C110000A6681 /* OrderDetailViewController.swift */; }; BF406CDE2057C537000A6681 /* OrderDetailTableViewCell.swift in Sources */ = {isa = PBXBuildFile; fileRef = BF406CDD2057C537000A6681 /* OrderDetailTableViewCell.swift */; }; BF406CE02057C708000A6681 /* OrderDetailCollectionViewCell.swift in Sources */ = {isa = PBXBuildFile; fileRef = BF406CDF2057C708000A6681 /* OrderDetailCollectionViewCell.swift */; }; - BF5D166A204E675C00274489 /* account.swift in Sources */ = {isa = PBXBuildFile; fileRef = BF5D1669204E675C00274489 /* account.swift */; }; - BF5D166C204E6A0300274489 /* network.swift in Sources */ = {isa = PBXBuildFile; fileRef = BF5D166B204E6A0300274489 /* network.swift */; }; + BF5D166A204E675C00274489 /* AccountManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = BF5D1669204E675C00274489 /* AccountManager.swift */; }; + BF5D166C204E6A0300274489 /* HTTPServer.swift in Sources */ = {isa = PBXBuildFile; fileRef = BF5D166B204E6A0300274489 /* HTTPServer.swift */; }; BF5D1678204F8E3300274489 /* CoreTelephony.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = BF5D1677204F8E3300274489 /* CoreTelephony.framework */; }; BF5D167A204F8E3D00274489 /* libz.tbd in Frameworks */ = {isa = PBXBuildFile; fileRef = BF5D1679204F8E3D00274489 /* libz.tbd */; }; BF5D167C204F8E6000274489 /* SystemConfiguration.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = BF5D167B204F8E6000274489 /* SystemConfiguration.framework */; }; @@ -288,8 +288,8 @@ BF406CDB2057C110000A6681 /* OrderDetailViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = OrderDetailViewController.swift; sourceTree = ""; }; BF406CDD2057C537000A6681 /* OrderDetailTableViewCell.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = OrderDetailTableViewCell.swift; sourceTree = ""; }; BF406CDF2057C708000A6681 /* OrderDetailCollectionViewCell.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = OrderDetailCollectionViewCell.swift; sourceTree = ""; }; - BF5D1669204E675C00274489 /* account.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = account.swift; sourceTree = ""; }; - BF5D166B204E6A0300274489 /* network.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = network.swift; sourceTree = ""; }; + BF5D1669204E675C00274489 /* AccountManager.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AccountManager.swift; sourceTree = ""; }; + BF5D166B204E6A0300274489 /* HTTPServer.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HTTPServer.swift; sourceTree = ""; }; BF5D1677204F8E3300274489 /* CoreTelephony.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = CoreTelephony.framework; path = System/Library/Frameworks/CoreTelephony.framework; sourceTree = SDKROOT; }; BF5D1679204F8E3D00274489 /* libz.tbd */ = {isa = PBXFileReference; lastKnownFileType = "sourcecode.text-based-dylib-definition"; name = libz.tbd; path = usr/lib/libz.tbd; sourceTree = SDKROOT; }; BF5D167B204F8E6000274489 /* SystemConfiguration.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = SystemConfiguration.framework; path = System/Library/Frameworks/SystemConfiguration.framework; sourceTree = SDKROOT; }; @@ -471,11 +471,9 @@ 599364E0204E62E700C8B371 /* Information */ = { isa = PBXGroup; children = ( + ADCDA074208B3FED004F1852 /* Controller */, ADCDA073208B298D004F1852 /* Model */, - 599364E1204E62E700C8B371 /* InformationViewController.swift */, - 599364DD204E62E700C8B371 /* ChannelViewController.swift */, - 599364DE204E62E700C8B371 /* Information.storyboard */, - 599364F4204E648C00C8B371 /* view */, + 599364F4204E648C00C8B371 /* View */, ); path = Information; sourceTree = ""; @@ -522,8 +520,8 @@ BFF9B7F02057A27C00F39B3E /* view */, 590944E12057DA73004478B5 /* utils.swift */, ADE33B302062202300BEA6E6 /* Macro.swift */, - BF5D1669204E675C00274489 /* account.swift */, - BF5D166B204E6A0300274489 /* network.swift */, + BF5D1669204E675C00274489 /* AccountManager.swift */, + BF5D166B204E6A0300274489 /* HTTPServer.swift */, AD639F062089C3950028BE73 /* LocationManger.swift */, BFA7446B208193D300845D30 /* MessageManager.swift */, 599365282052553900C8B371 /* pinyin.c */, @@ -532,7 +530,7 @@ path = util; sourceTree = ""; }; - 599364F4204E648C00C8B371 /* view */ = { + 599364F4204E648C00C8B371 /* View */ = { isa = PBXGroup; children = ( 599364F5204E648C00C8B371 /* ChannelCollectionViewCell.swift */, @@ -540,7 +538,7 @@ 599364F9204E742000C8B371 /* ChannelSelectViewCollectionViewCell.swift */, 599364FA204E742000C8B371 /* ChannelSelectViewCollectionViewCell.xib */, ); - path = view; + path = View; sourceTree = ""; }; 599364FD204E941900C8B371 /* userCenter */ = { @@ -655,6 +653,16 @@ path = Model; sourceTree = ""; }; + ADCDA074208B3FED004F1852 /* Controller */ = { + isa = PBXGroup; + children = ( + 599364DD204E62E700C8B371 /* ChannelViewController.swift */, + 599364DE204E62E700C8B371 /* Information.storyboard */, + 599364E1204E62E700C8B371 /* InformationViewController.swift */, + ); + path = Controller; + sourceTree = ""; + }; B605235D289EDBCA5C5AF2C5 /* Frameworks */ = { isa = PBXGroup; children = ( @@ -1133,7 +1141,7 @@ AD639F072089C3950028BE73 /* LocationManger.swift in Sources */, 590944E22057DA73004478B5 /* utils.swift in Sources */, BFEAAAC9205257460072FAAF /* NSDate+GFCalendar.m in Sources */, - BF5D166A204E675C00274489 /* account.swift in Sources */, + BF5D166A204E675C00274489 /* AccountManager.swift in Sources */, BF406CD62057B03A000A6681 /* MessageViewController.swift in Sources */, 599364F7204E648C00C8B371 /* ChannelCollectionViewCell.swift in Sources */, BF7A4C36204CD55300460463 /* ViewController.swift in Sources */, @@ -1157,7 +1165,7 @@ BFEAAACA205257460072FAAF /* NSString+NCDate.m in Sources */, BF388469205A4DE900A240EF /* StudentClassInfo.swift in Sources */, 59C0A9B8205375F800A8BB5A /* SelectCityViewController.swift in Sources */, - BF5D166C204E6A0300274489 /* network.swift in Sources */, + BF5D166C204E6A0300274489 /* HTTPServer.swift in Sources */, BF7A4C34204CD55300460463 /* AppDelegate.swift in Sources */, BFEAAAD720525D620072FAAF /* UIColor+Expanded.m in Sources */, BFF9B7ED2057776100F39B3E /* MyChildrenViewController.swift in Sources */, diff --git a/ParentAssistant/ParentAssistant.xcworkspace/xcuserdata/caoyang.xcuserdatad/UserInterfaceState.xcuserstate b/ParentAssistant/ParentAssistant.xcworkspace/xcuserdata/caoyang.xcuserdatad/UserInterfaceState.xcuserstate index 3f378d5..b32b4ea 100644 Binary files a/ParentAssistant/ParentAssistant.xcworkspace/xcuserdata/caoyang.xcuserdatad/UserInterfaceState.xcuserstate and b/ParentAssistant/ParentAssistant.xcworkspace/xcuserdata/caoyang.xcuserdatad/UserInterfaceState.xcuserstate differ diff --git a/ParentAssistant/ParentAssistant.xcworkspace/xcuserdata/caoyang.xcuserdatad/xcdebugger/Breakpoints_v2.xcbkptlist b/ParentAssistant/ParentAssistant.xcworkspace/xcuserdata/caoyang.xcuserdatad/xcdebugger/Breakpoints_v2.xcbkptlist index 14a0487..de9c5c1 100644 --- a/ParentAssistant/ParentAssistant.xcworkspace/xcuserdata/caoyang.xcuserdatad/xcdebugger/Breakpoints_v2.xcbkptlist +++ b/ParentAssistant/ParentAssistant.xcworkspace/xcuserdata/caoyang.xcuserdatad/xcdebugger/Breakpoints_v2.xcbkptlist @@ -20,7 +20,7 @@ ignoreCount = "0" continueAfterRunningActions = "No" filePath = "ParentAssistant/Classes/controllers/Grow/GrowViewController.swift" - timestampString = "545996291.249851" + timestampString = "545997467.221319" startingColumnNumber = "9223372036854775807" endingColumnNumber = "9223372036854775807" startingLineNumber = "162" diff --git a/ParentAssistant/ParentAssistant/Classes/controllers/Information/ChannelViewController.swift b/ParentAssistant/ParentAssistant/Classes/controllers/Information/ChannelViewController.swift deleted file mode 100644 index d368974..0000000 --- a/ParentAssistant/ParentAssistant/Classes/controllers/Information/ChannelViewController.swift +++ /dev/null @@ -1,261 +0,0 @@ -// -// ChannelViewController.swift -// ParentAssistant -// -// Created by 左丞 on 2018/3/5. -// Copyright © 2018年 HANGZHOUTEAM. All rights reserved. -// - -import UIKit - -class ChannelViewController: UIViewController,UISearchBarDelegate { - - var data:ChannelDemol! - var topADs:[ADSModel]=[] - var channelId:Int=0 - @IBOutlet weak var collectView: UICollectionView! - override func viewDidLoad() { - super.viewDidLoad() - let searchView = UISearchBar(frame: CGRect(x: 0, y: 7, width: getScreenWidth()-40, height: 30)) - searchView.delegate = self - searchView.placeholder = "请输入搜索内容" - searchView.showsCancelButton = false - self.navigationItem.titleView = searchView - collectView.register(UINib(nibName: "ChannelCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: "contentCell") - getData() - // Do any additional setup after loading the view. - } - - func getData(){ - let topADsQueue = DispatchQueue(label: "topADs") - topADsQueue.async { - HTTPServer.shared.getAds(["position":2 as AnyObject], completionHandler: { (str, error) in - httpJsonResule(jsonString: str, error: error, successHandler: { (json) in - if json["status"] == 1 && error == nil{ - self.topADs.removeAll() - for item in json.contentData().arrayValue{ - self.topADs.append(ADSModel(j: item)) - } - self.collectView.reloadData() - } - }, failHandler: { (error) in - - }) - }) - } - topADsQueue.async { - HTTPServer.shared.getChannelInfo([ "areaName": localAddress as AnyObject,"channel": self.channelId as AnyObject,"toFirstPage": 0 as AnyObject,"pageIndex": 1 as AnyObject,"pageSize": 20 as AnyObject], completionHandler: { (str, error) in - httpJsonResule(jsonString: str, error: error, successHandler: { (json) in - if json["status"] == 1 && error == nil{ - self.data = ChannelDemol(j: json.contentData()) - self.collectView.reloadData() - } - }, failHandler: { (error) in - - }) - }) - } - } - - func getList(key:String?) { - if key == nil{ - return - } - HTTPServer.shared.getInformationTopic(["keyword":key as AnyObject, "areaName": localAddress as AnyObject,"channel": self.channelId as AnyObject,"toFirstPage": 0 as AnyObject,"pageIndex": 1 as AnyObject,"pageSize": 20 as AnyObject], completionHandler: { (str, error) in - httpJsonResule(jsonString: str, error: error, successHandler: { (json) in - if json["status"] == 1 && error == nil{ - self.data.channelContent.removeAll() - for item in json.contentData()["channelList"].arrayValue{ - self.data.channelContent.append(ChannelContentDemol(j: item)) - } - self.collectView.reloadData() - } - }, failHandler: { (error) in - - }) - }) - } - - - func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) { - searchBar.showsCancelButton = true - } - - func searchBarCancelButtonClicked(_ searchBar: UISearchBar) { - searchData(searchBar) - } - - func searchBarSearchButtonClicked(_ searchBar: UISearchBar) { - searchData(searchBar) - } - - //搜索资讯 - func searchData(_ searchBar: UISearchBar){ - getList(key: searchBar.text) - searchBar.resignFirstResponder() - searchBar.showsCancelButton = false - - } - - override func didReceiveMemoryWarning() { - super.didReceiveMemoryWarning() - // Dispose of any resources that can be recreated. - } - - - /* - // MARK: - Navigation - - // In a storyboard-based application, you will often want to do a little preparation before navigation - override func prepare(for segue: UIStoryboardSegue, sender: Any?) { - // Get the new view controller using segue.destinationViewController. - // Pass the selected object to the new view controller. - } - */ - -} -extension ChannelViewController:UICollectionViewDataSource,UICollectionViewDelegateFlowLayout,UICollectionViewDelegate{ - func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { - switch section { - case 0: - return 1 - case 1: - if data != nil && data.subchannel.count > 0{ - return 1 - } - return 0 - default: - return data.channelContent.count - } - - } - - func numberOfSections(in collectionView: UICollectionView) -> Int { - return 3 - } - - func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { - switch indexPath.section { - case 0: - return CGSize(width: getScreenWidth(), height: 161) - case 1: - return CGSize(width: getScreenWidth()-20, height: 92) - default: - // if indexPath.row == 0{ - return CGSize(width: getScreenWidth()-20, height: 92) - // } - // return CGSize(width: getScreenWidth()-20, height: 180) - } - - } - - func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { - switch indexPath.section { - case 0: - let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "topCell", for: indexPath) as! InformationViewTopCell - if topADs.count > 0 { - var arr:[String]=[] - for item in topADs{ - arr.append(item.fileSrc) - } - cell.headerImageView.imageArray = arr - } - return cell - case 1: - - let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "channelSelectCell", for: indexPath) as! ChannelSelectView - cell.SubchannelList = data.subchannel - cell.superNC = self.navigationController - return cell - default: - /* - @IBOutlet weak var title: UILabel! - @IBOutlet weak var option: UILabel! - @IBOutlet weak var optionNum: UILabel! - @IBOutlet weak var shareNum: UILabel! - @IBOutlet weak var picture: UIImageView! - */ - // if indexPath.row == 0{ - let item = data.channelContent[indexPath.row] - let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "contentCell", for: indexPath) as! ChannelCollectionViewCell - cell.title.text = item.title - cell.option.text = item.content - cell.optionNum.text = "\(item.talkNum)" - cell.shareNum.text = "\(item.forwardingNum)" - cell.picture.sd_setImage(with: URL(string: (HOSTImage+item.image).addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!), placeholderImage: UIImage(named: "navigationBar_backgrounImage")) - return cell - // }else{ - // let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "adiouPlayerCell", for: indexPath) as! AdiouPlayerCell - // return cell - // } - } - - } - - func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { - switch indexPath.section { - case 1: - let vc = Story.instantiateViewControllerWithIdentifier("ChannelViewControllerVC", storyName: "Information") as! ChannelViewController - self.navigationController?.pushViewController(vc, animated: true) - break - default: - let vcs = Story.instantiateViewControllerWithIdentifier("JSViewController", storyName: "JS") as! JSViewController - vcs.webURL = "\(HOSTWAP!)/ParentOrderCenter.aspx?userid=\(AccountManager.shared.id())" - self.navigationController?.present(vcs.wrapWithNavigationController(), animated: true, completion: nil) - } - } - - func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize { - return CGSize(width: getScreenWidth(), height: 10) - } - -} - -class InformationTopCell: UICollectionViewCell { - - @IBOutlet weak var headerImageView: XRCarouselView! - @IBOutlet weak var title: UILabel! - -} - -class InformationADCell: UICollectionViewCell { - -} - -//频道栏 -class ChannelViewControllerCell: UICollectionViewCell { - var superNC:UINavigationController! - var SubchannelList:[SubchannelDemol]=[] - @IBOutlet weak var channelSelectCollectionView: UICollectionView! - override func awakeFromNib() { - channelSelectCollectionView.register(UINib(nibName: "ChannelSelectViewCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: "channelcell") - } - -} - -extension ChannelViewControllerCell:UICollectionViewDataSource,UICollectionViewDelegateFlowLayout,UICollectionViewDelegate{ - func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { - return SubchannelList.count - } - - func numberOfSections(in collectionView: UICollectionView) -> Int { - return 1 - } - - func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { - return CGSize(width: (getScreenWidth()-20)/5, height: 92) - } - - func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { - let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "channelcell", for: indexPath) as! ChannelSelectViewCollectionViewCell - cell.image.sd_setImage(with: URL(string: (HOSTImage+SubchannelList[indexPath.row].channelImage).addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!), placeholderImage: #imageLiteral(resourceName: "Information_bar_icon")) - cell.channelName.text = SubchannelList[indexPath.row].channelName - return cell - - } - - func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { - let vc = Story.instantiateViewControllerWithIdentifier("ChannelViewControllerVC", storyName: "Information") as! ChannelViewController - superNC.pushViewController(vc, animated: true) - } -} diff --git a/ParentAssistant/ParentAssistant/Classes/controllers/Information/Controller/ChannelViewController.swift b/ParentAssistant/ParentAssistant/Classes/controllers/Information/Controller/ChannelViewController.swift new file mode 100644 index 0000000..d368974 --- /dev/null +++ b/ParentAssistant/ParentAssistant/Classes/controllers/Information/Controller/ChannelViewController.swift @@ -0,0 +1,261 @@ +// +// ChannelViewController.swift +// ParentAssistant +// +// Created by 左丞 on 2018/3/5. +// Copyright © 2018年 HANGZHOUTEAM. All rights reserved. +// + +import UIKit + +class ChannelViewController: UIViewController,UISearchBarDelegate { + + var data:ChannelDemol! + var topADs:[ADSModel]=[] + var channelId:Int=0 + @IBOutlet weak var collectView: UICollectionView! + override func viewDidLoad() { + super.viewDidLoad() + let searchView = UISearchBar(frame: CGRect(x: 0, y: 7, width: getScreenWidth()-40, height: 30)) + searchView.delegate = self + searchView.placeholder = "请输入搜索内容" + searchView.showsCancelButton = false + self.navigationItem.titleView = searchView + collectView.register(UINib(nibName: "ChannelCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: "contentCell") + getData() + // Do any additional setup after loading the view. + } + + func getData(){ + let topADsQueue = DispatchQueue(label: "topADs") + topADsQueue.async { + HTTPServer.shared.getAds(["position":2 as AnyObject], completionHandler: { (str, error) in + httpJsonResule(jsonString: str, error: error, successHandler: { (json) in + if json["status"] == 1 && error == nil{ + self.topADs.removeAll() + for item in json.contentData().arrayValue{ + self.topADs.append(ADSModel(j: item)) + } + self.collectView.reloadData() + } + }, failHandler: { (error) in + + }) + }) + } + topADsQueue.async { + HTTPServer.shared.getChannelInfo([ "areaName": localAddress as AnyObject,"channel": self.channelId as AnyObject,"toFirstPage": 0 as AnyObject,"pageIndex": 1 as AnyObject,"pageSize": 20 as AnyObject], completionHandler: { (str, error) in + httpJsonResule(jsonString: str, error: error, successHandler: { (json) in + if json["status"] == 1 && error == nil{ + self.data = ChannelDemol(j: json.contentData()) + self.collectView.reloadData() + } + }, failHandler: { (error) in + + }) + }) + } + } + + func getList(key:String?) { + if key == nil{ + return + } + HTTPServer.shared.getInformationTopic(["keyword":key as AnyObject, "areaName": localAddress as AnyObject,"channel": self.channelId as AnyObject,"toFirstPage": 0 as AnyObject,"pageIndex": 1 as AnyObject,"pageSize": 20 as AnyObject], completionHandler: { (str, error) in + httpJsonResule(jsonString: str, error: error, successHandler: { (json) in + if json["status"] == 1 && error == nil{ + self.data.channelContent.removeAll() + for item in json.contentData()["channelList"].arrayValue{ + self.data.channelContent.append(ChannelContentDemol(j: item)) + } + self.collectView.reloadData() + } + }, failHandler: { (error) in + + }) + }) + } + + + func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) { + searchBar.showsCancelButton = true + } + + func searchBarCancelButtonClicked(_ searchBar: UISearchBar) { + searchData(searchBar) + } + + func searchBarSearchButtonClicked(_ searchBar: UISearchBar) { + searchData(searchBar) + } + + //搜索资讯 + func searchData(_ searchBar: UISearchBar){ + getList(key: searchBar.text) + searchBar.resignFirstResponder() + searchBar.showsCancelButton = false + + } + + override func didReceiveMemoryWarning() { + super.didReceiveMemoryWarning() + // Dispose of any resources that can be recreated. + } + + + /* + // MARK: - Navigation + + // In a storyboard-based application, you will often want to do a little preparation before navigation + override func prepare(for segue: UIStoryboardSegue, sender: Any?) { + // Get the new view controller using segue.destinationViewController. + // Pass the selected object to the new view controller. + } + */ + +} +extension ChannelViewController:UICollectionViewDataSource,UICollectionViewDelegateFlowLayout,UICollectionViewDelegate{ + func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { + switch section { + case 0: + return 1 + case 1: + if data != nil && data.subchannel.count > 0{ + return 1 + } + return 0 + default: + return data.channelContent.count + } + + } + + func numberOfSections(in collectionView: UICollectionView) -> Int { + return 3 + } + + func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { + switch indexPath.section { + case 0: + return CGSize(width: getScreenWidth(), height: 161) + case 1: + return CGSize(width: getScreenWidth()-20, height: 92) + default: + // if indexPath.row == 0{ + return CGSize(width: getScreenWidth()-20, height: 92) + // } + // return CGSize(width: getScreenWidth()-20, height: 180) + } + + } + + func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { + switch indexPath.section { + case 0: + let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "topCell", for: indexPath) as! InformationViewTopCell + if topADs.count > 0 { + var arr:[String]=[] + for item in topADs{ + arr.append(item.fileSrc) + } + cell.headerImageView.imageArray = arr + } + return cell + case 1: + + let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "channelSelectCell", for: indexPath) as! ChannelSelectView + cell.SubchannelList = data.subchannel + cell.superNC = self.navigationController + return cell + default: + /* + @IBOutlet weak var title: UILabel! + @IBOutlet weak var option: UILabel! + @IBOutlet weak var optionNum: UILabel! + @IBOutlet weak var shareNum: UILabel! + @IBOutlet weak var picture: UIImageView! + */ + // if indexPath.row == 0{ + let item = data.channelContent[indexPath.row] + let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "contentCell", for: indexPath) as! ChannelCollectionViewCell + cell.title.text = item.title + cell.option.text = item.content + cell.optionNum.text = "\(item.talkNum)" + cell.shareNum.text = "\(item.forwardingNum)" + cell.picture.sd_setImage(with: URL(string: (HOSTImage+item.image).addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!), placeholderImage: UIImage(named: "navigationBar_backgrounImage")) + return cell + // }else{ + // let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "adiouPlayerCell", for: indexPath) as! AdiouPlayerCell + // return cell + // } + } + + } + + func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { + switch indexPath.section { + case 1: + let vc = Story.instantiateViewControllerWithIdentifier("ChannelViewControllerVC", storyName: "Information") as! ChannelViewController + self.navigationController?.pushViewController(vc, animated: true) + break + default: + let vcs = Story.instantiateViewControllerWithIdentifier("JSViewController", storyName: "JS") as! JSViewController + vcs.webURL = "\(HOSTWAP!)/ParentOrderCenter.aspx?userid=\(AccountManager.shared.id())" + self.navigationController?.present(vcs.wrapWithNavigationController(), animated: true, completion: nil) + } + } + + func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize { + return CGSize(width: getScreenWidth(), height: 10) + } + +} + +class InformationTopCell: UICollectionViewCell { + + @IBOutlet weak var headerImageView: XRCarouselView! + @IBOutlet weak var title: UILabel! + +} + +class InformationADCell: UICollectionViewCell { + +} + +//频道栏 +class ChannelViewControllerCell: UICollectionViewCell { + var superNC:UINavigationController! + var SubchannelList:[SubchannelDemol]=[] + @IBOutlet weak var channelSelectCollectionView: UICollectionView! + override func awakeFromNib() { + channelSelectCollectionView.register(UINib(nibName: "ChannelSelectViewCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: "channelcell") + } + +} + +extension ChannelViewControllerCell:UICollectionViewDataSource,UICollectionViewDelegateFlowLayout,UICollectionViewDelegate{ + func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { + return SubchannelList.count + } + + func numberOfSections(in collectionView: UICollectionView) -> Int { + return 1 + } + + func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { + return CGSize(width: (getScreenWidth()-20)/5, height: 92) + } + + func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { + let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "channelcell", for: indexPath) as! ChannelSelectViewCollectionViewCell + cell.image.sd_setImage(with: URL(string: (HOSTImage+SubchannelList[indexPath.row].channelImage).addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!), placeholderImage: #imageLiteral(resourceName: "Information_bar_icon")) + cell.channelName.text = SubchannelList[indexPath.row].channelName + return cell + + } + + func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { + let vc = Story.instantiateViewControllerWithIdentifier("ChannelViewControllerVC", storyName: "Information") as! ChannelViewController + superNC.pushViewController(vc, animated: true) + } +} diff --git a/ParentAssistant/ParentAssistant/Classes/controllers/Information/Controller/Information.storyboard b/ParentAssistant/ParentAssistant/Classes/controllers/Information/Controller/Information.storyboard new file mode 100644 index 0000000..b0ac96b --- /dev/null +++ b/ParentAssistant/ParentAssistant/Classes/controllers/Information/Controller/Information.storyboard @@ -0,0 +1,140 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/ParentAssistant/ParentAssistant/Classes/controllers/Information/Controller/InformationViewController.swift b/ParentAssistant/ParentAssistant/Classes/controllers/Information/Controller/InformationViewController.swift new file mode 100644 index 0000000..4e661d5 --- /dev/null +++ b/ParentAssistant/ParentAssistant/Classes/controllers/Information/Controller/InformationViewController.swift @@ -0,0 +1,377 @@ +// +// InformationViewController.swift +// ParentAssistant +// +// Created by 葛建军 on 2018/3/5. +// Copyright © 2018年 HANGZHOUTEAM. All rights reserved. +// + +import UIKit +class InformationViewController: UIViewController,UISearchBarDelegate { + @IBOutlet weak var collectView: UICollectionView! + var leftLabel:UILabel! + var data:ChannelDemol! + var topADs:[ADSModel]=[] + var isFirstviewController:Bool=true + var channel:Int=0 + + //导航栏左侧按钮 + lazy var leftCityView = {()-> UIView in + //左按钮 + let leftView = UIButton.init(frame: CGRect.init(x: 0, y: 0, width: 70, height: 44)) + let titleLab = UILabel.init(frame: CGRect.init(x: 0, y: 0, width: 60, height: 44)) + + titleLab.font = UIFont.systemFont(ofSize: 15) + titleLab.numberOfLines = 0 + titleLab.adjustsFontSizeToFitWidth = true + titleLab.textAlignment = .center + titleLab.textColor = .white + titleLab.text = localAddress + self.leftLabel = titleLab + leftView.addSubview(titleLab) + + let imageView = UIImageView.init(frame: CGRect.init(x: 60, y: 11, width: 10, height: 22)) + imageView.image = UIImage.init(named: "report_white_pull") + imageView.contentMode = .scaleAspectFit + leftView.addSubview(imageView) + + leftView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(EvaluationViewController.getAddreess(tap:)))) + return leftView + }() + + override func viewDidLoad() { + super.viewDidLoad() + + let item = UIBarButtonItem.init(title: "返回", style: .plain, target: self, action: nil) + self.navigationItem.backBarButtonItem = item + + drawTopUI() + + } + override func viewWillAppear(_ animated: Bool) { + super.viewWillAppear(animated) + + if isFirstviewController{ + let leftBtn = UIBarButtonItem.init(customView: self.leftCityView) + self.navigationItem.leftBarButtonItem = leftBtn + if localAddress == "未知" { + LocationManger.shared.block = { str in + localAddress = str + self.leftLabel.text = localAddress + self.getDataFromNet() + } + } + } + self.getDataFromNet() + } + func drawTopUI(){ + + self.configTheme() + //搜索框 + let searchView = SearchBarView.init(frame: CGRect.init(x: 0, y: 0, width: screenWidth-100, height: navigationBarHeight!)) + //MARK:搜索框搜索回调 + searchView.block = { str,type in + DebugLog(str) + switch type { + case .SearchType: + self.getList(key: str) + case .CancelType: + self.getDataFromNet() + } + } + self.navigationItem.titleView = searchView + } + override func viewWillDisappear(_ animated: Bool) { + super.viewWillDisappear(animated) + SVProgressHUD.dismiss() + } + //MARK: - 获取该城市下的数据 + private func getDataFromNet(){ + //position 广告位置0-首次广告位1-开屏广告位2-资讯首页3-频道首页4-频道内容5-文章内容页 + SVProgressHUD.show() + let group = DispatchGroup() + var position:Int = 2 + if !self.isFirstviewController { + position = 3 + } + group.enter() + HTTPServer.shared.getAds(["position":position as AnyObject,"areaName":localAddress as AnyObject], completionHandler: { (str, error) in//getPercentEncodingString(str: localAddress) + httpJsonResule(jsonString: str, error: error, successHandler: { (json) in + if json["status"] == 1 && error == nil{ + self.topADs.removeAll() + for item in json.contentData().arrayValue{ + self.topADs.append(ADSModel(j: item)) + } + } + }, failHandler: { (error) in + + }) + group.leave() + }) + group.enter() + let dic = self.getListDic() + HTTPServer.shared.getChannelInfo(dic, completionHandler: { (str, error) in + httpJsonResule(jsonString: str, error: error, successHandler: { (json) in + if json["status"] == 1 && error == nil{ + self.data = ChannelDemol(j: json.contentData()) + } + }, failHandler: { (error) in + + }) + group.leave() + }) + group.notify(queue: DispatchQueue.main) { + SVProgressHUD.dismiss() + self.collectView.reloadData() + } + } + //MARK: - 地址选择回调 + @objc func getAddreess(tap:UITapGestureRecognizer){ + tap.view?.isUserInteractionEnabled = false + LZCityPickerController.showPicker(in: self + , select: { (address, province, city, area, isSelect) in + if isSelect{ + tap.view?.isUserInteractionEnabled = true + self.leftLabel.text = area! + localAddress = area! + self.getDataFromNet() + } + }) { + tap.view?.isUserInteractionEnabled = true + } + } + + //MARK: - 搜索框搜索咨询 + func getList(key:String?) { + if key == nil{ + return + } + var dic = getListDic() + dic.updateValue(key as AnyObject, forKey: "keyword") + + HTTPServer.shared.getInformationTopic(dic, completionHandler: { (str, error) in + httpJsonResule(jsonString: str, error: error, successHandler: { (json) in + if json["status"] == 1 && error == nil{ + self.data.channelContent.removeAll() + for item in json.contentData()["channelList"].arrayValue{ + self.data.channelContent.append(ChannelContentDemol(j: item)) + } + self.collectView.reloadData() + } + }, failHandler: { (error) in + + }) + }) + } + + //获得请求参数 + func getListDic()->[String:AnyObject]{ + var dic = [ "areaName": localAddress as AnyObject,"pageIndex": 1 as AnyObject,"pageSize": 20 as AnyObject] + var toFirstPage:Int = 1 + var ch:Int = 0 + if !isFirstviewController{ + toFirstPage = 0 + ch = channel + } + dic.updateValue(ch as AnyObject, forKey: "channel") + dic.updateValue(toFirstPage as AnyObject, forKey: "toFirstPage") + return dic + } + + + override func didReceiveMemoryWarning() { + super.didReceiveMemoryWarning() + // Dispose of any resources that can be recreated. + } + + //点击资讯进入详情 + func pushToInfoView(index:Int){ + let vcs = Story.instantiateViewControllerWithIdentifier("JSViewController", storyName: "JS") as! JSViewController + if data.channelContent[index].url != "" { + vcs.webURL = data.channelContent[index].url + }else{ + vcs.webURL = (HOSTWAP+"/InformationDetail.aspx?id="+"\(data.channelContent[index].id)"+"&areaname="+localAddress).addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)! + } + self.navigationController?.present(vcs.wrapWithNavigationController(), animated: true, completion: nil) + } + +} + +extension InformationViewController:XRCarouselViewDelegate{ + func carouselView(_ carouselView: XRCarouselView!, clickImageAt index: Int) { + pushToInfoView(index: index) + } +} + +//整体分三个部分1.轮播图,2频道栏,3列表 +extension InformationViewController:UICollectionViewDataSource,UICollectionViewDelegateFlowLayout,UICollectionViewDelegate{ + func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { + switch section { + case 0: + return 1 + case 1: + if data != nil && data.subchannel.count > 0{ + return 1 + } + return 0 + default: + return data != nil ? data.channelContent.count : 0 + } + } + + func numberOfSections(in collectionView: UICollectionView) -> Int { + return 3 + } + + func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { + switch indexPath.section { + case 0: + return CGSize(width: getScreenWidth(), height: getScreenWidth()/375*200) + case 1: + return CGSize(width: getScreenWidth()-20, height: 92) + default: +// if indexPath.row == 0{ + return CGSize(width: getScreenWidth()-20, height: 92) +// } +// return CGSize(width: getScreenWidth()-20, height: 180) + } + } + + func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize { + if section == 2{ + return CGSize(width: getScreenWidth()-20, height: 40) + }else{ + return CGSize(width: getScreenWidth(), height: 10) + } + } + + func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { + collectionView.register(UINib(nibName: "ChannelCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: "contentCell") + switch indexPath.section { + case 0: + let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "topCell", for: indexPath) as! InformationViewTopCell + if topADs.count > 0 { + var arr:[String]=[] + for item in topADs{ + arr.append(HOSTImage+item.fileSrc) + } + cell.headerImageView.imageArray = arr + } + return cell + case 1: + + let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "channelSelectCell", for: indexPath) as! ChannelSelectView + cell.SubchannelList = data.subchannel + cell.superNC = self.navigationController + return cell + default: +// if indexPath.row == 0{ + let item = data.channelContent[indexPath.row] + let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "contentCell", for: indexPath) as! ChannelCollectionViewCell + cell.title.text = item.title + cell.option.text = item.content + cell.optionNum.text = "\(item.lookNum)" + cell.shareNum.text = "\(item.forwardingNum)" + cell.picture.sd_setImage(with: URL(string: (HOSTImage+item.image).addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!), placeholderImage: UIImage(named: "navigationBar_backgrounImage")) + return cell +// }else{ +// let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "adiouPlayerCell", for: indexPath) as! AdiouPlayerCell +// return cell +// } + } + } + + func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { + switch indexPath.section { + case 1: + let vc = Story.instantiateViewControllerWithIdentifier("InformationViewControllerVC", storyName: "Main") as! InformationViewController + vc.channel = data.subchannel[indexPath.row].id + vc.isFirstviewController = false + self.navigationController?.pushViewController(vc, animated: true) + break + default: + let vcs = Story.instantiateViewControllerWithIdentifier("JSViewController", storyName: "JS") as! JSViewController + if data.channelContent[indexPath.row].url != "" { + vcs.webURL = data.channelContent[indexPath.row].url + }else{ + vcs.webURL = (HOSTWAP+"/InformationDetail.aspx?id="+"\(data.channelContent[indexPath.row].id)"+"&areaname="+localAddress).addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)! + } + self.navigationController?.present(vcs.wrapWithNavigationController(), animated: true, completion: nil) + +// pushToInfoView(index: indexPath.row) + } + } + + func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView { + var reusableview:UICollectionReusableView? + if kind == UICollectionElementKindSectionHeader{ + let headerView = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "headerView", for: indexPath) as! InformationSectionHeader + headerView.title.text = "咨讯话题" + reusableview = headerView + } + if indexPath.section == 2{ + reusableview?.isHidden = false + }else{ + reusableview?.isHidden = true + } + return reusableview! + } +} + + +class InformationSectionHeader: UICollectionReusableView { + @IBOutlet weak var title: UILabel! + +} + +//首页的轮播图所在的cell +class InformationViewTopCell: UICollectionViewCell { + + @IBOutlet weak var headerImageView: XRCarouselView! + +} + +//视频cell +class AdiouPlayerCell: UICollectionViewCell { + +} + +//频道栏 +class ChannelSelectView: UICollectionViewCell { + var superNC:UINavigationController! + var SubchannelList:[SubchannelDemol]=[] + @IBOutlet weak var channelSelectCollectionView: UICollectionView! + override func awakeFromNib() { + channelSelectCollectionView.register(UINib(nibName: "ChannelSelectViewCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: "channelcell") + } +} + +extension ChannelSelectView:UICollectionViewDataSource,UICollectionViewDelegateFlowLayout,UICollectionViewDelegate{ + func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { + return SubchannelList.count + } + + func numberOfSections(in collectionView: UICollectionView) -> Int { + return 1 + } + + func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { + return CGSize(width: (getScreenWidth()-20)/4, height: 92) + } + + func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { + let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "channelcell", for: indexPath) as! ChannelSelectViewCollectionViewCell + cell.image.sd_setImage(with: URL(string: (HOSTImage+SubchannelList[indexPath.row].channelImage).addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!), placeholderImage: UIImage(named: "evaluation_icon_highSchoolEnter")) + cell.channelName.text = SubchannelList[indexPath.row].channelName + return cell + } + + func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { + let vc = Story.instantiateViewControllerWithIdentifier("InformationViewControllerVC", storyName: "Main") as! InformationViewController + vc.channel = SubchannelList[indexPath.row].id + vc.isFirstviewController = false + superNC.pushViewController(vc, animated: true) + } +} + + diff --git a/ParentAssistant/ParentAssistant/Classes/controllers/Information/Information.storyboard b/ParentAssistant/ParentAssistant/Classes/controllers/Information/Information.storyboard deleted file mode 100644 index b0ac96b..0000000 --- a/ParentAssistant/ParentAssistant/Classes/controllers/Information/Information.storyboard +++ /dev/null @@ -1,140 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/ParentAssistant/ParentAssistant/Classes/controllers/Information/InformationViewController.swift b/ParentAssistant/ParentAssistant/Classes/controllers/Information/InformationViewController.swift deleted file mode 100644 index 4e661d5..0000000 --- a/ParentAssistant/ParentAssistant/Classes/controllers/Information/InformationViewController.swift +++ /dev/null @@ -1,377 +0,0 @@ -// -// InformationViewController.swift -// ParentAssistant -// -// Created by 葛建军 on 2018/3/5. -// Copyright © 2018年 HANGZHOUTEAM. All rights reserved. -// - -import UIKit -class InformationViewController: UIViewController,UISearchBarDelegate { - @IBOutlet weak var collectView: UICollectionView! - var leftLabel:UILabel! - var data:ChannelDemol! - var topADs:[ADSModel]=[] - var isFirstviewController:Bool=true - var channel:Int=0 - - //导航栏左侧按钮 - lazy var leftCityView = {()-> UIView in - //左按钮 - let leftView = UIButton.init(frame: CGRect.init(x: 0, y: 0, width: 70, height: 44)) - let titleLab = UILabel.init(frame: CGRect.init(x: 0, y: 0, width: 60, height: 44)) - - titleLab.font = UIFont.systemFont(ofSize: 15) - titleLab.numberOfLines = 0 - titleLab.adjustsFontSizeToFitWidth = true - titleLab.textAlignment = .center - titleLab.textColor = .white - titleLab.text = localAddress - self.leftLabel = titleLab - leftView.addSubview(titleLab) - - let imageView = UIImageView.init(frame: CGRect.init(x: 60, y: 11, width: 10, height: 22)) - imageView.image = UIImage.init(named: "report_white_pull") - imageView.contentMode = .scaleAspectFit - leftView.addSubview(imageView) - - leftView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(EvaluationViewController.getAddreess(tap:)))) - return leftView - }() - - override func viewDidLoad() { - super.viewDidLoad() - - let item = UIBarButtonItem.init(title: "返回", style: .plain, target: self, action: nil) - self.navigationItem.backBarButtonItem = item - - drawTopUI() - - } - override func viewWillAppear(_ animated: Bool) { - super.viewWillAppear(animated) - - if isFirstviewController{ - let leftBtn = UIBarButtonItem.init(customView: self.leftCityView) - self.navigationItem.leftBarButtonItem = leftBtn - if localAddress == "未知" { - LocationManger.shared.block = { str in - localAddress = str - self.leftLabel.text = localAddress - self.getDataFromNet() - } - } - } - self.getDataFromNet() - } - func drawTopUI(){ - - self.configTheme() - //搜索框 - let searchView = SearchBarView.init(frame: CGRect.init(x: 0, y: 0, width: screenWidth-100, height: navigationBarHeight!)) - //MARK:搜索框搜索回调 - searchView.block = { str,type in - DebugLog(str) - switch type { - case .SearchType: - self.getList(key: str) - case .CancelType: - self.getDataFromNet() - } - } - self.navigationItem.titleView = searchView - } - override func viewWillDisappear(_ animated: Bool) { - super.viewWillDisappear(animated) - SVProgressHUD.dismiss() - } - //MARK: - 获取该城市下的数据 - private func getDataFromNet(){ - //position 广告位置0-首次广告位1-开屏广告位2-资讯首页3-频道首页4-频道内容5-文章内容页 - SVProgressHUD.show() - let group = DispatchGroup() - var position:Int = 2 - if !self.isFirstviewController { - position = 3 - } - group.enter() - HTTPServer.shared.getAds(["position":position as AnyObject,"areaName":localAddress as AnyObject], completionHandler: { (str, error) in//getPercentEncodingString(str: localAddress) - httpJsonResule(jsonString: str, error: error, successHandler: { (json) in - if json["status"] == 1 && error == nil{ - self.topADs.removeAll() - for item in json.contentData().arrayValue{ - self.topADs.append(ADSModel(j: item)) - } - } - }, failHandler: { (error) in - - }) - group.leave() - }) - group.enter() - let dic = self.getListDic() - HTTPServer.shared.getChannelInfo(dic, completionHandler: { (str, error) in - httpJsonResule(jsonString: str, error: error, successHandler: { (json) in - if json["status"] == 1 && error == nil{ - self.data = ChannelDemol(j: json.contentData()) - } - }, failHandler: { (error) in - - }) - group.leave() - }) - group.notify(queue: DispatchQueue.main) { - SVProgressHUD.dismiss() - self.collectView.reloadData() - } - } - //MARK: - 地址选择回调 - @objc func getAddreess(tap:UITapGestureRecognizer){ - tap.view?.isUserInteractionEnabled = false - LZCityPickerController.showPicker(in: self - , select: { (address, province, city, area, isSelect) in - if isSelect{ - tap.view?.isUserInteractionEnabled = true - self.leftLabel.text = area! - localAddress = area! - self.getDataFromNet() - } - }) { - tap.view?.isUserInteractionEnabled = true - } - } - - //MARK: - 搜索框搜索咨询 - func getList(key:String?) { - if key == nil{ - return - } - var dic = getListDic() - dic.updateValue(key as AnyObject, forKey: "keyword") - - HTTPServer.shared.getInformationTopic(dic, completionHandler: { (str, error) in - httpJsonResule(jsonString: str, error: error, successHandler: { (json) in - if json["status"] == 1 && error == nil{ - self.data.channelContent.removeAll() - for item in json.contentData()["channelList"].arrayValue{ - self.data.channelContent.append(ChannelContentDemol(j: item)) - } - self.collectView.reloadData() - } - }, failHandler: { (error) in - - }) - }) - } - - //获得请求参数 - func getListDic()->[String:AnyObject]{ - var dic = [ "areaName": localAddress as AnyObject,"pageIndex": 1 as AnyObject,"pageSize": 20 as AnyObject] - var toFirstPage:Int = 1 - var ch:Int = 0 - if !isFirstviewController{ - toFirstPage = 0 - ch = channel - } - dic.updateValue(ch as AnyObject, forKey: "channel") - dic.updateValue(toFirstPage as AnyObject, forKey: "toFirstPage") - return dic - } - - - override func didReceiveMemoryWarning() { - super.didReceiveMemoryWarning() - // Dispose of any resources that can be recreated. - } - - //点击资讯进入详情 - func pushToInfoView(index:Int){ - let vcs = Story.instantiateViewControllerWithIdentifier("JSViewController", storyName: "JS") as! JSViewController - if data.channelContent[index].url != "" { - vcs.webURL = data.channelContent[index].url - }else{ - vcs.webURL = (HOSTWAP+"/InformationDetail.aspx?id="+"\(data.channelContent[index].id)"+"&areaname="+localAddress).addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)! - } - self.navigationController?.present(vcs.wrapWithNavigationController(), animated: true, completion: nil) - } - -} - -extension InformationViewController:XRCarouselViewDelegate{ - func carouselView(_ carouselView: XRCarouselView!, clickImageAt index: Int) { - pushToInfoView(index: index) - } -} - -//整体分三个部分1.轮播图,2频道栏,3列表 -extension InformationViewController:UICollectionViewDataSource,UICollectionViewDelegateFlowLayout,UICollectionViewDelegate{ - func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { - switch section { - case 0: - return 1 - case 1: - if data != nil && data.subchannel.count > 0{ - return 1 - } - return 0 - default: - return data != nil ? data.channelContent.count : 0 - } - } - - func numberOfSections(in collectionView: UICollectionView) -> Int { - return 3 - } - - func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { - switch indexPath.section { - case 0: - return CGSize(width: getScreenWidth(), height: getScreenWidth()/375*200) - case 1: - return CGSize(width: getScreenWidth()-20, height: 92) - default: -// if indexPath.row == 0{ - return CGSize(width: getScreenWidth()-20, height: 92) -// } -// return CGSize(width: getScreenWidth()-20, height: 180) - } - } - - func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize { - if section == 2{ - return CGSize(width: getScreenWidth()-20, height: 40) - }else{ - return CGSize(width: getScreenWidth(), height: 10) - } - } - - func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { - collectionView.register(UINib(nibName: "ChannelCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: "contentCell") - switch indexPath.section { - case 0: - let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "topCell", for: indexPath) as! InformationViewTopCell - if topADs.count > 0 { - var arr:[String]=[] - for item in topADs{ - arr.append(HOSTImage+item.fileSrc) - } - cell.headerImageView.imageArray = arr - } - return cell - case 1: - - let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "channelSelectCell", for: indexPath) as! ChannelSelectView - cell.SubchannelList = data.subchannel - cell.superNC = self.navigationController - return cell - default: -// if indexPath.row == 0{ - let item = data.channelContent[indexPath.row] - let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "contentCell", for: indexPath) as! ChannelCollectionViewCell - cell.title.text = item.title - cell.option.text = item.content - cell.optionNum.text = "\(item.lookNum)" - cell.shareNum.text = "\(item.forwardingNum)" - cell.picture.sd_setImage(with: URL(string: (HOSTImage+item.image).addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!), placeholderImage: UIImage(named: "navigationBar_backgrounImage")) - return cell -// }else{ -// let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "adiouPlayerCell", for: indexPath) as! AdiouPlayerCell -// return cell -// } - } - } - - func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { - switch indexPath.section { - case 1: - let vc = Story.instantiateViewControllerWithIdentifier("InformationViewControllerVC", storyName: "Main") as! InformationViewController - vc.channel = data.subchannel[indexPath.row].id - vc.isFirstviewController = false - self.navigationController?.pushViewController(vc, animated: true) - break - default: - let vcs = Story.instantiateViewControllerWithIdentifier("JSViewController", storyName: "JS") as! JSViewController - if data.channelContent[indexPath.row].url != "" { - vcs.webURL = data.channelContent[indexPath.row].url - }else{ - vcs.webURL = (HOSTWAP+"/InformationDetail.aspx?id="+"\(data.channelContent[indexPath.row].id)"+"&areaname="+localAddress).addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)! - } - self.navigationController?.present(vcs.wrapWithNavigationController(), animated: true, completion: nil) - -// pushToInfoView(index: indexPath.row) - } - } - - func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView { - var reusableview:UICollectionReusableView? - if kind == UICollectionElementKindSectionHeader{ - let headerView = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "headerView", for: indexPath) as! InformationSectionHeader - headerView.title.text = "咨讯话题" - reusableview = headerView - } - if indexPath.section == 2{ - reusableview?.isHidden = false - }else{ - reusableview?.isHidden = true - } - return reusableview! - } -} - - -class InformationSectionHeader: UICollectionReusableView { - @IBOutlet weak var title: UILabel! - -} - -//首页的轮播图所在的cell -class InformationViewTopCell: UICollectionViewCell { - - @IBOutlet weak var headerImageView: XRCarouselView! - -} - -//视频cell -class AdiouPlayerCell: UICollectionViewCell { - -} - -//频道栏 -class ChannelSelectView: UICollectionViewCell { - var superNC:UINavigationController! - var SubchannelList:[SubchannelDemol]=[] - @IBOutlet weak var channelSelectCollectionView: UICollectionView! - override func awakeFromNib() { - channelSelectCollectionView.register(UINib(nibName: "ChannelSelectViewCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: "channelcell") - } -} - -extension ChannelSelectView:UICollectionViewDataSource,UICollectionViewDelegateFlowLayout,UICollectionViewDelegate{ - func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { - return SubchannelList.count - } - - func numberOfSections(in collectionView: UICollectionView) -> Int { - return 1 - } - - func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { - return CGSize(width: (getScreenWidth()-20)/4, height: 92) - } - - func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { - let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "channelcell", for: indexPath) as! ChannelSelectViewCollectionViewCell - cell.image.sd_setImage(with: URL(string: (HOSTImage+SubchannelList[indexPath.row].channelImage).addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!), placeholderImage: UIImage(named: "evaluation_icon_highSchoolEnter")) - cell.channelName.text = SubchannelList[indexPath.row].channelName - return cell - } - - func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { - let vc = Story.instantiateViewControllerWithIdentifier("InformationViewControllerVC", storyName: "Main") as! InformationViewController - vc.channel = SubchannelList[indexPath.row].id - vc.isFirstviewController = false - superNC.pushViewController(vc, animated: true) - } -} - - diff --git a/ParentAssistant/ParentAssistant/Classes/controllers/Information/View/ChannelCollectionViewCell.swift b/ParentAssistant/ParentAssistant/Classes/controllers/Information/View/ChannelCollectionViewCell.swift new file mode 100644 index 0000000..e800828 --- /dev/null +++ b/ParentAssistant/ParentAssistant/Classes/controllers/Information/View/ChannelCollectionViewCell.swift @@ -0,0 +1,24 @@ +// +// ChannelCollectionViewCell.swift +// ParentAssistant +// +// Created by 左丞 on 2018/3/6. +// Copyright © 2018年 HANGZHOUTEAM. All rights reserved. +// + +import UIKit + +class ChannelCollectionViewCell: UICollectionViewCell { + + @IBOutlet weak var title: UILabel! + @IBOutlet weak var option: UILabel! + @IBOutlet weak var optionNum: UILabel! + @IBOutlet weak var shareNum: UILabel! + @IBOutlet weak var picture: UIImageView! + + override func awakeFromNib() { + super.awakeFromNib() + // Initialization code + } + +} diff --git a/ParentAssistant/ParentAssistant/Classes/controllers/Information/View/ChannelCollectionViewCell.xib b/ParentAssistant/ParentAssistant/Classes/controllers/Information/View/ChannelCollectionViewCell.xib new file mode 100644 index 0000000..ff3c811 --- /dev/null +++ b/ParentAssistant/ParentAssistant/Classes/controllers/Information/View/ChannelCollectionViewCell.xib @@ -0,0 +1,102 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/ParentAssistant/ParentAssistant/Classes/controllers/Information/View/ChannelSelectViewCollectionViewCell.swift b/ParentAssistant/ParentAssistant/Classes/controllers/Information/View/ChannelSelectViewCollectionViewCell.swift new file mode 100644 index 0000000..0e6df9e --- /dev/null +++ b/ParentAssistant/ParentAssistant/Classes/controllers/Information/View/ChannelSelectViewCollectionViewCell.swift @@ -0,0 +1,21 @@ +// +// ChannelSelectViewCollectionViewCell.swift +// ParentAssistant +// +// Created by 左丞 on 2018/3/6. +// Copyright © 2018年 HANGZHOUTEAM. All rights reserved. +// + +import UIKit + +class ChannelSelectViewCollectionViewCell: UICollectionViewCell { + + @IBOutlet weak var image: UIImageView! + @IBOutlet weak var channelName: UILabel! + + override func awakeFromNib() { + super.awakeFromNib() + // Initialization code + } + +} diff --git a/ParentAssistant/ParentAssistant/Classes/controllers/Information/View/ChannelSelectViewCollectionViewCell.xib b/ParentAssistant/ParentAssistant/Classes/controllers/Information/View/ChannelSelectViewCollectionViewCell.xib new file mode 100644 index 0000000..54d6463 --- /dev/null +++ b/ParentAssistant/ParentAssistant/Classes/controllers/Information/View/ChannelSelectViewCollectionViewCell.xib @@ -0,0 +1,65 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/ParentAssistant/ParentAssistant/Classes/controllers/Information/view/ChannelCollectionViewCell.swift b/ParentAssistant/ParentAssistant/Classes/controllers/Information/view/ChannelCollectionViewCell.swift deleted file mode 100644 index e800828..0000000 --- a/ParentAssistant/ParentAssistant/Classes/controllers/Information/view/ChannelCollectionViewCell.swift +++ /dev/null @@ -1,24 +0,0 @@ -// -// ChannelCollectionViewCell.swift -// ParentAssistant -// -// Created by 左丞 on 2018/3/6. -// Copyright © 2018年 HANGZHOUTEAM. All rights reserved. -// - -import UIKit - -class ChannelCollectionViewCell: UICollectionViewCell { - - @IBOutlet weak var title: UILabel! - @IBOutlet weak var option: UILabel! - @IBOutlet weak var optionNum: UILabel! - @IBOutlet weak var shareNum: UILabel! - @IBOutlet weak var picture: UIImageView! - - override func awakeFromNib() { - super.awakeFromNib() - // Initialization code - } - -} diff --git a/ParentAssistant/ParentAssistant/Classes/controllers/Information/view/ChannelCollectionViewCell.xib b/ParentAssistant/ParentAssistant/Classes/controllers/Information/view/ChannelCollectionViewCell.xib deleted file mode 100644 index ff3c811..0000000 --- a/ParentAssistant/ParentAssistant/Classes/controllers/Information/view/ChannelCollectionViewCell.xib +++ /dev/null @@ -1,102 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/ParentAssistant/ParentAssistant/Classes/controllers/Information/view/ChannelSelectViewCollectionViewCell.swift b/ParentAssistant/ParentAssistant/Classes/controllers/Information/view/ChannelSelectViewCollectionViewCell.swift deleted file mode 100644 index 0e6df9e..0000000 --- a/ParentAssistant/ParentAssistant/Classes/controllers/Information/view/ChannelSelectViewCollectionViewCell.swift +++ /dev/null @@ -1,21 +0,0 @@ -// -// ChannelSelectViewCollectionViewCell.swift -// ParentAssistant -// -// Created by 左丞 on 2018/3/6. -// Copyright © 2018年 HANGZHOUTEAM. All rights reserved. -// - -import UIKit - -class ChannelSelectViewCollectionViewCell: UICollectionViewCell { - - @IBOutlet weak var image: UIImageView! - @IBOutlet weak var channelName: UILabel! - - override func awakeFromNib() { - super.awakeFromNib() - // Initialization code - } - -} diff --git a/ParentAssistant/ParentAssistant/Classes/controllers/Information/view/ChannelSelectViewCollectionViewCell.xib b/ParentAssistant/ParentAssistant/Classes/controllers/Information/view/ChannelSelectViewCollectionViewCell.xib deleted file mode 100644 index 54d6463..0000000 --- a/ParentAssistant/ParentAssistant/Classes/controllers/Information/view/ChannelSelectViewCollectionViewCell.xib +++ /dev/null @@ -1,65 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/ParentAssistant/ParentAssistant/Classes/util/AccountManager.swift b/ParentAssistant/ParentAssistant/Classes/util/AccountManager.swift new file mode 100644 index 0000000..6d4ad49 --- /dev/null +++ b/ParentAssistant/ParentAssistant/Classes/util/AccountManager.swift @@ -0,0 +1,257 @@ +// +// account.swift +// ParentAssistant +// +// Created by 葛建军 on 2018/3/6. +// Copyright © 2018年 HANGZHOUTEAM. All rights reserved. +// + +import Foundation +class AccountManager: NSObject { + var rawUserInfo:JSON? + var userid:String="" + var token:String? + var refreshToken:String="" +// var address:String = "未知" + + + //单例 + static let shared = AccountManager() + + override init(){ + rawUserInfo=Setting.getUserInfo() + if let info=rawUserInfo{ + userid=info.contentData()["userid"].stringValue + } + } + + //MARK: - 获取个人信息 + /// 获取用户信息 + /// + /// - Returns: 返回 UserInfoModel + func getUserInfo() -> UserInfoModel { + + var model = UserInfoModel() + if let dic = Setting.getUserInfo()?.dictionary { + let data = dic["data"]?.dictionary + if let value = data { + model = UserInfoModel.deserialize(from: value)! + } + } + return model + } + //MARK: 获取孩子信息 + /// 获取用户孩子信息 + /// + /// - Returns: 返回 StudentClassInfoModel + func getChildClassInfo()-> Array { + var array = Array() + if let dic = Setting.getUserInfo()?.dictionary { + let data = dic["data"]?.dictionary + let studentArr = data!["studentClass"]?.arrayValue + for i in 0..JSON?{ + if let token=Setting.getJson("_token"){ + return token + } + return nil + } + func saveToken(tokenInfo:JSON){ + _=Setting.saveJson(tokenInfo, forKey: "_token") + } + //是否登录 + func isOnline() -> Bool { + if id() != "" { + return true + }else{ + return false + } + } + func id()->String{ + if let info=rawUserInfo{ + return info.contentData()["userid"].stringValue + } + return "" + } + func name()->String{ + if let info=rawUserInfo{ + return info.contentData()["name"].stringValue + } + return "" + } + func photo()->String{ + if let info=rawUserInfo{ + return info.contentData()["image"].stringValue + } + return "defphoto" + } + func phone()->String{ + if let info=rawUserInfo{ + return info.contentData()["mobile"].stringValue + } + return "" + } + func sex()->Int{ + if let info=rawUserInfo{ + return info.contentData()["sex"].intValue + } + return 0 + } + + func parentId()->Int{ + if let info=rawUserInfo{ + return info.contentData()["parentId"].intValue + } + return 0 + } + + func studentClass()->[JSON]{ + if let info=rawUserInfo{ + return info.contentData()["studentClass"].arrayValue + } + return [] + } + + func isNew()->Int{ + if let info=rawUserInfo{ + return info.contentData()["isNew"].intValue + } + return 0 + } + + func isHeaderTeacher()->Bool{ + if let info=rawUserInfo{ + return info.contentData()["f_Identity"].intValue == 2 ? true : false + } + return false + } + func logOut(auto:Bool? = false){ + //退出登录 + cleanUserInfoAndPoptoRootVC(auto: auto) + } + func cleanUserInfoAndPoptoRootVC(auto:Bool? = false){ + rawUserInfo=nil + userid="" + _=Setting.saveUserInfo("") + UserDefaults.standard.removeObject(forKey: "_token") + refreshToken = "" + token = "" + if auto! { + if self.appRootViewController().classForCoder==TabBarController.classForCoder(){ + ((self.appRootViewController() as! TabBarController).selectedViewController! as! UINavigationController).popToRootViewController(animated: true) + }else{ + self.appRootViewController().dismiss(animated: false, completion: { + (self.appRootViewController() as! UINavigationController).popToRootViewController(animated: true) + }) + } + } + NotificationCenter.default.post(name: NSNotification.Name(rawValue: "loginOutSuccess"), object: nil) + //取消之前注册的所有本地推送通知 +// UIApplication.shared.cancelAllLocalNotifications() + //发出刷新首页通知 +// NotificationCenter.default.post(name: NSNotification.Name(rawValue: "refreshFirstVC"), object: nil) + } + func appRootViewController()->UIViewController { + let appRootVC=UIApplication.shared.keyWindow?.rootViewController + var topVC=appRootVC + while topVC!.presentedViewController != nil { + topVC=topVC!.presentedViewController + } + return topVC! + } + func refreshUserInfo(_ mobile:String,completionHandler:((Bool) -> Void)?){ + HTTPServer.shared.getParentInfo(["mobile":mobile as AnyObject], completionHandler: { (str, error) -> Void in + if error == nil { + if JSON.fromString(str)!["status"].intValue==4 { + HTTPServer.shared.refreshToken(completionHandler: { (str, error) in + if error == nil && JSON.fromString(str)!["status"].intValue==1 { + self.setTokenInfo(tokenInfo: JSON.fromString(str)) + if let call=completionHandler{ + call(true) + } + }else{ + self.logOut() + appDelegate.window!.makeToast("登录信息已过期,请重新登录", duration: 2, position: CSToastPositionBottom) + if let call=completionHandler{ + call(false) + } + } + }, token: self.refreshToken) + }else{ + httpJsonResule(jsonString: str, error: error, successHandler: { (json) -> Void in + _=Setting.saveUserInfo(str) + self.rawUserInfo=json + self.userid=json.contentData()["userid"].stringValue + if let call=completionHandler{ + call(true) + } + }, failHandler: { (error) -> Void in + if let call=completionHandler{ + call(false) + } + }) + } + }else{ + if let call=completionHandler{ + call(false) + } + } + }) + } +} + +import HandyJSON +class UserInfoModel: HandyJSON { + var parentId = Int() + var name = String() + var bindSchoolFlag = Bool() + var mobile = String() + var image = String() + var userid = String() + var sex = Int() + required init(){} +} +class StudentClassInfoModel: HandyJSON { + + var photo = String() + var cityName = String() + var cardNumber = String() + var classId = Int() + var grade = Int() + var studentName = String() + var studentCode = String() + var parentId = Int() + var className = String() + var areaName = String() + var gradename = String() + var count = Int() + var schollId = Int() + var schoolName = String() + var studentUserId = String() + var studentId = Int() + var parentMobile = Int() + var sex = Int() + + required init(){} +} + + diff --git a/ParentAssistant/ParentAssistant/Classes/util/HTTPServer.swift b/ParentAssistant/ParentAssistant/Classes/util/HTTPServer.swift new file mode 100644 index 0000000..4c4fe19 --- /dev/null +++ b/ParentAssistant/ParentAssistant/Classes/util/HTTPServer.swift @@ -0,0 +1,315 @@ +// +// network.swift +// ParentAssistant +// +// Created by 葛建军 on 2018/3/6. +// Copyright © 2018年 HANGZHOUTEAM. All rights reserved. +// + +import Foundation +import Alamofire +import AlamofireImage +//http工具 +final class KHttp{ + private static func http(method:HTTPMethod,url:String,parameters: [String: AnyObject]? = nil,encoding: ParameterEncoding = URLEncoding.default,headers:[String: String]?=nil,completionHandler: @escaping (String?, NSError?) -> ()){ + //认证相关设置 + // let manager = Manager.sharedInstance + // manager.delegate.sessionDidReceiveChallenge = { session, challenge in + // //认证服务器证书 + // if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust { + // let serverTrust:SecTrustRef = challenge.protectionSpace.serverTrust! + // let certificate = SecTrustGetCertificateAtIndex(serverTrust, 0)! + // let remoteCertificateData = CFBridgingRetain(SecCertificateCopyData(certificate))! + // let cerPath = NSBundle.mainBundle().pathForResource("pub",ofType: "cer")! + // let localCertificateData = NSData(contentsOfFile:cerPath)! + // if (remoteCertificateData.isEqualToData(localCertificateData) == true) { + // let credential = NSURLCredential(forTrust: serverTrust) + // challenge.sender?.useCredential(credential, + // forAuthenticationChallenge: challenge) + // return (NSURLSessionAuthChallengeDisposition.UseCredential, + // NSURLCredential(forTrust: challenge.protectionSpace.serverTrust!)) + // }else{ + // return (.CancelAuthenticationChallenge, nil) + // } + // }else{ + // return (.CancelAuthenticationChallenge, nil) + // } + // } + + let requestUrl = HOST + url + request(requestUrl, method: method, parameters: parameters, encoding: encoding, headers: headers).responseString { (response) -> Void in + let error=response.result.error + let str=response.result.value + if let er=error{ + if (er as NSError).code==NSURLErrorNotConnectedToInternet{ + appDelegate.window!.makeToast("网络连接不可用", duration: 1, position: CSToastPositionBottom) + }else if (er as NSError).code==NSURLErrorCannotConnectToHost{ + appDelegate.window!.makeToast("未能连接到服务器", duration: 1, position: CSToastPositionBottom) + }else{ + appDelegate.window!.makeToast("加载失败:\(er.localizedDescription)", duration: 1, position: CSToastPositionBottom) + } + NSLog("ERROR: url:\(requestUrl),error:\(er)") + } + completionHandler(str,error as NSError?) + } + } + + static func POST(url:String,parameters: [String: AnyObject]? = nil,encoding: ParameterEncoding = URLEncoding.default,headers:[String: String]?=nil,completionHandler: @escaping (String?, NSError?) -> ()){ + var header:[String: String] + if let hd=headers { + header=hd + header.updateValue(getSign(), forKey: "sign") + }else{ + header=["sign":getSign()] + } + KHttp.http(method: .post, url: url, parameters: parameters,encoding:encoding,headers:header,completionHandler:completionHandler) + } + static func GET(url:String,parameters: [String: AnyObject]? = nil,headers:[String: String]?=nil,completionHandler: @escaping (String?, NSError?) -> Void){ + var header:[String: String] + if let hd=headers { + header=hd + header.updateValue(getSign(), forKey: "sign") + }else{ + header=["sign":getSign()] + } + KHttp.http(method: .get, url: url, parameters: parameters,headers:header,completionHandler:completionHandler) + } + static func getSign()->String{ + let timeFormatter=DateFormatter() + timeFormatter.dateFormat="yyyy-MM-dd-HH:mm:ss:sss" + let time=timeFormatter.string(from: Date())+"\(arc4random()%10000)"// let appKey="1e5b32490ad2e41ecc817849ea1310c6" + let appSecret="5d744518ac1c" + return (time.md5()+"/"+time.md5()+appSecret).md5().data(using: .ascii)?.base64EncodedString(options: []) ?? "" + } +} +final class HTTPServer{ + + //单例 + static let shared = HTTPServer() + init() {} + + var token:String?{ + return AccountManager.shared.token + } + + //上传图片 + func uploadFile(file:NSURL,progress:((Int64, Int64, Int64) -> Void)? = nil,completionHandler: @escaping (String?, NSError?) -> Void){ + upload(multipartFormData: { (multipartFormData) in + multipartFormData.append(file as URL, withName: "file") + }, usingThreshold: SessionManager.multipartFormDataEncodingMemoryThreshold, to: URL_UPLOAD_FILE, method: .post, headers: nil) { (encodingResult) in + switch encodingResult { + case .success(let upload, _, _): + upload.responseString(completionHandler: { (response) in + completionHandler(response.result.value,response.result.error as NSError?) + }) + case .failure(let encodingError): + completionHandler(nil,encodingError as NSError?) + } + } + } + //MARK:-User个人信息有关 + //登录 + func login(completionHandler:@escaping (String?, NSError?) -> (),phone:String, password:String){ + let timeFormatter=DateFormatter() + timeFormatter.dateFormat="yyyy-MM-dd-HH:mm:ss:sss" + let time=timeFormatter.string(from: Date())+"\(arc4random()%10000)" + let appSecret="5d744518ac1c" + let authorization=(time.md5()+":"+(time.md5()+appSecret).md5()).data(using: String.Encoding.ascii)?.base64EncodedString(options: Data.Base64EncodingOptions(rawValue: 0)) ?? "" + KHttp.POST(url: URL_OAUTH_TOKEN,parameters: ["grant_type":"password" as AnyObject,"username":phone as AnyObject,"password":password as AnyObject], encoding: URLEncoding.default,headers:["Authorization":"Basic "+authorization], completionHandler: completionHandler) + } + //更新token + func refreshToken(completionHandler:@escaping (String?, NSError?) -> Void,token refresh_token:String){ + let timeFormatter=DateFormatter() + timeFormatter.dateFormat="yyyy-MM-dd-HH:mm:ss:sss" + let time=timeFormatter.string(from: Date())+"\(arc4random()%10000)" + let appSecret="5d744518ac1c" + let authorization=(time.md5()+":"+(time.md5()+appSecret).md5()).data(using: String.Encoding.ascii)?.base64EncodedString(options: Data.Base64EncodingOptions(rawValue: 0)) ?? "" + KHttp.POST(url: URL_OAUTH_TOKEN, parameters:["grant_type":"refresh_token" as AnyObject,"refresh_token":refresh_token as AnyObject], headers:["Authorization":"Basic "+authorization],completionHandler: completionHandler) + } + //获取开屏广告URL + func getOpenAds(completionHandler:@escaping (String?, NSError?) -> ()){ + KHttp.GET(url: URL_GETOPENADS,headers:["Authorization":token!], completionHandler: completionHandler) + } + //我的课程提醒 + func getMyLiveRemind(completionHandler:@escaping (String?, NSError?) -> ()){ + KHttp.GET(url: URL_USER_MYLIVEREMIND, headers:["Authorization":token!], completionHandler: completionHandler) + } + //更新本地个人信息 + func uplocalUserInfo(completionHandler:@escaping (String?, NSError?) -> ()){ + KHttp.GET(url: URL_USER_USERINFO, headers:["Authorization":token!], completionHandler: completionHandler) + } + //修改密码 + func updatePassword(parameters: [String : AnyObject]?,completionHandler:@escaping (String?, NSError?) -> ()){ + KHttp.POST(url: URL_USER_UPDATEPASSWORD, parameters: parameters,headers:["Authorization":token!], completionHandler: completionHandler) + } + + + + //家长注册 + func parentRegister(parameters: [String : AnyObject]?,completionHandler:@escaping (String?, NSError?) -> ()){ + KHttp.POST(url: URL_PARENTREGISTER, parameters: parameters,headers:["Authorization":token!], completionHandler: completionHandler) + } + //获取注册验证码 + func getCaptcha(_ mobile:String,completionHandler:@escaping (String?, NSError?) -> Void){ + KHttp.GET(url: URL_CAPTCHA,parameters:["mobile":mobile as AnyObject],headers:["Authorization":token!], completionHandler: completionHandler) + } + //找回密码 + func resetPassWord(_ mobile:String,pw:String?=nil,code:String,completionHandler:@escaping (String?, NSError?) -> Void){ + var p:[String:String]! + if let pass=pw{ + p=["captcha":code,"Mobile":mobile,"pass":pass] + }else{ + p=["captcha":code,"Mobile":mobile,"pass":"Empty"] + } + //,headers:["Authorization":anonymousToken ?? ""] + + KHttp.GET(url: URL_RESTPW,parameters:p! as [String : AnyObject], completionHandler: completionHandler) + } + //登录获取家长信息(包括关联的孩子信息区分绑定状态 + func getParentInfo(_ parameters:[String:AnyObject],completionHandler:@escaping (String?, NSError?) -> ()){ + KHttp.POST(url: URL_GETPARENTINFO,parameters:parameters, headers:["Authorization":token!], completionHandler: completionHandler) + } + //更新姓名和性别 + func updateParentInfo(parameters: [String : AnyObject]?,completionHandler:@escaping (String?, NSError?) -> ()){ + KHttp.POST(url: URL_UPDATEPARENTINFO, parameters: parameters,headers:["Authorization":token!], completionHandler: completionHandler) + } + //获取我的短信包列表 + func getOrderList(_ parameters:[String:AnyObject],completionHandler:@escaping (String?, NSError?) -> ()){ + KHttp.GET(url: URL_GETORDERLIST,parameters:parameters,headers:["Authorization":token!], completionHandler: completionHandler) + } + //解绑孩子 + func getUnBindStudent(_ parameters:[String:AnyObject],completionHandler:@escaping (String?, NSError?) -> ()){ + KHttp.GET(url: URL_UNBINDSTUDENT,parameters:parameters,headers:["Authorization":token!], completionHandler: completionHandler) + } + + //根据选择的市获取该地区的学校或者根据关键字搜索学校 + func getAreaSchool(parameters: [String : AnyObject]?,completionHandler:@escaping (String?, NSError?) -> ()){ + // var urlStr = URL_GETAREASCHOOL+"?AreaName=\(getPercentEncodingString(str: parameters["AreaName"]! as! String))" + // if let str = parameters["Keyword"]{ + // urlStr = urlStr + "&Keyword=\(getPercentEncodingString(str: str as! String))" + // } + + KHttp.POST(url: URL_GETAREASCHOOL, parameters: parameters,headers:["Authorization":token!], completionHandler: completionHandler) + } + + //获取该学校的年级或班级 + func getClassOrGrade(_ parameters:[String:AnyObject],completionHandler:@escaping (String?, NSError?) -> ()){ + KHttp.GET(url: URL_GETCLASSORGRADE,parameters:parameters,headers:["Authorization":token!], completionHandler: completionHandler) + } + //MARK: ---- ParentService ----- + //获取工具入口和活动 + func getActivityTool(_ parameters:[String:AnyObject],completionHandler:@escaping (String?, NSError?) -> ()){ + KHttp.GET(url: URL_PARENTSERVICE_GETACTIVITYTOOL,parameters:parameters,headers:["Authorization":token!], completionHandler: completionHandler) + } + //绑定孩子信息(合作学校绑定返回null,非合作学校返回“汇作业”账号和密码) + func bindlingChildren(parameters: [String : AnyObject],completionHandler:@escaping (String?, NSError?) -> ()){ + KHttp.POST(url: URL_BINDLINGCHILDREN, parameters: parameters,headers:["Authorization":token!], completionHandler: completionHandler) + } + + + //获取频道资讯 + func getChannelInfo(_ parameters:[String:AnyObject],completionHandler:@escaping (String?, NSError?) -> ()){ + KHttp.POST(url: URL_PARENTSERVICE_GETCHANNELINFO,parameters:parameters,headers:["Authorization":token!], completionHandler: completionHandler) + } + + //获取首页资讯话题/搜索资讯 + func getInformationTopic(_ parameters:[String:AnyObject],completionHandler:@escaping (String?, NSError?) -> ()){ + KHttp.POST(url: URL_PARENTSERVICE_GETINFORMATIONTOPIC,parameters:parameters,headers:["Authorization":token!], completionHandler: completionHandler) + } + + //获取订购的报告或科目 + func getOrderSubject(_ parameters:[String:AnyObject],completionHandler:@escaping (String?, NSError?) -> ()){ + KHttp.GET(url: URL_PARENTSERVICE_GETORDERSUBJECT,parameters:parameters,headers:["Authorization":token!], completionHandler: completionHandler) + } + + //获取报告列表 + func workReport(parameters: [String : AnyObject]?,completionHandler:@escaping (String?, NSError?) -> ()){ + KHttp.POST(url: URL_PARENTSERVICE_WORKREPORT, parameters: parameters,headers:["Authorization":token!], completionHandler: completionHandler) + } + + //MARK: - 成长 + //MARK: 应用 + ///补卡 + func postStudentMendCard(parameters: [String : AnyObject]?,completionHandler:@escaping (String?, NSError?) -> ()){ + KHttp.POST(url: URL_POST_MEND_CARD, parameters: parameters,headers:["Authorization":token!], completionHandler: completionHandler) + } + ///考勤 + func getStudentCheckList(parameters: [String : AnyObject]?,completionHandler:@escaping (String?, NSError?) -> ()){ + KHttp.GET(url: URL_GET_ATTENDANCE_LIST, parameters: parameters,headers:["Authorization":token!], completionHandler: completionHandler) + } + //MARK:量规评价 + //获取报告详情 + func workReportDetails(parameters: [String : AnyObject]?,completionHandler:@escaping (String?, NSError?) -> ()){ + KHttp.POST(url: URL_PARENTSERVICE_WORKREPORTDETAILS, parameters: parameters,headers:["Authorization":token!], completionHandler: completionHandler) + } + //获取德育报告-总体详情 + func getEvaluationSceneAnalysis(parameters:[String:AnyObject]?,completionHandler:@escaping (String?,NSError?)->()){ + KHttp.POST(url: URL_POST_EVALUATION_ANALYSIS, parameters: parameters, headers: ["Authorization":token!], completionHandler: completionHandler) + } + //获取德育报告-场景详情 + func getEvaluationSceneAnalysisDetails(parameters:[String:AnyObject]?,completionHandler:@escaping (String?,NSError?)->()){ + KHttp.POST(url: URL_POST_EVALUATION_ANALYSIS_DETAILS, parameters: parameters, headers: ["Authorization":token!], completionHandler: completionHandler) + } + //订购信息 + func orderCenter(parameters: [String : AnyObject]?,completionHandler:@escaping (String?, NSError?) -> ()){ + KHttp.POST(url: URL_PARENTSERVICE_ORDERCENTER, parameters: parameters,headers:["Authorization":token!], completionHandler: completionHandler) + } + + //查看订购详情 + func orderServiceDetails(_ parameters:[String:AnyObject],completionHandler:@escaping (String?, NSError?) -> ()){ + KHttp.GET(url: URL_PARENTSERVICE_ORDERSERVICEDETAILS,parameters:parameters,headers:["Authorization":token!], completionHandler: completionHandler) + } + + //获取广告位信息 + func getAds(_ parameters:[String:AnyObject],completionHandler:@escaping (String?, NSError?) -> ()){ + KHttp.GET(url: URL_PARENTSERVICE_GETADS,parameters:parameters,headers:["Authorization":token!], completionHandler: completionHandler) + } + + +} +let SERVER_MESSAGE=393939 +func httpJsonResule(jsonString:String?,error:NSError?,successHandler:(JSON)->Void,failHandler:(NSError)->Void){ + let json=JSON.fromString(jsonString) + if let info=json{ + if info.isSuccess(){ + successHandler(info) + }else{ + failHandler(NSError(domain: "shunzhi.net", + code: SERVER_MESSAGE, + userInfo: [NSLocalizedDescriptionKey:info["message"].stringValue])) + } + }else{ + if let e=error{ + failHandler(e) + }else{ + failHandler(NSError(domain: "shunzhi.net", + code: 0, + userInfo: [NSLocalizedDescriptionKey:"not a json!!"])) + } + } +} + +// MARK: - 对UIImageView的网络加载图片扩展 +extension UIImageView { + + /// 网络加载图片 + /// + /// - Parameters: + /// - urlStr: 图片网络地址字符串 + /// - placeholder: 默认替代图片 + func setImageWithUrl(urlStr:String,placeholder:String?) { + if !(urlStr.isEmpty){ + let imageUrl = URL.init(string: urlStr) + if placeholder == nil { + self.af_setImage(withURL: imageUrl!) + }else{ + self.af_setImage(withURL: imageUrl!, placeholderImage: UIImage.init(named: placeholder!)) + } + }else{ + if let image = placeholder { + self.image = UIImage.init(named: image) + } + } + } +} + diff --git a/ParentAssistant/ParentAssistant/Classes/util/account.swift b/ParentAssistant/ParentAssistant/Classes/util/account.swift deleted file mode 100644 index 6d4ad49..0000000 --- a/ParentAssistant/ParentAssistant/Classes/util/account.swift +++ /dev/null @@ -1,257 +0,0 @@ -// -// account.swift -// ParentAssistant -// -// Created by 葛建军 on 2018/3/6. -// Copyright © 2018年 HANGZHOUTEAM. All rights reserved. -// - -import Foundation -class AccountManager: NSObject { - var rawUserInfo:JSON? - var userid:String="" - var token:String? - var refreshToken:String="" -// var address:String = "未知" - - - //单例 - static let shared = AccountManager() - - override init(){ - rawUserInfo=Setting.getUserInfo() - if let info=rawUserInfo{ - userid=info.contentData()["userid"].stringValue - } - } - - //MARK: - 获取个人信息 - /// 获取用户信息 - /// - /// - Returns: 返回 UserInfoModel - func getUserInfo() -> UserInfoModel { - - var model = UserInfoModel() - if let dic = Setting.getUserInfo()?.dictionary { - let data = dic["data"]?.dictionary - if let value = data { - model = UserInfoModel.deserialize(from: value)! - } - } - return model - } - //MARK: 获取孩子信息 - /// 获取用户孩子信息 - /// - /// - Returns: 返回 StudentClassInfoModel - func getChildClassInfo()-> Array { - var array = Array() - if let dic = Setting.getUserInfo()?.dictionary { - let data = dic["data"]?.dictionary - let studentArr = data!["studentClass"]?.arrayValue - for i in 0..JSON?{ - if let token=Setting.getJson("_token"){ - return token - } - return nil - } - func saveToken(tokenInfo:JSON){ - _=Setting.saveJson(tokenInfo, forKey: "_token") - } - //是否登录 - func isOnline() -> Bool { - if id() != "" { - return true - }else{ - return false - } - } - func id()->String{ - if let info=rawUserInfo{ - return info.contentData()["userid"].stringValue - } - return "" - } - func name()->String{ - if let info=rawUserInfo{ - return info.contentData()["name"].stringValue - } - return "" - } - func photo()->String{ - if let info=rawUserInfo{ - return info.contentData()["image"].stringValue - } - return "defphoto" - } - func phone()->String{ - if let info=rawUserInfo{ - return info.contentData()["mobile"].stringValue - } - return "" - } - func sex()->Int{ - if let info=rawUserInfo{ - return info.contentData()["sex"].intValue - } - return 0 - } - - func parentId()->Int{ - if let info=rawUserInfo{ - return info.contentData()["parentId"].intValue - } - return 0 - } - - func studentClass()->[JSON]{ - if let info=rawUserInfo{ - return info.contentData()["studentClass"].arrayValue - } - return [] - } - - func isNew()->Int{ - if let info=rawUserInfo{ - return info.contentData()["isNew"].intValue - } - return 0 - } - - func isHeaderTeacher()->Bool{ - if let info=rawUserInfo{ - return info.contentData()["f_Identity"].intValue == 2 ? true : false - } - return false - } - func logOut(auto:Bool? = false){ - //退出登录 - cleanUserInfoAndPoptoRootVC(auto: auto) - } - func cleanUserInfoAndPoptoRootVC(auto:Bool? = false){ - rawUserInfo=nil - userid="" - _=Setting.saveUserInfo("") - UserDefaults.standard.removeObject(forKey: "_token") - refreshToken = "" - token = "" - if auto! { - if self.appRootViewController().classForCoder==TabBarController.classForCoder(){ - ((self.appRootViewController() as! TabBarController).selectedViewController! as! UINavigationController).popToRootViewController(animated: true) - }else{ - self.appRootViewController().dismiss(animated: false, completion: { - (self.appRootViewController() as! UINavigationController).popToRootViewController(animated: true) - }) - } - } - NotificationCenter.default.post(name: NSNotification.Name(rawValue: "loginOutSuccess"), object: nil) - //取消之前注册的所有本地推送通知 -// UIApplication.shared.cancelAllLocalNotifications() - //发出刷新首页通知 -// NotificationCenter.default.post(name: NSNotification.Name(rawValue: "refreshFirstVC"), object: nil) - } - func appRootViewController()->UIViewController { - let appRootVC=UIApplication.shared.keyWindow?.rootViewController - var topVC=appRootVC - while topVC!.presentedViewController != nil { - topVC=topVC!.presentedViewController - } - return topVC! - } - func refreshUserInfo(_ mobile:String,completionHandler:((Bool) -> Void)?){ - HTTPServer.shared.getParentInfo(["mobile":mobile as AnyObject], completionHandler: { (str, error) -> Void in - if error == nil { - if JSON.fromString(str)!["status"].intValue==4 { - HTTPServer.shared.refreshToken(completionHandler: { (str, error) in - if error == nil && JSON.fromString(str)!["status"].intValue==1 { - self.setTokenInfo(tokenInfo: JSON.fromString(str)) - if let call=completionHandler{ - call(true) - } - }else{ - self.logOut() - appDelegate.window!.makeToast("登录信息已过期,请重新登录", duration: 2, position: CSToastPositionBottom) - if let call=completionHandler{ - call(false) - } - } - }, token: self.refreshToken) - }else{ - httpJsonResule(jsonString: str, error: error, successHandler: { (json) -> Void in - _=Setting.saveUserInfo(str) - self.rawUserInfo=json - self.userid=json.contentData()["userid"].stringValue - if let call=completionHandler{ - call(true) - } - }, failHandler: { (error) -> Void in - if let call=completionHandler{ - call(false) - } - }) - } - }else{ - if let call=completionHandler{ - call(false) - } - } - }) - } -} - -import HandyJSON -class UserInfoModel: HandyJSON { - var parentId = Int() - var name = String() - var bindSchoolFlag = Bool() - var mobile = String() - var image = String() - var userid = String() - var sex = Int() - required init(){} -} -class StudentClassInfoModel: HandyJSON { - - var photo = String() - var cityName = String() - var cardNumber = String() - var classId = Int() - var grade = Int() - var studentName = String() - var studentCode = String() - var parentId = Int() - var className = String() - var areaName = String() - var gradename = String() - var count = Int() - var schollId = Int() - var schoolName = String() - var studentUserId = String() - var studentId = Int() - var parentMobile = Int() - var sex = Int() - - required init(){} -} - - diff --git a/ParentAssistant/ParentAssistant/Classes/util/network.swift b/ParentAssistant/ParentAssistant/Classes/util/network.swift deleted file mode 100644 index 4c4fe19..0000000 --- a/ParentAssistant/ParentAssistant/Classes/util/network.swift +++ /dev/null @@ -1,315 +0,0 @@ -// -// network.swift -// ParentAssistant -// -// Created by 葛建军 on 2018/3/6. -// Copyright © 2018年 HANGZHOUTEAM. All rights reserved. -// - -import Foundation -import Alamofire -import AlamofireImage -//http工具 -final class KHttp{ - private static func http(method:HTTPMethod,url:String,parameters: [String: AnyObject]? = nil,encoding: ParameterEncoding = URLEncoding.default,headers:[String: String]?=nil,completionHandler: @escaping (String?, NSError?) -> ()){ - //认证相关设置 - // let manager = Manager.sharedInstance - // manager.delegate.sessionDidReceiveChallenge = { session, challenge in - // //认证服务器证书 - // if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust { - // let serverTrust:SecTrustRef = challenge.protectionSpace.serverTrust! - // let certificate = SecTrustGetCertificateAtIndex(serverTrust, 0)! - // let remoteCertificateData = CFBridgingRetain(SecCertificateCopyData(certificate))! - // let cerPath = NSBundle.mainBundle().pathForResource("pub",ofType: "cer")! - // let localCertificateData = NSData(contentsOfFile:cerPath)! - // if (remoteCertificateData.isEqualToData(localCertificateData) == true) { - // let credential = NSURLCredential(forTrust: serverTrust) - // challenge.sender?.useCredential(credential, - // forAuthenticationChallenge: challenge) - // return (NSURLSessionAuthChallengeDisposition.UseCredential, - // NSURLCredential(forTrust: challenge.protectionSpace.serverTrust!)) - // }else{ - // return (.CancelAuthenticationChallenge, nil) - // } - // }else{ - // return (.CancelAuthenticationChallenge, nil) - // } - // } - - let requestUrl = HOST + url - request(requestUrl, method: method, parameters: parameters, encoding: encoding, headers: headers).responseString { (response) -> Void in - let error=response.result.error - let str=response.result.value - if let er=error{ - if (er as NSError).code==NSURLErrorNotConnectedToInternet{ - appDelegate.window!.makeToast("网络连接不可用", duration: 1, position: CSToastPositionBottom) - }else if (er as NSError).code==NSURLErrorCannotConnectToHost{ - appDelegate.window!.makeToast("未能连接到服务器", duration: 1, position: CSToastPositionBottom) - }else{ - appDelegate.window!.makeToast("加载失败:\(er.localizedDescription)", duration: 1, position: CSToastPositionBottom) - } - NSLog("ERROR: url:\(requestUrl),error:\(er)") - } - completionHandler(str,error as NSError?) - } - } - - static func POST(url:String,parameters: [String: AnyObject]? = nil,encoding: ParameterEncoding = URLEncoding.default,headers:[String: String]?=nil,completionHandler: @escaping (String?, NSError?) -> ()){ - var header:[String: String] - if let hd=headers { - header=hd - header.updateValue(getSign(), forKey: "sign") - }else{ - header=["sign":getSign()] - } - KHttp.http(method: .post, url: url, parameters: parameters,encoding:encoding,headers:header,completionHandler:completionHandler) - } - static func GET(url:String,parameters: [String: AnyObject]? = nil,headers:[String: String]?=nil,completionHandler: @escaping (String?, NSError?) -> Void){ - var header:[String: String] - if let hd=headers { - header=hd - header.updateValue(getSign(), forKey: "sign") - }else{ - header=["sign":getSign()] - } - KHttp.http(method: .get, url: url, parameters: parameters,headers:header,completionHandler:completionHandler) - } - static func getSign()->String{ - let timeFormatter=DateFormatter() - timeFormatter.dateFormat="yyyy-MM-dd-HH:mm:ss:sss" - let time=timeFormatter.string(from: Date())+"\(arc4random()%10000)"// let appKey="1e5b32490ad2e41ecc817849ea1310c6" - let appSecret="5d744518ac1c" - return (time.md5()+"/"+time.md5()+appSecret).md5().data(using: .ascii)?.base64EncodedString(options: []) ?? "" - } -} -final class HTTPServer{ - - //单例 - static let shared = HTTPServer() - init() {} - - var token:String?{ - return AccountManager.shared.token - } - - //上传图片 - func uploadFile(file:NSURL,progress:((Int64, Int64, Int64) -> Void)? = nil,completionHandler: @escaping (String?, NSError?) -> Void){ - upload(multipartFormData: { (multipartFormData) in - multipartFormData.append(file as URL, withName: "file") - }, usingThreshold: SessionManager.multipartFormDataEncodingMemoryThreshold, to: URL_UPLOAD_FILE, method: .post, headers: nil) { (encodingResult) in - switch encodingResult { - case .success(let upload, _, _): - upload.responseString(completionHandler: { (response) in - completionHandler(response.result.value,response.result.error as NSError?) - }) - case .failure(let encodingError): - completionHandler(nil,encodingError as NSError?) - } - } - } - //MARK:-User个人信息有关 - //登录 - func login(completionHandler:@escaping (String?, NSError?) -> (),phone:String, password:String){ - let timeFormatter=DateFormatter() - timeFormatter.dateFormat="yyyy-MM-dd-HH:mm:ss:sss" - let time=timeFormatter.string(from: Date())+"\(arc4random()%10000)" - let appSecret="5d744518ac1c" - let authorization=(time.md5()+":"+(time.md5()+appSecret).md5()).data(using: String.Encoding.ascii)?.base64EncodedString(options: Data.Base64EncodingOptions(rawValue: 0)) ?? "" - KHttp.POST(url: URL_OAUTH_TOKEN,parameters: ["grant_type":"password" as AnyObject,"username":phone as AnyObject,"password":password as AnyObject], encoding: URLEncoding.default,headers:["Authorization":"Basic "+authorization], completionHandler: completionHandler) - } - //更新token - func refreshToken(completionHandler:@escaping (String?, NSError?) -> Void,token refresh_token:String){ - let timeFormatter=DateFormatter() - timeFormatter.dateFormat="yyyy-MM-dd-HH:mm:ss:sss" - let time=timeFormatter.string(from: Date())+"\(arc4random()%10000)" - let appSecret="5d744518ac1c" - let authorization=(time.md5()+":"+(time.md5()+appSecret).md5()).data(using: String.Encoding.ascii)?.base64EncodedString(options: Data.Base64EncodingOptions(rawValue: 0)) ?? "" - KHttp.POST(url: URL_OAUTH_TOKEN, parameters:["grant_type":"refresh_token" as AnyObject,"refresh_token":refresh_token as AnyObject], headers:["Authorization":"Basic "+authorization],completionHandler: completionHandler) - } - //获取开屏广告URL - func getOpenAds(completionHandler:@escaping (String?, NSError?) -> ()){ - KHttp.GET(url: URL_GETOPENADS,headers:["Authorization":token!], completionHandler: completionHandler) - } - //我的课程提醒 - func getMyLiveRemind(completionHandler:@escaping (String?, NSError?) -> ()){ - KHttp.GET(url: URL_USER_MYLIVEREMIND, headers:["Authorization":token!], completionHandler: completionHandler) - } - //更新本地个人信息 - func uplocalUserInfo(completionHandler:@escaping (String?, NSError?) -> ()){ - KHttp.GET(url: URL_USER_USERINFO, headers:["Authorization":token!], completionHandler: completionHandler) - } - //修改密码 - func updatePassword(parameters: [String : AnyObject]?,completionHandler:@escaping (String?, NSError?) -> ()){ - KHttp.POST(url: URL_USER_UPDATEPASSWORD, parameters: parameters,headers:["Authorization":token!], completionHandler: completionHandler) - } - - - - //家长注册 - func parentRegister(parameters: [String : AnyObject]?,completionHandler:@escaping (String?, NSError?) -> ()){ - KHttp.POST(url: URL_PARENTREGISTER, parameters: parameters,headers:["Authorization":token!], completionHandler: completionHandler) - } - //获取注册验证码 - func getCaptcha(_ mobile:String,completionHandler:@escaping (String?, NSError?) -> Void){ - KHttp.GET(url: URL_CAPTCHA,parameters:["mobile":mobile as AnyObject],headers:["Authorization":token!], completionHandler: completionHandler) - } - //找回密码 - func resetPassWord(_ mobile:String,pw:String?=nil,code:String,completionHandler:@escaping (String?, NSError?) -> Void){ - var p:[String:String]! - if let pass=pw{ - p=["captcha":code,"Mobile":mobile,"pass":pass] - }else{ - p=["captcha":code,"Mobile":mobile,"pass":"Empty"] - } - //,headers:["Authorization":anonymousToken ?? ""] - - KHttp.GET(url: URL_RESTPW,parameters:p! as [String : AnyObject], completionHandler: completionHandler) - } - //登录获取家长信息(包括关联的孩子信息区分绑定状态 - func getParentInfo(_ parameters:[String:AnyObject],completionHandler:@escaping (String?, NSError?) -> ()){ - KHttp.POST(url: URL_GETPARENTINFO,parameters:parameters, headers:["Authorization":token!], completionHandler: completionHandler) - } - //更新姓名和性别 - func updateParentInfo(parameters: [String : AnyObject]?,completionHandler:@escaping (String?, NSError?) -> ()){ - KHttp.POST(url: URL_UPDATEPARENTINFO, parameters: parameters,headers:["Authorization":token!], completionHandler: completionHandler) - } - //获取我的短信包列表 - func getOrderList(_ parameters:[String:AnyObject],completionHandler:@escaping (String?, NSError?) -> ()){ - KHttp.GET(url: URL_GETORDERLIST,parameters:parameters,headers:["Authorization":token!], completionHandler: completionHandler) - } - //解绑孩子 - func getUnBindStudent(_ parameters:[String:AnyObject],completionHandler:@escaping (String?, NSError?) -> ()){ - KHttp.GET(url: URL_UNBINDSTUDENT,parameters:parameters,headers:["Authorization":token!], completionHandler: completionHandler) - } - - //根据选择的市获取该地区的学校或者根据关键字搜索学校 - func getAreaSchool(parameters: [String : AnyObject]?,completionHandler:@escaping (String?, NSError?) -> ()){ - // var urlStr = URL_GETAREASCHOOL+"?AreaName=\(getPercentEncodingString(str: parameters["AreaName"]! as! String))" - // if let str = parameters["Keyword"]{ - // urlStr = urlStr + "&Keyword=\(getPercentEncodingString(str: str as! String))" - // } - - KHttp.POST(url: URL_GETAREASCHOOL, parameters: parameters,headers:["Authorization":token!], completionHandler: completionHandler) - } - - //获取该学校的年级或班级 - func getClassOrGrade(_ parameters:[String:AnyObject],completionHandler:@escaping (String?, NSError?) -> ()){ - KHttp.GET(url: URL_GETCLASSORGRADE,parameters:parameters,headers:["Authorization":token!], completionHandler: completionHandler) - } - //MARK: ---- ParentService ----- - //获取工具入口和活动 - func getActivityTool(_ parameters:[String:AnyObject],completionHandler:@escaping (String?, NSError?) -> ()){ - KHttp.GET(url: URL_PARENTSERVICE_GETACTIVITYTOOL,parameters:parameters,headers:["Authorization":token!], completionHandler: completionHandler) - } - //绑定孩子信息(合作学校绑定返回null,非合作学校返回“汇作业”账号和密码) - func bindlingChildren(parameters: [String : AnyObject],completionHandler:@escaping (String?, NSError?) -> ()){ - KHttp.POST(url: URL_BINDLINGCHILDREN, parameters: parameters,headers:["Authorization":token!], completionHandler: completionHandler) - } - - - //获取频道资讯 - func getChannelInfo(_ parameters:[String:AnyObject],completionHandler:@escaping (String?, NSError?) -> ()){ - KHttp.POST(url: URL_PARENTSERVICE_GETCHANNELINFO,parameters:parameters,headers:["Authorization":token!], completionHandler: completionHandler) - } - - //获取首页资讯话题/搜索资讯 - func getInformationTopic(_ parameters:[String:AnyObject],completionHandler:@escaping (String?, NSError?) -> ()){ - KHttp.POST(url: URL_PARENTSERVICE_GETINFORMATIONTOPIC,parameters:parameters,headers:["Authorization":token!], completionHandler: completionHandler) - } - - //获取订购的报告或科目 - func getOrderSubject(_ parameters:[String:AnyObject],completionHandler:@escaping (String?, NSError?) -> ()){ - KHttp.GET(url: URL_PARENTSERVICE_GETORDERSUBJECT,parameters:parameters,headers:["Authorization":token!], completionHandler: completionHandler) - } - - //获取报告列表 - func workReport(parameters: [String : AnyObject]?,completionHandler:@escaping (String?, NSError?) -> ()){ - KHttp.POST(url: URL_PARENTSERVICE_WORKREPORT, parameters: parameters,headers:["Authorization":token!], completionHandler: completionHandler) - } - - //MARK: - 成长 - //MARK: 应用 - ///补卡 - func postStudentMendCard(parameters: [String : AnyObject]?,completionHandler:@escaping (String?, NSError?) -> ()){ - KHttp.POST(url: URL_POST_MEND_CARD, parameters: parameters,headers:["Authorization":token!], completionHandler: completionHandler) - } - ///考勤 - func getStudentCheckList(parameters: [String : AnyObject]?,completionHandler:@escaping (String?, NSError?) -> ()){ - KHttp.GET(url: URL_GET_ATTENDANCE_LIST, parameters: parameters,headers:["Authorization":token!], completionHandler: completionHandler) - } - //MARK:量规评价 - //获取报告详情 - func workReportDetails(parameters: [String : AnyObject]?,completionHandler:@escaping (String?, NSError?) -> ()){ - KHttp.POST(url: URL_PARENTSERVICE_WORKREPORTDETAILS, parameters: parameters,headers:["Authorization":token!], completionHandler: completionHandler) - } - //获取德育报告-总体详情 - func getEvaluationSceneAnalysis(parameters:[String:AnyObject]?,completionHandler:@escaping (String?,NSError?)->()){ - KHttp.POST(url: URL_POST_EVALUATION_ANALYSIS, parameters: parameters, headers: ["Authorization":token!], completionHandler: completionHandler) - } - //获取德育报告-场景详情 - func getEvaluationSceneAnalysisDetails(parameters:[String:AnyObject]?,completionHandler:@escaping (String?,NSError?)->()){ - KHttp.POST(url: URL_POST_EVALUATION_ANALYSIS_DETAILS, parameters: parameters, headers: ["Authorization":token!], completionHandler: completionHandler) - } - //订购信息 - func orderCenter(parameters: [String : AnyObject]?,completionHandler:@escaping (String?, NSError?) -> ()){ - KHttp.POST(url: URL_PARENTSERVICE_ORDERCENTER, parameters: parameters,headers:["Authorization":token!], completionHandler: completionHandler) - } - - //查看订购详情 - func orderServiceDetails(_ parameters:[String:AnyObject],completionHandler:@escaping (String?, NSError?) -> ()){ - KHttp.GET(url: URL_PARENTSERVICE_ORDERSERVICEDETAILS,parameters:parameters,headers:["Authorization":token!], completionHandler: completionHandler) - } - - //获取广告位信息 - func getAds(_ parameters:[String:AnyObject],completionHandler:@escaping (String?, NSError?) -> ()){ - KHttp.GET(url: URL_PARENTSERVICE_GETADS,parameters:parameters,headers:["Authorization":token!], completionHandler: completionHandler) - } - - -} -let SERVER_MESSAGE=393939 -func httpJsonResule(jsonString:String?,error:NSError?,successHandler:(JSON)->Void,failHandler:(NSError)->Void){ - let json=JSON.fromString(jsonString) - if let info=json{ - if info.isSuccess(){ - successHandler(info) - }else{ - failHandler(NSError(domain: "shunzhi.net", - code: SERVER_MESSAGE, - userInfo: [NSLocalizedDescriptionKey:info["message"].stringValue])) - } - }else{ - if let e=error{ - failHandler(e) - }else{ - failHandler(NSError(domain: "shunzhi.net", - code: 0, - userInfo: [NSLocalizedDescriptionKey:"not a json!!"])) - } - } -} - -// MARK: - 对UIImageView的网络加载图片扩展 -extension UIImageView { - - /// 网络加载图片 - /// - /// - Parameters: - /// - urlStr: 图片网络地址字符串 - /// - placeholder: 默认替代图片 - func setImageWithUrl(urlStr:String,placeholder:String?) { - if !(urlStr.isEmpty){ - let imageUrl = URL.init(string: urlStr) - if placeholder == nil { - self.af_setImage(withURL: imageUrl!) - }else{ - self.af_setImage(withURL: imageUrl!, placeholderImage: UIImage.init(named: placeholder!)) - } - }else{ - if let image = placeholder { - self.image = UIImage.init(named: image) - } - } - } -} - diff --git a/ParentAssistant/ParentAssistant/Classes/util/utils.swift b/ParentAssistant/ParentAssistant/Classes/util/utils.swift index 9dfc573..e6eaab9 100644 --- a/ParentAssistant/ParentAssistant/Classes/util/utils.swift +++ b/ParentAssistant/ParentAssistant/Classes/util/utils.swift @@ -207,7 +207,8 @@ extension String{ for i in 0 ..< digestLen { hash.appendFormat("%02x", result[i]) } - result.deinitialize() +// result.deinitialize() + result.deinitialize(count: digestLen) return hash.uppercased } } -- libgit2 0.21.0