git.iko.soy/dashared/GDproject
on master help sign in
still working on denis new version. channels can be listed. a lot to be done on channels. almost moved to new API
8cecd53Darya Rednikina
GDproject/Controller/ News and channels/ChannelController.swift+90−36
@@ -9,7 +9,12 @@
9import UIKit
9import UIKit
10
10
11protocol DataDelegate {
11protocol DataDelegate {
12− func passData(for row: Int, channel: Channel)
12+ func passData(for row: Int, channel: Model.Channels)
13+}
14+
15+enum ActiveTable {
16+ case tags
17+ case people
13}
18}
14
19
15class ChannelController: UIViewController, UITableViewDelegate, UITableViewDataSource, UITextFieldDelegate, UISearchBarDelegate
20class ChannelController: UIViewController, UITableViewDelegate, UITableViewDataSource, UITextFieldDelegate, UISearchBarDelegate
@@ -17,12 +22,15 @@ class ChannelController: UIViewController, UITableViewDelegate, UITableViewDataS
17 @IBOutlet weak var tableView: UITableView!
22 @IBOutlet weak var tableView: UITableView!
18
23
19 var index: Int?
24 var index: Int?
20− var channel: Channel?
25+ var channel: Model.Channels?
21 var myProtocol: DataDelegate?
26 var myProtocol: DataDelegate?
22
27
23− var dataSource: [String] = []
28+ var dataSourcePeople: [Int] = []
29+ var dataSourceTags: [String] = []
30+
31+ var activeDataSource: ActiveTable = .people
24
32
25− var fullPeople: [String] = ["Other Ann", "Other Ilya", "Other Kostya", "Pasha", "Valera"]
33+ var fullPeople: [Int] = [5051,69]
26
34
27 var fullTags: [String] = ["# happy", "# sad", "# meme", "# shershakov", "# pupsik"]
35 var fullTags: [String] = ["# happy", "# sad", "# meme", "# shershakov", "# pupsik"]
28
36
@@ -32,22 +40,30 @@ class ChannelController: UIViewController, UITableViewDelegate, UITableViewDataS
32
40
33 override func viewDidLoad() {
41 override func viewDidLoad() {
34 super.viewDidLoad()
42 super.viewDidLoad()
43+
44+ dataSourcePeople = channel!.people
45+ dataSourceTags = channel!.tags
46+
35 tableView.delegate = self
47 tableView.delegate = self
36 tableView.dataSource = self
48 tableView.dataSource = self
37− dataSource = channel!.people
38 tableView.register(UITableViewCell.self, forCellReuseIdentifier: itemCellId)
49 tableView.register(UITableViewCell.self, forCellReuseIdentifier: itemCellId)
39 tableView.reloadData()
50 tableView.reloadData()
40 textField.delegate = self
51 textField.delegate = self
41 searchBar.delegate = self
52 searchBar.delegate = self
42 searchBar.selectedScopeButtonIndex = 0
53 searchBar.selectedScopeButtonIndex = 0
54+
43− navigationItem.title = channel?.title
55+ navigationItem.title = channel?.name
44− textField.placeholder = channel?.title
56+ textField.placeholder = channel?.name
57+
45 textField.addTarget(self, action: #selector(changedText(_:)), for: .editingChanged)
58 textField.addTarget(self, action: #selector(changedText(_:)), for: .editingChanged)
46 }
59 }
47
60
61+ override func viewWillDisappear(_ animated: Bool) {
62+ Model.createChannel(with: channel!)
63+ }
48 @objc func changedText(_ textField: UITextField){
64 @objc func changedText(_ textField: UITextField){
49 navigationItem.title = textField.text
65 navigationItem.title = textField.text
50− channel?.title = textField.text!
66+ channel?.name = textField.text!
51 myProtocol?.passData(for: index!, channel: channel!)
67 myProtocol?.passData(for: index!, channel: channel!)
52 }
68 }
53
69
@@ -56,7 +72,12 @@ class ChannelController: UIViewController, UITableViewDelegate, UITableViewDataS
56 }
72 }
57
73
58 func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
74 func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
75+ switch activeDataSource {
76+ case .people:
59− return dataSource.count
77+ return dataSourcePeople.count
78+ case .tags:
79+ return dataSourceTags.count
80+ }
60 }
81 }
61
82
62 func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
83 func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
@@ -67,11 +88,11 @@ class ChannelController: UIViewController, UITableViewDelegate, UITableViewDataS
67 if cell.accessoryType == .none{
88 if cell.accessoryType == .none{
68 switch searchBar.selectedScopeButtonIndex{
89 switch searchBar.selectedScopeButtonIndex{
69 case 0:
90 case 0:
70− channel?.people.append(dataSource[indexPath.row])
91+ channel?.people.append(dataSourcePeople[indexPath.row])
71 print("people = \(channel!.people)")
92 print("people = \(channel!.people)")
72 case 1:
93 case 1:
73− channel?.hashtags.append(dataSource[indexPath.row])
94+ channel?.tags.append(dataSourceTags[indexPath.row])
74− print("hashtags = \(channel!.hashtags)")
95+ print("hashtags = \(channel!.tags)")
75 default:
96 default:
76 break
97 break
77 }
98 }
@@ -82,12 +103,10 @@ class ChannelController: UIViewController, UITableViewDelegate, UITableViewDataS
82
103
83 switch searchBar.selectedScopeButtonIndex{
104 switch searchBar.selectedScopeButtonIndex{
84 case 0:
105 case 0:
85− channel?.people = channel!.people.filter({ (s) -> Bool in
106+ channel?.people = channel!.people.filter{ $0 == fullPeople[indexPath.row] }
86− !fullPeople[indexPath.row].contains(s)
87− })
88 // TODO: dataPass
107 // TODO: dataPass
89 case 1:
108 case 1:
90− channel?.hashtags = channel!.hashtags.filter({ (s) -> Bool in
109+ channel?.tags = channel!.tags.filter({ (s) -> Bool in
91 !fullTags[indexPath.row].contains(s)
110 !fullTags[indexPath.row].contains(s)
92 })
111 })
93 // TODO: dataPass
112 // TODO: dataPass
@@ -99,13 +118,18 @@ class ChannelController: UIViewController, UITableViewDelegate, UITableViewDataS
99 } else
118 } else
100 {
119 {
101 tableView.beginUpdates()
120 tableView.beginUpdates()
121+ switch activeDataSource{
122+ case .people:
123+ dataSourcePeople.remove(at: indexPath.row)
124+ case .tags:
102− dataSource.remove(at: indexPath.row)
125+ dataSourceTags.remove(at: indexPath.row)
126+ }
103 switch searchBar.selectedScopeButtonIndex{
127 switch searchBar.selectedScopeButtonIndex{
104 case 0:
128 case 0:
105 channel?.people.remove(at: indexPath.row)
129 channel?.people.remove(at: indexPath.row)
106 // TODO: dataPass
130 // TODO: dataPass
107 case 1:
131 case 1:
108− channel?.hashtags.remove(at: indexPath.row)
132+ channel?.tags.remove(at: indexPath.row)
109 // TODO: dataPass
133 // TODO: dataPass
110 default:
134 default:
111 break
135 break
@@ -118,10 +142,11 @@ class ChannelController: UIViewController, UITableViewDelegate, UITableViewDataS
118 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
142 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
119 let cell = tableView.dequeueReusableCell(withIdentifier: itemCellId, for: indexPath)
143 let cell = tableView.dequeueReusableCell(withIdentifier: itemCellId, for: indexPath)
120
144
121− cell.textLabel?.text = dataSource[indexPath.row]
145+ cell.textLabel?.text = activeDataSource == .people ? String(dataSourcePeople[indexPath.row]) : dataSourceTags[indexPath.row]
122 cell.selectionStyle = .none
146 cell.selectionStyle = .none
123
147
148+ if activeDataSource == .tags && channel!.tags.contains(dataSourceTags[indexPath.row]) ||
124− if channel!.hashtags.contains(dataSource[indexPath.row]) || channel!.people.contains(dataSource[indexPath.row])
149+ activeDataSource == .people && channel!.people.contains(dataSourcePeople[indexPath.row])
125 {
150 {
126 cell.accessoryType = .checkmark
151 cell.accessoryType = .checkmark
127 } else {
152 } else {
@@ -147,7 +172,7 @@ class ChannelController: UIViewController, UITableViewDelegate, UITableViewDataS
147 {
172 {
148 let view = UIView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 70))
173 let view = UIView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 70))
149
174
150− if flag {
175+ if activeDataSource == .tags {
151 searchBar.selectedScopeButtonIndex = 1
176 searchBar.selectedScopeButtonIndex = 1
152 } else {
177 } else {
153 searchBar.selectedScopeButtonIndex = 0
178 searchBar.selectedScopeButtonIndex = 0
@@ -165,7 +190,12 @@ class ChannelController: UIViewController, UITableViewDelegate, UITableViewDataS
165
190
166 func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
191 func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
167 if searchText.isEmpty {
192 if searchText.isEmpty {
168− dataSource = searchBar.selectedScopeButtonIndex == 0 ? fullPeople : fullTags
193+ switch activeDataSource{
194+ case .people:
195+ dataSourcePeople = fullPeople
196+ case .tags:
197+ dataSourceTags = fullTags
198+ }
169 tableView.reloadData()
199 tableView.reloadData()
170 } else {
200 } else {
171 filterTableView(ind: searchBar.selectedScopeButtonIndex, text: searchText)
201 filterTableView(ind: searchBar.selectedScopeButtonIndex, text: searchText)
@@ -175,12 +205,10 @@ class ChannelController: UIViewController, UITableViewDelegate, UITableViewDataS
175 func filterTableView(ind: Int, text: String){
205 func filterTableView(ind: Int, text: String){
176 switch ind {
206 switch ind {
177 case 0:
207 case 0:
178− dataSource = fullPeople.filter({ (s) -> Bool in
208+ dataSourcePeople = fullPeople.filter { if let numb = Int(text) { return $0 == numb } else {return false}}
179− s.lowercased().contains(text.lowercased())
180− })
181 tableView.reloadData()
209 tableView.reloadData()
182 case 1:
210 case 1:
183− dataSource = fullTags.filter({ (s) -> Bool in
211+ dataSourceTags = fullTags.filter({ (s) -> Bool in
184 s.lowercased().contains(text.lowercased())
212 s.lowercased().contains(text.lowercased())
185 })
213 })
186 tableView.reloadData()
214 tableView.reloadData()
@@ -189,33 +217,59 @@ class ChannelController: UIViewController, UITableViewDelegate, UITableViewDataS
189 }
217 }
190 }
218 }
191
219
192− var flag = false
193−
194 func searchBar(_ searchBar: UISearchBar, selectedScopeButtonIndexDidChange selectedScope: Int) {
220 func searchBar(_ searchBar: UISearchBar, selectedScopeButtonIndexDidChange selectedScope: Int) {
195 if searchBar.isFirstResponder {
221 if searchBar.isFirstResponder {
196− dataSource = searchBar.selectedScopeButtonIndex == 0 ? fullPeople : fullTags
222+ switch activeDataSource{
223+ case .people :
224+ dataSourcePeople = fullPeople
225+ dataSourceTags = []
226+ case .tags:
227+ dataSourceTags = fullTags
228+ dataSourcePeople = []
229+ }
197− flag = searchBar.selectedScopeButtonIndex == 0 ? false : true
230+ activeDataSource = searchBar.selectedScopeButtonIndex == 0 ? .people : .tags
198 if (!(searchBar.text?.isEmpty ?? true))
231 if (!(searchBar.text?.isEmpty ?? true))
199 {
232 {
200 filterTableView(ind: selectedScope, text: searchBar.text!)
233 filterTableView(ind: selectedScope, text: searchBar.text!)
201 }
234 }
202 tableView.reloadData()
235 tableView.reloadData()
203 } else if !(searchBar.isFirstResponder){
236 } else if !(searchBar.isFirstResponder){
204− dataSource = searchBar.selectedScopeButtonIndex == 0 ? channel!.people : channel!.hashtags
237+ switch activeDataSource{
238+ case .people :
239+ dataSourcePeople = channel!.people
240+ dataSourceTags = []
241+ case .tags:
242+ dataSourceTags = channel!.tags
243+ dataSourcePeople = []
244+ }
205− flag = searchBar.selectedScopeButtonIndex == 0 ? false : true
245+ activeDataSource = searchBar.selectedScopeButtonIndex == 0 ? .people : .tags
206 tableView.reloadData()
246 tableView.reloadData()
207 }
247 }
208 }
248 }
209
249
210 func searchBarTextDidEndEditing(_ searchBar: UISearchBar) {
250 func searchBarTextDidEndEditing(_ searchBar: UISearchBar) {
211− dataSource = searchBar.selectedScopeButtonIndex == 0 ? channel!.people : channel!.hashtags
251+ switch activeDataSource{
252+ case .people :
253+ dataSourcePeople = channel!.people
254+ dataSourceTags = []
255+ case .tags:
256+ dataSourceTags = channel!.tags
257+ dataSourcePeople = []
258+ }
212− flag = searchBar.selectedScopeButtonIndex == 0 ? false : true
259+ activeDataSource = searchBar.selectedScopeButtonIndex == 0 ? .people : .tags
213 tableView.reloadData()
260 tableView.reloadData()
214 }
261 }
215
262
216 func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
263 func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
217− dataSource = searchBar.selectedScopeButtonIndex == 0 ? fullPeople : fullTags
264+ switch activeDataSource{
265+ case .people :
266+ dataSourcePeople = fullPeople
267+ dataSourceTags = []
268+ case .tags:
269+ dataSourceTags = fullTags
270+ dataSourcePeople = []
271+ }
218− flag = searchBar.selectedScopeButtonIndex == 0 ? false : true
272+ activeDataSource = searchBar.selectedScopeButtonIndex == 0 ? .people : .tags
219 tableView.reloadData()
273 tableView.reloadData()
220 }
274 }
221
275
GDproject/Controller/ News and channels/ChannelListController.swift+32−29
@@ -17,13 +17,13 @@ struct ChannelData{
17class ChannelListController: UITableViewController, DataDelegate {
17class ChannelListController: UITableViewController, DataDelegate {
18
18
19 // MARK: - Output -
19 // MARK: - Output -
20− var onChannelSelected: ((Channel) -> Void)?
20+ var onChannelSelected: ((Model.Channels) -> Void)?
21
21
22− // MARK:- filter search controller
22+ // MARK: - filter search controller
23− var filteredDataSource = [Channel]()
23+ var filteredDataSource = [Model.Channels]()
24
24
25 var myProtocol: DataDelegate?
25 var myProtocol: DataDelegate?
26− var displayingChannel: Channel?
26+ var displayingChannel: Model.Channels?
27
27
28 var isFiltering: Bool {
28 var isFiltering: Bool {
29 return searchController.isActive && !searchBarIsEmpty()
29 return searchController.isActive && !searchBarIsEmpty()
@@ -35,15 +35,15 @@ class ChannelListController: UITableViewController, DataDelegate {
35
35
36 func filterContentForSearchText(_ searchText: String, scope: String = "All")
36 func filterContentForSearchText(_ searchText: String, scope: String = "All")
37 {
37 {
38− filteredDataSource = ChannelListController.dataSource.filter({(keys : Channel) -> Bool in
38+ filteredDataSource = dataSource.filter({(keys : Model.Channels) -> Bool in
39− return keys.title.lowercased().contains(searchText.lowercased())
39+ return keys.name.lowercased().contains(searchText.lowercased())
40 })
40 })
41
41
42 tableView.reloadData()
42 tableView.reloadData()
43 }
43 }
44
44
45− func passData(for row: Int, channel: Channel) {
45+ func passData(for row: Int, channel: Model.Channels) {
46− ChannelListController.dataSource[row] = channel
46+ dataSource[row] = channel
47 }
47 }
48
48
49 var searchController = UISearchController(searchResultsController: nil)
49 var searchController = UISearchController(searchResultsController: nil)
@@ -68,34 +68,37 @@ class ChannelListController: UITableViewController, DataDelegate {
68 {
68 {
69 super.viewWillAppear(animated)
69 super.viewWillAppear(animated)
70 searchController.isActive = false
70 searchController.isActive = false
71− tableView.reloadData()
71+ Model.channelsList { [weak self] (channels) in
72+ self?.dataSource = [ChannelListController.generalChannel] + channels
73+ }
72 }
74 }
73
75
74 @objc func addChannel()
76 @objc func addChannel()
75 {
77 {
76− // insertion
77− tableView.beginUpdates()
78− ChannelListController.dataSource.insert(Channel(title: "Untitled", subtitle: "No", hashtags: [], people: [], posts: []), at: 1)
79− tableView.insertRows(at: [IndexPath(row: 1, section: 0)], with: .none)
80− tableView.endUpdates()
81−
82 // editing mode is on automatically
78 // editing mode is on automatically
83 let vc = storyboard?.instantiateViewController(withIdentifier: channelControllerId) as! ChannelController
79 let vc = storyboard?.instantiateViewController(withIdentifier: channelControllerId) as! ChannelController
84 vc.index = 1
80 vc.index = 1
85 vc.myProtocol = self
81 vc.myProtocol = self
86− vc.channel = ChannelListController.dataSource[1]
82+ vc.channel = Model.Channels(people: [], name: "Untitled", tags: [])
87 navigationController?.pushViewController(vc, animated: true)
83 navigationController?.pushViewController(vc, animated: true)
88 }
84 }
89
85
86+ static let generalChannel = Model.Channels(people: [], name: "General", id: -1, tags: [])
87+
90− static var dataSource : [Channel] = [
88+ var dataSource : [Model.Channels] = [
91− Channel(title: "General", subtitle: "All posts", hashtags: ["All"], people: ["All"], posts: [])
89+ Model.Channels(people: [], name: "General", id: -1, tags: [])
92− ]
90+ ]
91+ {
92+ didSet{
93+ self.tableView.reloadData()
94+ }
95+ }
93
96
94 override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
97 override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
95 if isFiltering {
98 if isFiltering {
96 return filteredDataSource.count
99 return filteredDataSource.count
97 } else {
100 } else {
98− return ChannelListController.dataSource.count
101+ return dataSource.count
99 }
102 }
100 }
103 }
101
104
@@ -106,11 +109,11 @@ class ChannelListController: UITableViewController, DataDelegate {
106
109
107
110
108 if isFiltering{
111 if isFiltering{
109− cell.textLabel?.text = filteredDataSource[indexPath.row].title
112+ cell.textLabel?.text = filteredDataSource[indexPath.row].name
110− cell.detailTextLabel?.text = filteredDataSource[indexPath.row].subtitle
113+ cell.detailTextLabel?.text = filteredDataSource[indexPath.row].tags.reduce(String(), { (r, next) -> String in "\(r) \(next)" })
111 } else {
114 } else {
112− cell.textLabel?.text = ChannelListController.dataSource[indexPath.row].title
115+ cell.textLabel?.text = dataSource[indexPath.row].name
113− cell.detailTextLabel?.text = ChannelListController.dataSource[indexPath.row].subtitle
116+ cell.detailTextLabel?.text = dataSource[indexPath.row].tags.reduce(String(), { (r, next) -> String in "\(r) \(next)" })
114 }
117 }
115
118
116 return cell
119 return cell
@@ -133,19 +136,19 @@ class ChannelListController: UITableViewController, DataDelegate {
133 let vc = self?.storyboard?.instantiateViewController(withIdentifier: channelControllerId) as! ChannelController
136 let vc = self?.storyboard?.instantiateViewController(withIdentifier: channelControllerId) as! ChannelController
134 vc.index = indexPath.row
137 vc.index = indexPath.row
135 vc.myProtocol = self!
138 vc.myProtocol = self!
136− vc.channel = ChannelListController.dataSource[indexPath.row]
139+ vc.channel = self?.dataSource[indexPath.row]
137 self?.navigationController?.pushViewController(vc, animated: true)
140 self?.navigationController?.pushViewController(vc, animated: true)
138 }
141 }
139 editButton.backgroundColor = .green
142 editButton.backgroundColor = .green
140
143
141
144
142 let deleteButton = UITableViewRowAction(style: .normal, title: "Delete") { [weak self] (action, indexPath) in
145 let deleteButton = UITableViewRowAction(style: .normal, title: "Delete") { [weak self] (action, indexPath) in
143− if (ChannelListController.dataSource[indexPath.row] == self!.displayingChannel!)
146+ if (self!.dataSource[indexPath.row].id == self!.displayingChannel?.id ?? -1)
144 {
147 {
145− self?.myProtocol?.passData(for: 0, channel: ChannelListController.dataSource[0])
148+ self?.myProtocol?.passData(for: 0, channel: self!.dataSource[0])
146 }
149 }
147 self?.tableView.beginUpdates()
150 self?.tableView.beginUpdates()
148− ChannelListController.dataSource.remove(at: indexPath.row)
151+ self?.dataSource.remove(at: indexPath.row)
149 self?.tableView.deleteRows(at: [indexPath], with: .none)
152 self?.tableView.deleteRows(at: [indexPath], with: .none)
150 self?.tableView.endUpdates()
153 self?.tableView.endUpdates()
151 }
154 }
@@ -163,7 +166,7 @@ class ChannelListController: UITableViewController, DataDelegate {
163 myProtocol?.passData(for: 0, channel: filteredDataSource[indexPath.row])
166 myProtocol?.passData(for: 0, channel: filteredDataSource[indexPath.row])
164 navigationController?.popViewController(animated: true)
167 navigationController?.popViewController(animated: true)
165 } else {
168 } else {
166− myProtocol?.passData(for: 0, channel: ChannelListController.dataSource[indexPath.row])
169+ myProtocol?.passData(for: 0, channel: dataSource[indexPath.row])
167 navigationController?.popViewController(animated: true)
170 navigationController?.popViewController(animated: true)
168 //onChannelSelected?(ChannelListController.dataSource[indexPath.row])
171 //onChannelSelected?(ChannelListController.dataSource[indexPath.row])
169 }
172 }
GDproject/Controller/ News and channels/ChannelsCoordinator.swift+2−2
@@ -12,11 +12,11 @@ import UIKit
12final class ChannelsCoordinator{
12final class ChannelsCoordinator{
13
13
14 // MARK: - Properties
14 // MARK: - Properties
15− private var channel: Channel { didSet { updateInterfaces() } }
15+ private var channel: Model.Channels { didSet { updateInterfaces() } }
16 private weak var navigationController: UINavigationController?
16 private weak var navigationController: UINavigationController?
17
17
18 // MARK:- Init
18 // MARK:- Init
19− init(currentChannel: Channel, navigationController: UINavigationController) {
19+ init(currentChannel: Model.Channels, navigationController: UINavigationController) {
20 self.channel = currentChannel
20 self.channel = currentChannel
21 self.navigationController = navigationController
21 self.navigationController = navigationController
22 }
22 }
GDproject/Controller/ News and channels/NewsController.swift+32−11
@@ -11,7 +11,7 @@ import TinyConstraints
11import Cartography
11import Cartography
12
12
13protocol UpdateableWithChannel: class {
13protocol UpdateableWithChannel: class {
14− var channel: Channel? { get set }
14+ var channel: Model.Channels? { get set }
15}
15}
16protocol NewPostDelegate {
16protocol NewPostDelegate {
17 func addPost(post: Post)
17 func addPost(post: Post)
@@ -23,8 +23,12 @@ protocol UpdateableWithUser: class {
23// Search is availiable within every table (posts and channels). Has button-functionality for boths post and chnnels
23// Search is availiable within every table (posts and channels). Has button-functionality for boths post and chnnels
24class NewsController: UITableViewController, UISearchControllerDelegate, NewPostDelegate, UpdateableWithChannel, DataDelegate
24class NewsController: UITableViewController, UISearchControllerDelegate, NewPostDelegate, UpdateableWithChannel, DataDelegate
25{
25{
26− func passData(for row: Int, channel: Channel) {
26+ func passData(for row: Int, channel: Model.Channels) {
27+ if channel.id == -1{
28+ self.channel = nil
29+ } else {
27− self.channel = channel
30+ self.channel = channel
31+ }
28 }
32 }
29
33
30 var dictionary: [Int: Model.Users]? {
34 var dictionary: [Int: Model.Users]? {
@@ -32,7 +36,7 @@ class NewsController: UITableViewController, UISearchControllerDelegate, NewPost
32
36
33 var newPosts: [Model.Posts] = []
37 var newPosts: [Model.Posts] = []
34
38
35− channel?.posts.forEach({ (post) in
39+ posts!.forEach({ (post) in
36 newPosts.append(Model.Posts(body: post.body, authorId: post.authorId, id: post.id, user: dictionary![post.authorId]!, date: post.updated, tags: post.tags))
40 newPosts.append(Model.Posts(body: post.body, authorId: post.authorId, id: post.id, user: dictionary![post.authorId]!, date: post.updated, tags: post.tags))
37 })
41 })
38
42
@@ -42,10 +46,15 @@ class NewsController: UITableViewController, UISearchControllerDelegate, NewPost
42 }
46 }
43 }
47 }
44
48
45− var channel: Channel?{
49+ var posts: [Model.Posts]? {
50+ didSet{
51+
52+ }
53+ }
54+
55+ var channel: Model.Channels? {
46 didSet{
56 didSet{
47− print(channel!.posts.count)
48− navigationItem.title = channel?.title ?? ""
57+ navigationItem.title = channel?.name ?? ""
49 }
58 }
50 }
59 }
51
60
@@ -94,7 +103,7 @@ class NewsController: UITableViewController, UISearchControllerDelegate, NewPost
94 @objc func refreshPostsData( _ ff: UIRefreshControl){
103 @objc func refreshPostsData( _ ff: UIRefreshControl){
95 print("I am here")
104 print("I am here")
96 Model.getLast { [weak self] (tuple) in
105 Model.getLast { [weak self] (tuple) in
97− self?.channel = tuple.channel
106+ self?.posts = tuple.posts
98 self?.dictionary = tuple.users
107 self?.dictionary = tuple.users
99 self?.refreshContr.endRefreshing()
108 self?.refreshContr.endRefreshing()
100 }
109 }
@@ -119,9 +128,21 @@ class NewsController: UITableViewController, UISearchControllerDelegate, NewPost
119 searchController.isActive = false
128 searchController.isActive = false
120 // TODO:- display something if no posts are availiable
129 // TODO:- display something if no posts are availiable
121
130
131+ if let channel = channel, let id = channel.id {
132+
133+ Model.getChannel(with: id) { [weak self] in
134+ self?.posts = $0.posts
135+ self?.dictionary = $0.users
136+ }
137+
138+ } else{
139+
140+ navigationItem.title = "@&% General"
122− Model.getLast {
141+ Model.getLast { [weak self] in
123− self.channel = $0.channel
142+ self?.posts = $0.posts
124− self.dictionary = $0.users
143+ self?.dictionary = $0.users
144+ }
145+
125 }
146 }
126
147
127 // tableView.reloadData()
148 // tableView.reloadData()
GDproject/Controller/ News and channels/NewsVC.swift+1−1
@@ -28,7 +28,7 @@ struct PostCellData{
28class NewsVC: UIViewController, UITableViewDelegate, UITableViewDataSource{
28class NewsVC: UIViewController, UITableViewDelegate, UITableViewDataSource{
29
29
30 var dataSourse: [Model.Posts] = []{
30 var dataSourse: [Model.Posts] = []{
31− didSet{
31+ didSet {
32 cellDataSourse = []
32 cellDataSourse = []
33 dataSourse.forEach { (item) in
33 dataSourse.forEach { (item) in
34 cellDataSourse.append(PostCellData(attributedData: PostCellData.create(with: item.body)))
34 cellDataSourse.append(PostCellData(attributedData: PostCellData.create(with: item.body)))
GDproject/Simple model/Model.swift+87−20
@@ -10,7 +10,9 @@ import Foundation
10import Alamofire
10import Alamofire
11
11
12class Model{
12class Model{
13+
13 static let invalidTocken = 498
14 static let invalidTocken = 498
15+
14 private static var isValidTocken: ((Int)->())? = {
16 private static var isValidTocken: ((Int)->())? = {
15 responce in
17 responce in
16 print("\(responce)")
18 print("\(responce)")
@@ -20,6 +22,7 @@ class Model{
20 }
22 }
21
23
22 private static let baseUrl = "https://valera-denis.herokuapp.com"
24 private static let baseUrl = "https://valera-denis.herokuapp.com"
25+ static let decoder = JSONDecoder()
23
26
24 static let url = URL(string:"\(baseUrl)/authentication/login")!
27 static let url = URL(string:"\(baseUrl)/authentication/login")!
25 static let url1 = URL(string:"\(baseUrl)/posts/last")!
28 static let url1 = URL(string:"\(baseUrl)/posts/last")!
@@ -27,6 +30,9 @@ class Model{
27 static let urlForUsers = URL(string:"\(baseUrl)/users")!
30 static let urlForUsers = URL(string:"\(baseUrl)/users")!
28 static let createAndPublishURL = URL(string:"\(baseUrl)/posts/publish")!
31 static let createAndPublishURL = URL(string:"\(baseUrl)/posts/publish")!
29 static let channelsGetURL = URL(string: "\(baseUrl)/channels/get")!
32 static let channelsGetURL = URL(string: "\(baseUrl)/channels/get")!
33+ static let channelsUpdateURL = URL(string: "\(baseUrl)/channels/update")!
34+ static let channelsListURL = URL(string: "\(baseUrl)/channels")!
35+ static let channelsCreateURL = URL(string: "\(baseUrl)/channels/create")!
30
36
31
37
32 struct QueryPosts: Codable{
38 struct QueryPosts: Codable{
@@ -117,6 +123,43 @@ class Model{
117 }
123 }
118 }
124 }
119
125
126+ struct Channels: Codable {
127+
128+ var people: [Int]
129+ var name: String
130+ var id: Int?
131+ var tags: [String]
132+
133+ enum CodingKeys: String, CodingKey {
134+ case people
135+ case name
136+ case id
137+ case tags
138+ }
139+
140+ init(people: [Int], name: String, id: Int, tags: [String]) {
141+ self.id = id
142+ self.people = people
143+ self.tags = tags
144+ self.name = name
145+ }
146+
147+ init(people: [Int], name: String, tags: [String]) {
148+ self.people = people
149+ self.tags = tags
150+ self.name = name
151+ }
152+
153+ func encode(to encoder: Encoder) throws {
154+ var container = encoder.container(keyedBy: CodingKeys.self)
155+ try container.encode(people, forKey: .people)
156+ try container.encode(name, forKey: .name)
157+ // try container.encode(id, forKey: .id)
158+ try container.encode(tags, forKey: .tags)
159+ }
160+
161+ }
162+
120 static func authenticate(with id: Int, completion: @escaping ((Bool)->())) {
163 static func authenticate(with id: Int, completion: @escaping ((Bool)->())) {
121
164
122 let json: [String:Any] = ["authenticationId" : id]
165 let json: [String:Any] = ["authenticationId" : id]
@@ -156,7 +199,7 @@ class Model{
156 }
199 }
157
200
158
201
159− static func getLast(completion: @escaping (((users:[Int: Users], channel:Channel))->())){
202+ static func getLast(completion: @escaping (((users:[Int: Users], posts:[Posts]))->())){
160 let jsonString = "30"
203 let jsonString = "30"
161 var request = URLRequest(url: url1)
204 var request = URLRequest(url: url1)
162
205
@@ -171,21 +214,19 @@ class Model{
171
214
172 isValidTocken?(response.response?.statusCode ?? 498)
215 isValidTocken?(response.response?.statusCode ?? 498)
173
216
174− let decoder = JSONDecoder()
175 guard let json = response.data else { return }
217 guard let json = response.data else { return }
176
218
177 guard let newQueery = try? decoder.decode(QueryPosts.self, from: json) else { print("no")
219 guard let newQueery = try? decoder.decode(QueryPosts.self, from: json) else { print("no")
178 return }
220 return }
179
221
180 idUser = newQueery.users
222 idUser = newQueery.users
181− completion((newQueery.users, Channel(title: "# General", subtitle: "No subtitle", hashtags: ["ПИ"], people: ["No"], posts: newQueery.posts)))
223+ completion((newQueery.users, newQueery.posts))
182 }
224 }
183 }
225 }
184
226
185
227
186 static func createAndPublish(body: [Attachments], tags: [String]){
228 static func createAndPublish(body: [Attachments], tags: [String]){
187 let jsonUpd = CreatedPost(body: body, tags: tags)
229 let jsonUpd = CreatedPost(body: body, tags: tags)
188−
189 var request = URLRequest(url: createAndPublishURL)
230 var request = URLRequest(url: createAndPublishURL)
190
231
191 request.httpMethod = "POST"
232 request.httpMethod = "POST"
@@ -220,11 +261,8 @@ class Model{
220 AF.request(request).responseJSON {
261 AF.request(request).responseJSON {
221 (response) in
262 (response) in
222
263
223− if response.response?.statusCode == 200 {
264+ isValidTocken?(response.response?.statusCode ?? 498)
224− print("success")
225− }
226
265
227− let decoder = JSONDecoder()
228 guard let json = response.data else { return }
266 guard let json = response.data else { return }
229
267
230 guard let newPost = try? decoder.decode(QueryPosts.self, from: json) else { return }
268 guard let newPost = try? decoder.decode(QueryPosts.self, from: json) else { return }
@@ -249,11 +287,8 @@ class Model{
249 AF.request(request).responseJSON {
287 AF.request(request).responseJSON {
250 (response) in
288 (response) in
251
289
252− if response.response?.statusCode == 200 {
290+ isValidTocken?(response.response?.statusCode ?? 498)
253− print("successddd")
254− }
255
291
256− let decoder = JSONDecoder()
257 guard let json = response.data else { return }
292 guard let json = response.data else { return }
258
293
259 guard let users = try? decoder.decode([Users].self, from: json) else { return }
294 guard let users = try? decoder.decode([Users].self, from: json) else { return }
@@ -267,7 +302,7 @@ class Model{
267 }
302 }
268
303
269 // get channel (with id): in responce -- PostQuery
304 // get channel (with id): in responce -- PostQuery
270− static func getChannels(with channelId: Int, completion: @escaping (([Posts])->())){
305+ static func getChannel(with channelId: Int, completion: @escaping (((users:[Int: Users], posts:[Posts]))->())){
271 let json = [
306 let json = [
272 "request" : channelId,
307 "request" : channelId,
273 "limit": 10
308 "limit": 10
@@ -275,7 +310,7 @@ class Model{
275
310
276 let jsonData = try? JSONSerialization.data(withJSONObject: json)
311 let jsonData = try? JSONSerialization.data(withJSONObject: json)
277
312
278− var request = URLRequest(url: urlForPostsForUser)
313+ var request = URLRequest(url: channelsGetURL)
279 request.httpMethod = "POST"
314 request.httpMethod = "POST"
280
315
281 // insert json data to the request
316 // insert json data to the request
@@ -285,16 +320,48 @@ class Model{
285 AF.request(request).responseJSON {
320 AF.request(request).responseJSON {
286 (response) in
321 (response) in
287
322
288− if response.response?.statusCode == 200 {
323+ isValidTocken?(response.response?.statusCode ?? 498)
289− print("success")
324+
290− }
291
325
292− let decoder = JSONDecoder()
293 guard let json = response.data else { return }
326 guard let json = response.data else { return }
294
327
295− guard let newPost = try? decoder.decode(QueryPosts.self, from: json) else { return }
328+ guard let newQueery = try? decoder.decode(QueryPosts.self, from: json) else { return }
296
329
330+ idUser = newQueery.users
297− completion(newPost.posts)
331+ completion((newQueery.users, newQueery.posts))
332+ }
333+ }
334+
335+
336+ static func createChannel(with channel: Channels) {
337+
338+ var request = URLRequest(url: channelsCreateURL)
339+ request.httpMethod = "POST"
340+ request.httpBody = try? JSONEncoder().encode(channel)
341+
342+ request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
343+ AF.request(request).response {
344+ (response) in
345+
346+ isValidTocken?(response.response?.statusCode ?? 498)
347+ }
348+
349+ }
350+
351+ static func channelsList(completion: @escaping (([Channels])->())){
352+ var request = URLRequest(url: channelsListURL)
353+ request.httpMethod = "POST"
354+ request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
355+
356+ AF.request(request).responseJSON { (response) in
357+
358+ isValidTocken?(response.response?.statusCode ?? 498)
359+
360+ guard let json = response.data else { return }
361+
362+ guard let channelsList = try? decoder.decode([Channels].self, from: json) else { return }
363+
364+ completion(channelsList)
298 }
365 }
299 }
366 }
300}
367}