git.iko.soy/dashared/GDproject
on master help sign in
established connection with server. getting first posts
commitee55c87c425a901dd95b717a5a3a7e45d7d96603 authorDarya Rednikina <rednikina.com@yandex.ru> dateSun 24 Feb 2019, 23:23 (8 years ago) parent011b79c
12 files changed+207−50
GDproject/Controller/ News and channels/ChannelListController.swift+1−8 GDproject/Controller/ News and channels/FullPostController.swift+4−4 GDproject/Controller/ News and channels/NewPostViewController.swift+6−4 GDproject/Controller/ News and channels/NewsController.swift+11−3 GDproject/Controller/ News and channels/NewsVC.swift+2−2 GDproject/Controller/ News and channels/PostViewCell.swift+6−14 GDproject/Controller/Log In/LogInCoordinator.swift+1−3 GDproject/Controller/Profile/ProfileViewController.swift+1−1 GDproject/DataStorage.swift+8−2 GDproject/Simple model/Channel.swift+2−2 GDproject/Simple model/Model.swift+163−4 GDproject/Supporting files/AppDelegate.swift+2−3
GDproject/Controller/ News and channels/ChannelListController.swift+1−8
@@ -88,14 +88,7 @@ class ChannelListController: UITableViewController, DataDelegate {
8888 }
8989
9090 static var dataSource : [Channel] = [
91− Channel(title: "General", subtitle: "All posts", hashtags: ["All"], people: ["All"], posts: []),
92− Channel(title: "Title", subtitle: "subtitle", hashtags: ["# sad", "# happy"], people: ["Seva", "Andrey"], posts: [Post(dataArray: [.text("Le Lorem Ipsum est simplement du faux texte employé dans la composition et la mise en page avant impression. Le Lorem Ipsum est le faux texte standard.")], from: User(name: "vbogomazova", id: 2, fullName: "Богомазова Вероника Львовна"), date: "14.02.19 в 12:05")]),
93− Channel(title: "Title2", subtitle: "subtitle2", hashtags: ["# studyhard", "# university"], people: ["Pasha", "Olya", "Andrey", "Ilya"], posts:
94− [
95− Post(dataArray: [.text("L'avantage du Lorem Ipsum sur un texte générique comme 'Du texte. Du texte. Du texte.' est qu'il possède une distribution de lettres plus ou moins normale.")], from: User(name: "vbogomazova", id: 2, fullName: "Богомазова Вероника Львовна"), date: "14.02.19 в 12:05"),
96− Post(dataArray: [.text("par accident, souvent intentionnellement (histoire d'y rajouter de petits clins d'oeil, voire des phrases embarassantes).")], from: User(name: "vbogomazova", id: 2, fullName: "Богомазова Вероника Львовна"), date: "14.02.19 в 12:05")
97− ]),
98− Channel(title: "Title3", subtitle: "subtitle3", hashtags: ["# lol", "# meme", "# hehe"], people: ["Superman"], posts: [Post(dataArray: [.text("Ipsum est le faux texte standard de l'imprimerie depuis les années 1500, quand un imprimeur anonyme assembla ensemble des morceaux de texte pour réaliser un livre spécimen de polices de texte. Il n'a pas fait que survivre cinq siècles, mais s'est aussi adapté à la bureautique informatique, sans que son contenu n'en soit modifié.")], from: User(name: "vbogomazova", id: 2, fullName: "Богомазова Вероника Львовна"), date: "14.02.19 в 12:05")])
91+ Channel(title: "General", subtitle: "All posts", hashtags: ["All"], people: ["All"], posts: [])
9992 ]
10093
10194 override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
GDproject/Controller/ News and channels/FullPostController.swift+4−4
@@ -11,7 +11,7 @@ import TinyConstraints
1111
1212class FullPostController: UITableViewController {
1313
14− var post: Post?
14+ var post: Model.Posts?
1515
1616 override func viewDidLoad() {
1717 super.viewDidLoad()
@@ -26,7 +26,7 @@ class FullPostController: UITableViewController {
2626
2727 func setUpNavigationBar(){
2828 navigationController?.navigationBar.prefersLargeTitles = false
29− navigationItem.title = "\(post?.fromUser.login ?? "")"
29+ navigationItem.title = "\(post?.authorId ?? 0)"
3030 navigationItem.rightBarButtonItems = [UIBarButtonItem(barButtonSystemItem: .action, target: self, action: #selector(self.options))]
3131 }
3232
@@ -83,7 +83,7 @@ class FullPostController: UITableViewController {
8383 case 0:
8484 return 1
8585 case 1:
86− return post?.comments.count ?? 0
86+ return 0
8787 default:
8888 return 0
8989 }
@@ -95,7 +95,7 @@ class FullPostController: UITableViewController {
9595
9696 let cell = tableView.dequeueReusableCell(withIdentifier: postCellId) as! PostViewCell
9797
98− cell.fill(with: post!.dataArray, true, post: post!)
98+ cell.fill(with: post!.body, true, post: post!)
9999 cell.selectionStyle = .none
100100 return cell
101101 }
GDproject/Controller/ News and channels/NewPostViewController.swift+6−4
@@ -46,6 +46,9 @@ class NewPostViewController: UIViewController, UITextViewDelegate {
4646 override func viewDidLoad()
4747 {
4848 super.viewDidLoad()
49+ Model.createDraft { [weak self] (int) in
50+ self?.indexOfPost = int
51+ }
4952 setUpMD()
5053 setUpTextView()
5154 setUpAccessoryView()
@@ -186,13 +189,12 @@ class NewPostViewController: UIViewController, UITextViewDelegate {
186189 textView = UITextView(frame: view.bounds, textContainer: textContainer)
187190 }
188191
192+ var indexOfPost = 0
189193 // MARK:- new post
190194 @objc func newPost(){
191− let p = Post(dataArray: [.text(textView.text)], from: User(name: "Сева", id: 5, fullName: "Сева Леонидович"), date: "12.01.19")
192−
193−
195+ Model.update(post: Model.Posts(body: [Model.Attachments(markdown: textView.text)], authorId: 42, id: indexOfPost))
194196 // adding row to uiTableView after adding new post
195− myProtocol?.addPost(post: p)
197+ // myProtocol?.addPost(post: p)
196198 moveBackToParentVC()
197199 // somewhere here i will be sending server notifications about new post arrival
198200 }
GDproject/Controller/ News and channels/NewsController.swift+11−3
@@ -29,6 +29,7 @@ class NewsController: UITableViewController, UISearchControllerDelegate, NewPost
2929 didSet{
3030 news.dataSourse = channel?.posts ?? []
3131 navigationItem.title = channel?.title ?? ""
32+ tableView.reloadData()
3233 }
3334 }
3435
@@ -36,7 +37,7 @@ class NewsController: UITableViewController, UISearchControllerDelegate, NewPost
3637 var onSelectChannel: (() -> Void)?
3738
3839 func addPost(post: Post) {
39− news.dataSourse.insert(post, at: 0)
40+ //news.dataSourse.insert(post, at: 0)
4041 }
4142
4243 var searchController = UISearchController(searchResultsController: nil)
@@ -46,7 +47,7 @@ class NewsController: UITableViewController, UISearchControllerDelegate, NewPost
4647 override func viewDidLoad()
4748 {
4849 super.viewDidLoad()
49− channel = ChannelListController.dataSource[0]
50+
5051
5152 tableView.register(PostViewCell.self, forCellReuseIdentifier: postCellId)
5253 tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
@@ -57,7 +58,6 @@ class NewsController: UITableViewController, UISearchControllerDelegate, NewPost
5758 definesPresentationContext = true
5859 searchController.searchBar.placeholder = "Search anything"
5960
60− news.dataSourse = channel!.posts
6161 news.viewController = self
6262
6363 news.type = .NONE
@@ -67,6 +67,9 @@ class NewsController: UITableViewController, UISearchControllerDelegate, NewPost
6767 //setUpBanner()
6868 }
6969
70+ deinit {
71+ print("news clear")
72+ }
7073
7174 let label : UILabel = {
7275 let label = UILabel()
@@ -82,6 +85,11 @@ class NewsController: UITableViewController, UISearchControllerDelegate, NewPost
8285 super.viewWillAppear(animated)
8386 searchController.isActive = false
8487 // TODO:- display something if no posts are availiable
88+
89+ Model.getLast { (channel) in
90+ self.channel = channel
91+ }
92+
8593 tableView.reloadData()
8694 }
8795
GDproject/Controller/ News and channels/NewsVC.swift+2−2
@@ -10,7 +10,7 @@ import UIKit
1010
1111class NewsVC: UIViewController, UITableViewDelegate, UITableViewDataSource{
1212
13− var dataSourse: [Post] = []
13+ var dataSourse: [Model.Posts] = []
1414
1515 var type: HeaderType = .NONE
1616
@@ -37,7 +37,7 @@ class NewsVC: UIViewController, UITableViewDelegate, UITableViewDataSource{
3737 {
3838 let cell = tableView.dequeueReusableCell(withIdentifier: postCellId, for: indexPath) as! PostViewCell
3939
40− cell.fill(with: dataSourse[indexPath.row].dataArray, false, post: dataSourse[indexPath.row])
40+ cell.fill(with: dataSourse[indexPath.row].body, false, post: dataSourse[indexPath.row])
4141 cell.selectionStyle = .none
4242 return cell
4343 }
GDproject/Controller/ News and channels/PostViewCell.swift+6−14
@@ -69,9 +69,9 @@ class PostViewCell: UITableViewCell
6969
7070 var views: [UIView] = []
7171 var data : [UIImage] = []
72− var post: Post?
72+ var post: Model.Posts?
7373
74− func fill(with info: [Media], _ isFullVersoin: Bool, post: Post)
74+ func fill(with info: [Model.Attachments], _ isFullVersoin: Bool, post: Model.Posts)
7575 {
7676 self.post = post
7777 // important
@@ -79,21 +79,13 @@ class PostViewCell: UITableViewCell
7979
8080 data = []
8181 views = []
82− for item in info.enumerated()
82+ for attachment in info
8383 {
84− switch item.element
85− {
86− case .text(let text):
87− views.append(createTextView(with: text))
88− case .image(let images):
89− self.data = images
90− default:
91− break
92− }
84+ views.append(createTextView(with: attachment.markdown))
9385 }
9486 setUpInStackView(isFullVersoin)
9587 }
96−
88+ let hashtags = ["Kek", "Lol"]
9789 func setUpInStackView(_ full : Bool){
9890 let nameStackView = UIStackView(arrangedSubviews: [nameLabel, fullNameLabel])
9991 nameStackView.axis = .vertical
@@ -113,7 +105,7 @@ class PostViewCell: UITableViewCell
113105 scrollView.showsHorizontalScrollIndicator = false
114106
115107 var buttons: [UIButton] = []
116− for hash in post!.hashtags {
108+ for hash in hashtags {
117109 let button = UIButton()
118110 button.setTitle("#" + hash, for: .normal)
119111 //button.backgroundColor = #colorLiteral(red: 0.8039215803, green: 0.8039215803, blue: 0.8039215803, alpha: 1)
GDproject/Controller/Log In/LogInCoordinator.swift+1−3
@@ -11,7 +11,7 @@ import UIKit
1111class LogInCoordinator{
1212
1313 private weak var navigationController: UINavigationController?
14− private var window: UIWindow!
14+ private var window: UIWindow!
1515 // MARK:- Init
1616 init(navigationController: UINavigationController, window: UIWindow) {
1717 self.navigationController = navigationController
@@ -30,9 +30,7 @@ class LogInCoordinator{
3030
3131 private func showLogInPage(){
3232 let controller = UIStoryboard.makeLogIn()
33− //controller.channel = channel
3433 controller.onLogIn = { [weak self] in
35− self?.showStatusPage()
3634 DataStorage.standard.setIsLoggedIn(value: true)
3735 Model.authenticate()
3836 }
GDproject/Controller/Profile/ProfileViewController.swift+1−1
@@ -48,7 +48,7 @@ class ProfileViewController: UIViewController
4848 {
4949 super.viewDidLoad()
5050
51− posts.dataSourse = [Post(dataArray: [.text("Le Lorem Ipsum est simplement du faux texte employé dans la composition et la mise en page avant impression. Le Lorem Ipsum est le faux texte standard de l'imprimerie depuis les années 1500, quand un imprimeur anonyme assembla ensemble des morceaux de texte pour réaliser un livre spécimen de polices de texte. comme Aldus PageMaker. est qu'il possède une distribution de lettres plus ou moins normale, et en tout cas comparable avec celle du français standard. De nombreuses suites logicielles de mise en page ou éditeurs de sites Web ont fait du Lorem Ipsum leur faux texte par défaut, et une recherche pour 'Lorem Ipsum' vous conduira vers de nombreux sites qui n'en sont encore qu'à leur phase de construction. Plusieurs versions sont apparues avec le temps, parfois par accident, souvent intentionnellement (histoire d'y rajouter de petits clins d'oeil, voire des phrases embarassantes).")]), Post(dataArray: [.text("Il n'a pas fait que survivre cinq siècles, mais s'est aussi adapté à la bureautique informatique, sans que son contenu n'en soit modifié. Il a été popularisé dans les années 1960 grâce à la vente de feuilles Letraset contenant des passages du Lorem Ipsum, et, plus récemment, par son inclusion dans des applications de mise en page de texte, comme Aldus PageMaker. .")])]
51+ //posts.dataSourse = [Post(dataArray: [.text("Le Lorem Ipsum est simplement du faux texte employé dans la composition et la mise en page avant impression. Le Lorem Ipsum est le faux texte standard de l'imprimerie depuis les années 1500, quand un imprimeur anonyme assembla ensemble des morceaux de texte pour réaliser un livre spécimen de polices de texte. comme Aldus PageMaker. est qu'il possède une distribution de lettres plus ou moins normale, et en tout cas comparable avec celle du français standard. De nombreuses suites logicielles de mise en page ou éditeurs de sites Web ont fait du Lorem Ipsum leur faux texte par défaut, et une recherche pour 'Lorem Ipsum' vous conduira vers de nombreux sites qui n'en sont encore qu'à leur phase de construction. Plusieurs versions sont apparues avec le temps, parfois par accident, souvent intentionnellement (histoire d'y rajouter de petits clins d'oeil, voire des phrases embarassantes).")]), Post(dataArray: [.text("Il n'a pas fait que survivre cinq siècles, mais s'est aussi adapté à la bureautique informatique, sans que son contenu n'en soit modifié. Il a été popularisé dans les années 1960 grâce à la vente de feuilles Letraset contenant des passages du Lorem Ipsum, et, plus récemment, par son inclusion dans des applications de mise en page de texte, comme Aldus PageMaker. .")])]
5252
5353 // basicInfo.dataSourse =
5454
GDproject/DataStorage.swift+8−2
@@ -17,9 +17,14 @@ class DataStorage{
1717
1818 private init(){}
1919
20− var coordinator: LogInCoordinator?
20+ //weak var coordinator: LogInCoordinator?
2121 static let standard = DataStorage()
2222
23+ var cookie: HTTPCookie? = nil {
24+ didSet {
25+ (UIApplication.shared.delegate as? AppDelegate)?.tabCoordinator.start()
26+ }
27+ }
2328 // add channel
2429
2530 // delete channel
@@ -38,7 +43,7 @@ class DataStorage{
3843 Function to determine is user logged in already or not
3944 */
4045 func isLoggedIn() -> Bool {
41− return UserDefaults.standard.bool(forKey: UserDefaultsKeys.loggedIn.rawValue)
46+ return UserDefaults.standard.bool(forKey: UserDefaultsKeys.loggedIn.rawValue) && cookie != nil
4247 }
4348}
4449
@@ -47,4 +52,5 @@ class DataStorage{
4752 */
4853enum UserDefaultsKeys: String{
4954 case loggedIn
55+ case cookie
5056}
GDproject/Simple model/Channel.swift+2−2
@@ -22,9 +22,9 @@ class Channel: Equatable {
2222 var hashtags: [String] = []
2323 var people: [String] = []
2424
25− var posts: [Post] = []
25+ var posts: [Model.Posts] = []
2626
27− init(title: String, subtitle: String, hashtags: [String], people: [String], posts: [Post])
27+ init(title: String, subtitle: String = "none", hashtags: [String] = [], people: [String] = [], posts: [Model.Posts])
2828 {
2929 self.title = title
3030 self.subtitle = subtitle
GDproject/Simple model/Model.swift+163−4
@@ -11,15 +11,174 @@ import Alamofire
1111
1212class Model{
1313 static var url = URL(string:"https://valera-denis.herokuapp.com/authenticate")!
14+ static var url1 = URL(string:"https://valera-denis.herokuapp.com/posts/last")!
15+ static var urlForDrafts = URL(string:"https://valera-denis.herokuapp.com/drafts/create")!
16+ static var urlForPublish = URL(string:"https://valera-denis.herokuapp.com/drafts/publish")!
17+ static var urlForUpdate = URL(string:"https://valera-denis.herokuapp.com/drafts/update")!
18+
19+ struct Posts: Codable {
20+ var body: [Attachments]
21+ var authorId: Int
22+ var id: Int
23+
24+ init(body: [Attachments], authorId: Int, id: Int) {
25+ self.body = body
26+ self.authorId = authorId
27+ self.id = id
28+ }
29+ }
30+
31+ struct Attachments: Codable {
32+ var markdown: String
33+
34+ init(markdown: String) {
35+ self.markdown = markdown
36+ }
37+ }
1438
1539 static func authenticate(){
1640
17− let params: Parameters = ["authenticationId" : 9]
18− AF.request(url, method: .post, parameters: params).response{
19− (responce) in
41+ let json: [String:Any] = ["authenticationId" : 9]
42+ let jsonData = try? JSONSerialization.data(withJSONObject: json)
43+
44+ var request = URLRequest(url: url)
45+ request.httpMethod = "POST"
46+
47+ // insert json data to the request
48+ request.httpBody = jsonData
49+ request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
50+
51+ AF.request(request).response { (responce) in
52+
53+ guard let realResponse = responce.response, realResponse.statusCode == 204 else {
54+ print("Not a 204 response")
55+ return
56+ }
57+
58+ let fields = realResponse.allHeaderFields as? [String :String]
59+
60+ let cookies = HTTPCookie.cookies(withResponseHeaderFields: fields!, for: realResponse.url!)
61+
62+
63+ for cookie in cookies {
64+ HTTPCookieStorage.shared.setCookie(cookie)
65+ DataStorage.standard.cookie = cookie
66+ }
67+ }
68+ }
69+
70+
71+ static func getLast(completion: @escaping ((Channel)->())){
72+ let jsonString = "100"
73+ var request = URLRequest(url: url1)
74+
75+ request.httpMethod = "POST"
76+
77+ // insert json data to the request
78+ request.httpBody = jsonString.data(using: .utf8)
79+ request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
80+
81+ AF.request(request).responseJSON {
82+ (response) in
83+
84+ if response.response?.statusCode == 200 {
85+ print("success")
86+ }
87+
88+ let decoder = JSONDecoder()
89+ guard let json = response.data else { return }
90+
91+ guard let newPost = try? decoder.decode([Posts].self, from: json) else { return }
2092
21− print(responce.response?.allHeaderFields)
93+ completion(Channel(title: "# General", subtitle: "No subtitle", hashtags: ["ПИ"], people: ["No"], posts: newPost))
2294 }
95+ }
96+
97+ static func createDraft(completion: @escaping ((Int)->())){
98+ let jsonString = "[{ \"markdown\": \"# This is a markdown title\nThis is body.\" }]"
99+ var request = URLRequest(url: urlForDrafts)
100+
101+ request.httpMethod = "POST"
102+
103+ // insert json data to the request
104+ request.httpBody = jsonString.data(using: .utf8)
105+ request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
106+
107+ AF.request(request).responseJSON {
108+ (response) in
109+
110+ if response.response?.statusCode == 200 {
111+ print("success in creating draft")
112+ } else {
113+ print("\(response.response?.statusCode ?? 0)")
114+ }
115+
116+ //let decoder = JSONDecoder()
117+ guard let json = response.data else { return }
118+
119+ guard let id = String(data: json, encoding: String.Encoding.utf8) else {return}
120+
121+ print("with id \(id)")
122+ completion(Int(id) ?? 0)
123+ }
124+ }
125+
126+ static var seeMe: Int = 0 {
127+ didSet{
128+ publish()
129+ }
130+ }
131+
132+ static func publish(){
133+ let jsonUpd = "\(seeMe)"
134+ var request = URLRequest(url: urlForPublish)
23135
136+ request.httpMethod = "POST"
137+
138+ // insert json data to the request
139+ request.httpBody = jsonUpd.data(using: .utf8)
140+ request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
141+ AF.request(request).response {
142+ (response) in
143+
144+ if response.response?.statusCode == 204 {
145+ print("successfuly published \(jsonUpd)")
146+ }
147+ }
148+ }
149+
150+ static func update(post: Posts){
151+ let transformed = post.body.reduce("") { (res, att) -> String in
152+ res + att.markdown
153+ }
154+
155+ let jsonUpd = """
156+ {
157+ "body": [
158+ {
159+ "markdown": "\(transformed)"
160+ }
161+ ],
162+ "id": \(post.id)
163+ }
164+ """
165+ print(jsonUpd)
166+ var request = URLRequest(url: urlForUpdate)
167+
168+ request.httpMethod = "POST"
169+
170+ // insert json data to the request
171+ request.httpBody = jsonUpd.data(using: .utf8)
172+ request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
173+ AF.request(request).response {
174+ (response) in
175+
176+ if response.response?.statusCode == 204 {
177+ print("successfuly updated \(post.id) with \(jsonUpd)")
178+ seeMe = post.id
179+ } else {
180+ print(response.response?.statusCode)
181+ }
182+ }
24183 }
25184}
GDproject/Supporting files/AppDelegate.swift+2−3
@@ -31,13 +31,12 @@ class AppDelegate: UIResponder, UIApplicationDelegate {
3131
3232 func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool
3333 {
34−
34+ coordinator = LogInCoordinator(navigationController: rootController!, window: window!)
35+ tabCoordinator = TabbarCoordinator(window: window!)
3536 // TODO:- determine what to do here: log in or tabbar
3637 if DataStorage.standard.isLoggedIn() {
37− tabCoordinator = TabbarCoordinator(window: window!)
3838 tabCoordinator.start()
3939 } else {
40− coordinator = LogInCoordinator(navigationController: rootController!, window: window!)
4140 coordinator.start()
4241 }
4342