PublishEditController.swift 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505
  1. //
  2. // PublishEditController.swift
  3. // RainbowPlanet
  4. //
  5. // Created by Christopher on 2019/6/17.
  6. // Copyright © 2019 RainbowPlanet. All rights reserved.
  7. // 编辑发布Vc
  8. import UIKit
  9. import RxSwift
  10. import SwiftyJSON
  11. import Photos
  12. @objc(PublishMediaType)
  13. enum PublishMediaType: Int {
  14. case image = 0
  15. case video = 1
  16. }
  17. class PublishEditController: BaseViewController {
  18. @objc var mediaType: PublishMediaType = .image
  19. @objc var videoPath: String = ""
  20. @objc var coverImagePath: String = ""
  21. @objc var videoSize: CGSize = CGSize()
  22. @objc var videoImage: UIImage? {
  23. didSet {
  24. imageArr = [videoImage] as? Array<UIImage>
  25. }
  26. }
  27. var imgCount: Int = 0
  28. var majorImageUrl: String?
  29. var imageUrlArray: Array<String> = []
  30. var imageArr: Array<UIImage>? {
  31. didSet {
  32. imgCount = self.imageArr?.count ?? 0
  33. }
  34. }
  35. // 选中的话题
  36. var selTopicModelArr: Array<CommunityTopicDataModel> = []
  37. // 已选话题id
  38. var selTopicIdArr: Array<String> = []
  39. // 已选话题name
  40. var selTopicName: String = ""
  41. // 标题
  42. var pubTitle: String = ""
  43. // 内容
  44. var pubContent: String = ""
  45. // 位置
  46. var locationStr: String = ""
  47. // 视频id,当type为video时必填
  48. var paraVideo: String = ""
  49. var uploadManager: AlivcShortVideoUploadManager?
  50. var vUploadFinished: Bool?
  51. // MARK: 控制器生命周期
  52. override func viewDidLoad() {
  53. super.viewDidLoad()
  54. setupViews()
  55. setupData()
  56. // imageUrlArray每次进入页面需置空
  57. imageUrlArray = []
  58. rightButton.isEnabled = false
  59. rightButton.backgroundColor = kd8d8d8Color
  60. if mediaType == .video {
  61. subLabel.text = "视频正在上传中(0/1)..."
  62. communityVideoUploadAuthApi()
  63. print("----上传视频")
  64. }
  65. if mediaType == .image {
  66. subLabel.text = "图片正在上传中(0/\(imageArr?.count ?? 0))..."
  67. uploadAllImages(totalTimes: 0)
  68. }
  69. }
  70. override func viewWillAppear(_ animated: Bool) {
  71. // let serialQueue = DispatchQueue(label: "serial_queue")
  72. // serialQueue.async {
  73. // print("----startUpLoad\n----\(Thread.current)")
  74. // self.uploadAllImages(totalTimes: 0)
  75. // }
  76. // DispatchQueue.main.async {
  77. // print("----startUpLoad\n----\(Thread.current)")
  78. // self.uploadAllImages(totalTimes: 0)
  79. // }
  80. }
  81. override func setupViews() {
  82. self.view.backgroundColor = kffffffColor
  83. navigationBar.title = ""
  84. navigationBar.wr_setLeftButton(image: kImage(name: "navbar_back_black")!)
  85. navigationBar.onClickLeftButton = {
  86. [weak self] in
  87. AlertSheetView.alert(title: "是否退出内容发布?退出后你所编辑的内容无法恢复!", cancelTitle: "取消", sureTitle: "确认", cancelBlock: { (popupView, index, string) in
  88. }, confirmBlock: {
  89. (popupView, index, string) in
  90. NotificationCenter.default.post(name: NSNotification.Name(rawValue: "DismissFromPublishEditVc"), object: nil)
  91. })
  92. }
  93. view.addSubview(rightButton)
  94. rightButton.snp.makeConstraints { (make) in
  95. make.top.equalToSuperview().offset(kSafeStatusBarHeight+8)
  96. make.right.equalTo(-14)
  97. make.width.equalTo(64)
  98. make.height.equalTo(26)
  99. }
  100. view.addSubview(progressBackView)
  101. progressBackView.addSubview(progressView)
  102. progressBackView.addSubview(subLabel)
  103. progressBackView.snp.makeConstraints { (make) in
  104. make.top.equalToSuperview().offset(kNavBarTotalHeight)
  105. make.left.right.equalToSuperview()
  106. make.height.equalTo(38)
  107. }
  108. progressView.snp.makeConstraints { (make) in
  109. make.top.left.right.equalToSuperview()
  110. make.height.equalTo(3)
  111. }
  112. subLabel.snp.makeConstraints { (make) in
  113. make.left.equalTo(14)
  114. make.centerY.equalToSuperview()
  115. make.height.equalTo(20)
  116. }
  117. view.addSubview(tableView)
  118. tableView.snp.makeConstraints { (make) in
  119. make.top.equalTo(progressBackView.snp_bottom)
  120. make.left.right.bottom.equalToSuperview()
  121. }
  122. }
  123. override func setupData() {
  124. }
  125. lazy var tableView: UITableView = {
  126. let tableView = UITableView(frame: CGRect.zero, style: UITableView.Style.grouped)
  127. tableView.separatorStyle = .none
  128. tableView.backgroundColor = kffffffColor
  129. tableView.dataSource = self
  130. tableView.delegate = self
  131. tableView.estimatedRowHeight = 0.000001
  132. tableView.estimatedSectionFooterHeight = 0.000001
  133. tableView.estimatedSectionHeaderHeight = 0.000001
  134. return tableView
  135. }()
  136. private lazy var rightButton: UIButton = {
  137. let rightButton = UIButton(type: UIButton.ButtonType.custom)
  138. rightButton.setTitle("发布", for: UIControl.State.normal)
  139. rightButton.setTitleColor(kffffffColor, for: UIControl.State.normal)
  140. rightButton.titleLabel?.font = kMediumFont13
  141. rightButton.cornerRadius = 16
  142. rightButton.masksToBounds = true
  143. rightButton.rx.tap.subscribe(onNext: { [weak self] (data) in
  144. self?.communityPublishApi()
  145. }).disposed(by: disposeBag)
  146. return rightButton
  147. }()
  148. private lazy var progressBackView: UIView = {
  149. let progressBackView = UIView()
  150. progressBackView.backgroundColor = kffffffColor
  151. return progressBackView
  152. }()
  153. private lazy var progressView: UIProgressView = {
  154. let progressView = UIProgressView(progressViewStyle: .default)
  155. progressView.setProgress(0, animated: false)
  156. progressView.progressTintColor = k62CC74Color //进度颜色
  157. progressView.trackTintColor = kd8d8d8Color //剩余进度颜色
  158. return progressView
  159. }()
  160. private lazy var subLabel: UILabel = {
  161. let subLabel = UILabel()
  162. subLabel.textColor = k333333Color
  163. subLabel.font = kRegularFont14
  164. subLabel.textAlignment = .left
  165. return subLabel
  166. }()
  167. }
  168. // MARK: - tableView dataSource && delegate
  169. extension PublishEditController : UITableViewDelegate, UITableViewDataSource {
  170. func numberOfSections(in tableView: UITableView) -> Int {
  171. return 1
  172. }
  173. func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
  174. return 5
  175. }
  176. func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
  177. switch indexPath.row {
  178. case 0:
  179. let picCell = PublishEditAddPicCell.cellWith(tableView: tableView, indexPath: indexPath)
  180. picCell.pubImageArr = imageArr
  181. if mediaType == .video {
  182. picCell.maxImageCount = 1
  183. }
  184. picCell.reloadData()
  185. picCell.choosePicBlock = {
  186. [weak self] in
  187. print("\n----选取图片")
  188. }
  189. picCell.delPicTransBlock = {
  190. [weak self] (picIdx) in
  191. self?.imageArr?.remove(at: picIdx!)
  192. self?.imageUrlArray.remove(at: picIdx!)
  193. self?.tableView.reloadData()
  194. }
  195. return picCell
  196. case 1:
  197. let titleCell = PublishEditTitleCell.cellWith(tableView: tableView, indexPath: indexPath)
  198. titleCell.topicTextClosure = {
  199. [weak self] (text) in
  200. self?.pubTitle = text
  201. }
  202. return titleCell
  203. case 2:
  204. let desCell = PublishEditDescribeCell.cellWith(tableView: tableView, indexPath: indexPath)
  205. desCell.commentTextViewClosure = {
  206. [weak self] (text) in
  207. self?.pubContent = text
  208. }
  209. return desCell
  210. case 3:
  211. let topicCell = PublishEditAddTopicCell.cellWith(tableView: tableView, indexPath: indexPath)
  212. topicCell.isTopicsNull = selTopicIdArr.count == 0 ? true : false
  213. topicCell.selTopicName = selTopicName
  214. return topicCell
  215. case 4:
  216. let addrCell = PublishEditAddAddressCell.cellWith(tableView: tableView, indexPath: indexPath)
  217. addrCell.location = locationStr
  218. return addrCell
  219. default:
  220. return UITableViewCell()
  221. }
  222. }
  223. func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
  224. switch indexPath.row {
  225. case 3:
  226. let vc = PublishAddTopicController()
  227. vc.selTopicModelArr = self.selTopicModelArr
  228. vc.selTopicsClosure = {
  229. [weak self] (topicMdlArr) in
  230. self?.selTopicModelArr = topicMdlArr
  231. self?.selTopicName = ""
  232. self?.selTopicIdArr.removeAll()
  233. for (index,topicModel) in (topicMdlArr.enumerated()) {
  234. let strTopicId: String = String(format: "%d", topicModel.id ?? 0)
  235. self?.selTopicIdArr.append(strTopicId)
  236. if index == 0 {
  237. self?.selTopicName.append(topicModel.name!)
  238. } else {
  239. self?.selTopicName.append(", \(topicModel.name!)")
  240. }
  241. }
  242. self?.tableView.reloadRows(at: [indexPath], with: UITableView.RowAnimation.none)
  243. }
  244. self.navigationController?.pushViewController(vc, animated: true)
  245. case 4:
  246. let vc = PublishAddAddressController()
  247. vc.selectLocationClosure = {
  248. [weak self] (address) in
  249. self?.locationStr = address
  250. self?.tableView.reloadRows(at: [indexPath], with: UITableView.RowAnimation.none)
  251. }
  252. self.navigationController?.pushViewController(vc, animated: true)
  253. default:
  254. break
  255. }
  256. }
  257. func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
  258. switch indexPath.row {
  259. case 0:
  260. return 130
  261. case 1,3,4:
  262. return 50
  263. case 2:
  264. return 190
  265. default:
  266. return UITableView.automaticDimension
  267. }
  268. }
  269. func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
  270. return 0
  271. }
  272. func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
  273. return nil
  274. }
  275. func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
  276. return 0.000001
  277. }
  278. func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
  279. return nil
  280. }
  281. }
  282. // MARK: - 逻辑处理
  283. extension PublishEditController {
  284. func uploadAllImages(totalTimes: Int) {
  285. var curTimes: Int = totalTimes
  286. print("-----StartUpload,totalTimes == \(totalTimes)")
  287. SwiftMoyaNetWorkServiceConfig.shared().configUploadSingleImgWithoutHudApi(imageArray: [self.imageArr![totalTimes]]) {
  288. [weak self] (imgUrl) -> (Void) in
  289. let urlStr: String = imgUrl as! String
  290. self?.imageUrlArray.append(urlStr)
  291. if curTimes == 0 {
  292. // 设置主图
  293. self?.majorImageUrl = urlStr
  294. }
  295. print("-----FinishUpload,Times == \(curTimes)")
  296. curTimes += 1
  297. // 更新进度
  298. DispatchQueue.main.async {
  299. print("----\(Thread.current)")
  300. self?.progressView.setProgress(Float(curTimes/(self?.imageArr!.count)!), animated: true)
  301. }
  302. if curTimes == self?.imageArr!.count {
  303. self?.subLabel.text = "图片上传成功!"
  304. } else {
  305. self?.subLabel.text = "图片正在上传中(\(curTimes)/\(self?.imageArr?.count ?? 0))..."
  306. }
  307. if curTimes < self?.imageArr?.count ?? 0 {
  308. self?.uploadAllImages(totalTimes: curTimes)
  309. } else {
  310. self?.rightButton.isEnabled = true
  311. self?.rightButton.backgroundColor = k62CC74Color
  312. }
  313. }
  314. }
  315. // 发布Api
  316. func communityPublishApi() {
  317. if pubTitle.count > 20 {
  318. SwiftProgressHUD.shared().showText("标题最多输入20个字符")
  319. return
  320. }
  321. if pubContent.count == 0 {
  322. SwiftProgressHUD.shared().showText("还没输入描述内容")
  323. return
  324. }
  325. if selTopicIdArr.count == 0 {
  326. SwiftProgressHUD.shared().showText("还没选择话题哟")
  327. return
  328. }
  329. var typeStr: String = ""
  330. if mediaType == .image {
  331. typeStr = "image"
  332. } else {
  333. typeStr = "video"
  334. }
  335. let topicJsonStr = JSON(selTopicIdArr).description
  336. let imgsJsonStr = JSON(imageUrlArray).description
  337. print("----mediaType == \(typeStr)\n----pubTitle = \(pubTitle)\n----topicJsonStr == \(topicJsonStr)\n----imgsJsonStr == \(imgsJsonStr)")
  338. SwiftMoyaNetWorkServiceCommunity.shared().communityPublishApi(type: typeStr, img: majorImageUrl ?? "", topic_ids: topicJsonStr, video: paraVideo, title: pubTitle, content: pubContent, location: locationStr, imgs: imgsJsonStr) {
  339. [weak self] (communityPublishModel) -> (Void) in
  340. let communityPublishModel = communityPublishModel as? CommunityPublishModel
  341. self?.publishSuccessAction(communityPublishModel!)
  342. }
  343. }
  344. func publishSuccessAction(_ pubModel: CommunityPublishModel) {
  345. var typeStr: String = ""
  346. if mediaType == .image {
  347. typeStr = "image"
  348. } else {
  349. typeStr = "video"
  350. }
  351. VirusViewModel.shared.publishVirueRecordAddApi(postId: pubModel.postId, postType: typeStr, title: pubTitle, content: pubContent, postCover: majorImageUrl)
  352. let sucVc = PublishSuccessController()
  353. sucVc.postId = pubModel.postId
  354. sucVc.bean = pubModel.bean
  355. sucVc.H5UrlStr = pubModel.h5url
  356. sucVc.imgUrl = majorImageUrl
  357. sucVc.titleStr = pubTitle
  358. sucVc.contentStr = pubContent
  359. // 暂给已选首个
  360. sucVc.topicStr = selTopicModelArr[0].name ?? ""
  361. let userMdl = UserModel.shared().getModel()
  362. sucVc.nameStr = userMdl?.username
  363. sucVc.avatarStr = userMdl?.avatarurl
  364. sucVc.uid = userMdl?.uid
  365. sucVc.type = typeStr
  366. self.navigationController?.pushViewController(sucVc, animated: true)
  367. }
  368. }
  369. // MARK: - 视频相关处理
  370. extension PublishEditController: AlivcShortVideoUploadManagerDelegate {
  371. // 获取上传地址和凭证
  372. func communityVideoUploadAuthApi() {
  373. var vTitle: String = ""
  374. if videoPath.count > 20 {
  375. vTitle = String(videoPath.suffix(20))
  376. } else {
  377. vTitle = videoPath
  378. }
  379. SwiftMoyaNetWorkServiceCommunity.shared().communityVideoUploadAuthApi(title: vTitle, filename: vTitle, cover_url: coverImagePath) {
  380. [weak self] (communityVideoAuthModel) -> (Void) in
  381. let communityVideoAuthModel = communityVideoAuthModel as? CommunityVideoAuthModel
  382. self?.paraVideo = communityVideoAuthModel?.videoId ?? ""
  383. self?.startUploadVideo(communityVideoAuthModel!)
  384. }
  385. }
  386. // 上传视频
  387. func startUploadVideo(_ authModel: CommunityVideoAuthModel) {
  388. let info = AliyunUploadSVideoInfo()
  389. uploadManager = AlivcShortVideoUploadManager.shared()
  390. uploadManager?.setCoverImagePath(coverImagePath, videoInfo: info, videoPath: videoPath)
  391. uploadManager?.managerDelegate = self
  392. uploadManager?.uploadAddress = authModel.uploadAddress
  393. uploadManager?.videoId = authModel.videoId
  394. uploadManager?.uploadAuth = authModel.uploadAuth
  395. uploadManager?.startUpload()
  396. }
  397. // 上传进度回调
  398. func uploadManager(_ manager: AlivcShortVideoUploadManager!, updateProgress progress: CGFloat) {
  399. DispatchQueue.main.async(execute: {
  400. self.progressView.progress = Float(progress)
  401. })
  402. }
  403. // 上传状态回调
  404. func uploadManager(_ manager: AlivcShortVideoUploadManager!, uploadStatusChangedTo newStatus: AlivcUploadStatus) {
  405. switch newStatus {
  406. case AlivcUploadStatus.failure:
  407. DispatchQueue.main.async(execute: {
  408. self.subLabel.text = "上传失败!"
  409. SwiftProgressHUD.shared().showText("上传失败!")
  410. })
  411. case AlivcUploadStatus.success:
  412. // 上传封面图
  413. self.uploadVideoCoverImage()
  414. default:
  415. break
  416. }
  417. }
  418. // 上传视频封面图
  419. func uploadVideoCoverImage() {
  420. SwiftMoyaNetWorkServiceConfig.shared().configUploadSingleImgWithoutHudApi(imageArray: [videoImage!]) {
  421. [weak self] (imgUrl) -> (Void) in
  422. // 设置主图
  423. self?.majorImageUrl = imgUrl as? String
  424. self?.vUploadFinished = true
  425. self?.subLabel.text = "上传成功!"
  426. self?.rightButton.isEnabled = true
  427. self?.rightButton.backgroundColor = k62CC74Color
  428. }
  429. }
  430. }