You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

488 lines
18 KiB

6 years ago
  1. //
  2. // StatusUploadViewController.swift
  3. // GMERemittance
  4. //
  5. // Created by Fm-user on 1/16/18.
  6. // Copyright © 2018 Gobal Money Express Co. Ltd. All rights reserved.
  7. //
  8. import UIKit
  9. import SDWebImage
  10. class StatusUploadViewController: UIViewController {
  11. @IBOutlet weak var labelUserNameInitial: UILabel!
  12. @IBOutlet weak var labelUserName: UILabel!
  13. @IBOutlet weak var dropDownView: UIPickerView!
  14. @IBOutlet weak var dropDownButton: UIButton!
  15. @IBOutlet weak var imageViewPost: FLAnimatedImageView!
  16. @IBOutlet weak var textViewPost: UITextView!
  17. @IBOutlet weak var textViewConstraint: NSLayoutConstraint!
  18. @IBOutlet weak var imageViewUserImage: UIImageView!
  19. @IBOutlet weak var postImageHeight: NSLayoutConstraint!
  20. @IBOutlet weak var buttonAddPhoto: UIButton!
  21. @IBOutlet weak var buttonSharePost: UIButton!
  22. @IBOutlet weak var viewShare: UIView!
  23. @IBOutlet weak var shareScrollView: UIScrollView!
  24. let imagePicker = UIImagePickerController()
  25. private let shareMode = ["Public ", "Private "]
  26. private var shareModeIndex: Int = 0
  27. private var movement: CGFloat = 0.0
  28. private var feedInputText: String!
  29. /*----statusUploadMode = 0 means user wants to upload text status, so image is optional
  30. ----statusUploadMode = 1 means user wants to upload image, so text is optional
  31. ----statusUploadMode = 2 means user wants to edit post, so either text or image is optional--*/
  32. private var activityIndicator: UIActivityIndicatorView = UIActivityIndicatorView()
  33. var statusUploadMode: Int?
  34. var editablePostIndex: Int?
  35. var socialfeedviewmodel: SocialFeedViewModel?
  36. var showNotificationParameter: Bool?
  37. @IBAction func sharePost(_ sender: Any) {
  38. textViewPost.resignFirstResponder()
  39. disableUserInteractions()
  40. showActivityIndicator(activityIndicator: activityIndicator)
  41. socialfeedviewmodel?.socialFeedConnectionTimeOut.value = nil
  42. /**
  43. connection timeout
  44. */
  45. socialfeedviewmodel?.socialFeedConnectionTimeOut.bind { [unowned self] in
  46. guard $0 != nil else {
  47. return
  48. }
  49. self.enableUserInteractions()
  50. self.dismissActivityIndicator(activityIndicator: self.activityIndicator)
  51. self.popUpMessage(value: 20)
  52. }
  53. switch statusUploadMode {
  54. case 0?, 1?:
  55. switch shareModeIndex {
  56. case 0:
  57. socialfeedviewmodel?.setAccessType(accessType: "public")
  58. case 1:
  59. socialfeedviewmodel?.setAccessType(accessType: "private")
  60. default:
  61. return
  62. }
  63. socialfeedviewmodel!.createSocialFeed()
  64. case 2?:
  65. let feedToEdit = socialfeedviewmodel?.getSocialFeedAt(index: editablePostIndex!)
  66. if feedToEdit?.accessType == "private" {
  67. if shareModeIndex == 1 {
  68. socialfeedviewmodel!.updateSocialFeed(feed: feedToEdit!, index: editablePostIndex!)
  69. } else {
  70. socialfeedviewmodel!.updateSocialFeed(feed: feedToEdit!, index: editablePostIndex!, toggle: true)
  71. }
  72. } else if feedToEdit?.accessType == "public" {
  73. if shareModeIndex == 1 {
  74. socialfeedviewmodel!.updateSocialFeed(feed: feedToEdit!, index: editablePostIndex!, toggle: true)
  75. } else {
  76. socialfeedviewmodel!.updateSocialFeed(feed: feedToEdit!, index: editablePostIndex!)
  77. }
  78. }
  79. default:
  80. enableUserInteractions()
  81. dismissActivityIndicator(activityIndicator: activityIndicator)
  82. return
  83. }
  84. }
  85. func setUpNetworkListener() {
  86. socialfeedviewmodel!.internetConnection.value = nil
  87. socialfeedviewmodel!.internetConnection.bind { [unowned self] in
  88. guard $0 != nil else {
  89. return
  90. }
  91. self.enableUserInteractions()
  92. self.dismissActivityIndicator(activityIndicator: self.activityIndicator)
  93. self.popUpMessage(value: 15)
  94. self.socialfeedviewmodel!.internetConnection.value = nil
  95. }
  96. }
  97. override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
  98. if segue.identifier == "myStory" {
  99. let privateStoryViewController = segue.destination as! MyStoryViewController
  100. privateStoryViewController.socialfeedviewmodel = self.socialfeedviewmodel
  101. privateStoryViewController.showNotificationParameter = self.showNotificationParameter
  102. }
  103. }
  104. @objc func clearKeyboard() {
  105. textViewPost.resignFirstResponder()
  106. }
  107. override func viewDidLoad() {
  108. super.viewDidLoad()
  109. let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(clearKeyboard))
  110. view.addGestureRecognizer(tap)
  111. if let userName = UserDefaults.standard.object(forKey: "com.gmeremit.fullName") as? String {
  112. labelUserName.text = userName
  113. }
  114. labelUserNameInitial.isHidden = false
  115. labelUserNameInitial.backgroundColor = UIColor(hex: 0x2e3192)
  116. labelUserNameInitial.layer.cornerRadius = labelUserNameInitial.frame.height / 2
  117. labelUserNameInitial.text = getFirstName().prefix(1).uppercased()
  118. let userDpString = UserDefaults.standard.object(forKey: "com.gmeremit.dpUrl") as? String
  119. if let userDpUrl = URL(string: userDpString!) {
  120. imageViewUserImage.isHidden = false
  121. imageViewUserImage.sd_setImage(with: userDpUrl, placeholderImage: nil, options: [.progressiveDownload,.scaleDownLargeImages], completed: nil)
  122. imageViewUserImage.layer.cornerRadius = imageViewUserImage.frame.height/2
  123. labelUserNameInitial.isHidden = true
  124. }
  125. guard socialfeedviewmodel != nil, statusUploadMode != nil else {
  126. return
  127. }
  128. if statusUploadMode == 2 && editablePostIndex == nil {
  129. return
  130. }
  131. setUpNetworkListener()
  132. setUpNavBar(id: 5, title: "")
  133. setUpAnotherLoginListener(genericviewmodel: socialfeedviewmodel!)
  134. imagePicker.delegate = self
  135. textViewPost.delegate = self
  136. dropDownButton.layer.borderColor = UIColor(red:0.93, green:0.11, blue:0.14, alpha:1.0).cgColor
  137. dropDownButton.layer.borderWidth = 1.0
  138. dropDownButton.layer.cornerRadius = 8
  139. textViewPost.text = "Share your story "
  140. textViewPost.textColor = UIColor(red:0.78, green:0.78, blue:0.80, alpha:1.0)
  141. imageViewUserImage.layer.cornerRadius = imageViewUserImage.frame.height / 2
  142. var frame = self.textViewPost.frame
  143. frame.size.height = self.textViewPost.contentSize.height
  144. self.textViewPost.frame = frame
  145. textViewPost.isScrollEnabled = true
  146. textViewPost.sizeToFit()
  147. NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
  148. NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
  149. buttonAddPhoto.setTitle(" Add Photo", for: UIControlState.normal)
  150. if statusUploadMode == 1 {
  151. selectImageToUpload()
  152. } else if statusUploadMode == 2 {
  153. if let postText = socialfeedviewmodel?.getSocialFeedAt(index: editablePostIndex!).feedText {
  154. socialfeedviewmodel?.updateFeedText(text: postText)
  155. textViewPost.text = postText
  156. }
  157. if let imageId = socialfeedviewmodel?.getSocialFeedAt(index: editablePostIndex!).feedImageId {
  158. buttonAddPhoto.setTitle(" Change Photo", for: UIControlState.normal)
  159. socialfeedviewmodel?.setFeedImageId(imageId: imageId)
  160. if let imageURL = socialfeedviewmodel?.getSocialFeedAt(index: editablePostIndex!).feedImage {
  161. imageViewPost.sd_setImage(with: URL(string: imageURL)!, placeholderImage: nil, options: [.progressiveDownload,.scaleDownLargeImages], completed: nil)
  162. postImageHeight.constant = view.frame.width
  163. }
  164. }
  165. }
  166. socialfeedviewmodel?.socialFeedsRxValue.bind { [weak self] in
  167. guard $0 != nil else {
  168. return
  169. }
  170. self?.enableUserInteractions()
  171. if self?.activityIndicator != nil {
  172. self?.dismissActivityIndicator(activityIndicator: (self?.activityIndicator)!)
  173. }
  174. guard $0 != 0 else {
  175. self?.textViewPost.resignFirstResponder()
  176. self?.popUpMessageError(value: 10, message: (self?.socialfeedviewmodel!.getErrorMessage())!)
  177. self?.socialfeedviewmodel!.socialFeedsRxValue.value = nil
  178. return
  179. }
  180. if $0 == socialWallCode.createUpdatePost.rawValue {
  181. if self?.shareModeIndex == 1 {
  182. self?.performSegue(withIdentifier: "myStory", sender: nil)
  183. } else {
  184. self?.navigationController?.popViewController(animated: true)
  185. }
  186. }
  187. self?.socialfeedviewmodel!.socialFeedsRxValue.value = nil
  188. }
  189. socialfeedviewmodel?.imageUploaded.bind { [weak self] in
  190. guard $0 != nil else {
  191. return
  192. }
  193. guard $0! else {
  194. self?.popUpMessageError(value: 10, message: (self?.socialfeedviewmodel!.getErrorMessage())!)
  195. return
  196. }
  197. self?.buttonSharePost.isEnabled = true
  198. self?.socialfeedviewmodel?.imageUploaded.value = nil
  199. }
  200. }
  201. @objc func keyboardWillShow(notification: NSNotification) {
  202. let userInfo = notification.userInfo
  203. var keyboardFrame:CGRect = (userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
  204. keyboardFrame = self.view.convert(keyboardFrame, from: nil)
  205. movement = (keyboardFrame.size.height)
  206. UIView.animate(withDuration: 0.3, animations: {
  207. self.viewShare.frame = self.viewShare.frame.offsetBy(dx: 0, dy: self.movement * -1.0) //dy is negative for upward movement
  208. })
  209. }
  210. @objc func keyboardWillHide(notification: NSNotification){
  211. UIView.animate(withDuration: 0.3, animations: {
  212. self.viewShare.frame = self.viewShare.frame.offsetBy(dx: 0, dy: self.movement)
  213. })
  214. }
  215. @IBAction func pickerButtonTap(_ sender: Any) {
  216. if dropDownView.isHidden{
  217. dropDownView.isHidden = false
  218. }
  219. textViewPost.resignFirstResponder()
  220. }
  221. override func viewDidAppear(_ animated: Bool) {
  222. shareScrollView.frame.size.width = self.view.frame.width
  223. }
  224. @IBAction func addPhotoButtonTap(_ sender: Any) {
  225. selectImageToUpload()
  226. }
  227. /**
  228. Display image selection option dialog for camera or Gallary
  229. */
  230. func selectImageToUpload() {
  231. let alert = UIAlertController(title: "Choose Image", message: nil, preferredStyle: .actionSheet)
  232. alert.addAction(UIAlertAction(title: "Camera", style: .default, handler: { _ in
  233. self.openCamera()
  234. }))
  235. alert.addAction(UIAlertAction(title: "Gallery", style: .default, handler: { _ in
  236. self.openGallery()
  237. }))
  238. alert.addAction(UIAlertAction.init(title: "Cancel", style: .destructive, handler: nil))
  239. self.present(alert, animated: true, completion: nil)
  240. }
  241. /**
  242. open camera
  243. */
  244. func openCamera() {
  245. if(UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.camera)) {
  246. imagePicker.sourceType = UIImagePickerControllerSourceType.camera
  247. imagePicker.allowsEditing = true
  248. present(imagePicker, animated: true, completion: nil)
  249. }
  250. else {
  251. let alert = UIAlertController(title: "Warning", message: "You don't have camera", preferredStyle: .alert)
  252. alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
  253. self.present(alert, animated: true, completion: nil)
  254. }
  255. }
  256. /**
  257. Open gallery for image selection
  258. */
  259. func openGallery() {
  260. imagePicker.sourceType = UIImagePickerControllerSourceType.photoLibrary
  261. imagePicker.allowsEditing = true
  262. present(imagePicker, animated: true, completion: nil)
  263. }
  264. override func didReceiveMemoryWarning() {
  265. super.didReceiveMemoryWarning()
  266. }
  267. }
  268. extension StatusUploadViewController: UIPickerViewDelegate, UIPickerViewDataSource {
  269. func numberOfComponents(in pickerView: UIPickerView) -> Int {
  270. return 1
  271. }
  272. func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
  273. return shareMode.count
  274. }
  275. func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
  276. return shareMode[row]
  277. }
  278. func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView {
  279. let label = (view as? UILabel) ?? UILabel()
  280. label.textColor = UIColor(red:0.29, green:0.29, blue:0.29, alpha:1.0)
  281. label.textAlignment = .center
  282. label.font = UIFont.systemFont(ofSize: 14)
  283. /// where data is an Array of String
  284. label.text = shareMode[row]
  285. return label
  286. }
  287. func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
  288. dropDownButton.setTitle(shareMode[row], for: UIControlState.normal)
  289. self.dropDownView.isHidden = true
  290. shareModeIndex = row
  291. textViewPost.resignFirstResponder()
  292. }
  293. }
  294. extension StatusUploadViewController: UITextViewDelegate {
  295. func textViewDidBeginEditing(_ textFieldPost: UITextView) {
  296. if textFieldPost.text.removeSpacesTrailingPreceding() == "Share your story" {
  297. textFieldPost.text = ""
  298. }
  299. if statusUploadMode == 2 {
  300. textFieldPost.textColor = UIColor(red:0.29, green:0.29, blue:0.29, alpha:1.0)
  301. }
  302. if textFieldPost.textColor == UIColor(red:0.78, green:0.78, blue:0.80, alpha:1.0) {
  303. textFieldPost.text = nil
  304. textFieldPost.textColor = UIColor(red:0.29, green:0.29, blue:0.29, alpha:1.0)
  305. }
  306. }
  307. func textViewDidEndEditing(_ textFieldPost: UITextView) {
  308. if textFieldPost.text.isEmpty {
  309. textFieldPost.text = "Share your story"
  310. textFieldPost.textColor = UIColor(red:0.78, green:0.78, blue:0.80, alpha:1.0)
  311. }
  312. }
  313. func textViewDidChange(_ textView: UITextView) {
  314. let size = textView.sizeThatFits(CGSize(width: textView.frame.size.width, height: CGFloat.greatestFiniteMagnitude))
  315. if size.height != textViewConstraint.constant && size.height > textView.frame.size.height || size.height < textView.frame.size.height{
  316. textViewConstraint.constant = size.height + 8
  317. textView.setContentOffset(CGPoint.zero, animated: false)
  318. }
  319. }
  320. func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
  321. feedInputText = (textView.text! as NSString).replacingCharacters(in: range, with: text)
  322. socialfeedviewmodel?.updateFeedText(text: feedInputText)
  323. return true
  324. }
  325. }
  326. extension StatusUploadViewController: UINavigationControllerDelegate, UIImagePickerControllerDelegate {
  327. func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
  328. if let image = info[UIImagePickerControllerEditedImage] as? UIImage {
  329. self.buttonSharePost.isEnabled = false
  330. imageViewPost.image = image
  331. buttonAddPhoto.setTitle(" Change Photo", for: UIControlState.normal)
  332. if let imageURL = info["UIImagePickerControllerImageURL"] as? NSURL {
  333. //GALLERY SELECTION
  334. let imageExtension = imageURL.lastPathComponent?.suffix(3)// (imageURL as! String).suffix(3)
  335. if imageExtension!.lowercased() == "gif" {
  336. do {
  337. let gifData = try Data(contentsOf: imageURL as URL)
  338. socialfeedviewmodel?.uploadImage(image: gifData, isGif: true)
  339. } catch let e {
  340. }
  341. } else {
  342. socialfeedviewmodel?.uploadImage(image: image, isGif: false)
  343. }
  344. } else {
  345. //CAMERA SELECTION
  346. socialfeedviewmodel?.uploadImage(image: image, isGif: false)
  347. }
  348. dismiss(animated: true, completion: nil)
  349. } else {
  350. }
  351. }
  352. func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
  353. dismiss(animated: true, completion: nil)
  354. }
  355. func didCropImage(_ croppedImage: UIImage, usingCropRect cropRect: CGRect){
  356. }}