ShareViewController.swift 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787
  1. //
  2. // ShareViewController.swift
  3. // AppBuilderShare
  4. //
  5. // Created by Qindi on 11/02/25.
  6. //
  7. import UIKit
  8. import Social
  9. import UniformTypeIdentifiers
  10. import AVFoundation
  11. import QuickLook
  12. class ShareViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UISearchBarDelegate, UITextViewDelegate, QLPreviewControllerDataSource {
  13. let tableView = UITableView()
  14. let searchBar = UISearchBar()
  15. var contacts: [Contact] = []
  16. var filteredContacts: [Contact] = []
  17. var selectedContact: Contact!
  18. private var textViewBottomConstraint: NSLayoutConstraint?
  19. private var containerBottomConstraint: NSLayoutConstraint?
  20. private var heightTextView: NSLayoutConstraint?
  21. let vcHandleText = UIViewController()
  22. let vcHandleImage = UIViewController()
  23. let vcHandleVideo = UIViewController()
  24. let vcHandleFile = UIViewController()
  25. var textView = UITextView()
  26. var typeShareNum = 0
  27. var selectedImage: URL!
  28. var selectedVideo: URL!
  29. var selectedFile: URL!
  30. private var previewView: VideoPreviewView?
  31. let previewController = QLPreviewController()
  32. override func viewDidLoad() {
  33. super.viewDidLoad()
  34. loadCustomContacts()
  35. registerKeyboardNotifications()
  36. }
  37. deinit {
  38. NotificationCenter.default.removeObserver(self) // Remove observers when view controller deallocates
  39. }
  40. override func viewDidAppear(_ animated: Bool) {
  41. setupUI()
  42. }
  43. func setupUI() {
  44. let cancelButton = UIBarButtonItem(title: "Cancel", style: .plain, target: self, action: #selector(cancelAction))
  45. cancelButton.tintColor = .label
  46. self.navigationItem.leftBarButtonItem = cancelButton
  47. // Search Bar (Right)
  48. searchBar.placeholder = "Search"
  49. searchBar.delegate = self
  50. searchBar.sizeToFit()
  51. self.navigationItem.titleView = searchBar
  52. self.navigationController?.navigationBar.backgroundColor = .systemBackground
  53. self.navigationController?.navigationBar.tintColor = .label
  54. // TableView Setup
  55. tableView.translatesAutoresizingMaskIntoConstraints = false
  56. tableView.delegate = self
  57. tableView.dataSource = self
  58. tableView.register(ContactCell.self, forCellReuseIdentifier: "ContactCell")
  59. tableView.separatorStyle = .singleLine
  60. view.addSubview(tableView)
  61. // Auto Layout Constraints
  62. NSLayoutConstraint.activate([
  63. tableView.topAnchor.constraint(equalTo: view.topAnchor),
  64. tableView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
  65. tableView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
  66. tableView.bottomAnchor.constraint(equalTo: view.bottomAnchor)
  67. ])
  68. }
  69. func loadCustomContacts() {
  70. if let userDefaults = UserDefaults(suiteName: "group.nexilis.share"),
  71. let value = userDefaults.string(forKey: "shareContacts") {
  72. if let jsonData = value.data(using: .utf8) {
  73. do {
  74. if let jsonArray = try JSONSerialization.jsonObject(with: jsonData, options: []) as? [[String: Any]] {
  75. for json in jsonArray {
  76. let id = json["id"] as? String ?? ""
  77. let name = json["name"] as? String ?? ""
  78. let imageId = json["image"] as? String ?? ""
  79. let type = json["type"] as? Int ?? 0
  80. var profileImage = type == 0 ? UIImage(systemName: "person.fill") : UIImage(systemName: "bubble.right.fill")
  81. if !imageId.isEmpty {
  82. if let appGroupURL = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "group.nexilis.share") {
  83. let sharedFileURL = appGroupURL.appendingPathComponent(imageId)
  84. if FileManager.default.fileExists(atPath: sharedFileURL.path) {
  85. profileImage = UIImage(contentsOfFile: sharedFileURL.path)
  86. }
  87. }
  88. }
  89. contacts.append(Contact(id: id, name: name, profileImage: profileImage, imageId: imageId, typeContact: "\(type)"))
  90. }
  91. filteredContacts = contacts
  92. tableView.reloadData()
  93. }
  94. } catch {
  95. print("Error parsing JSON: \(error)")
  96. }
  97. }
  98. }
  99. }
  100. // TableView DataSource Methods
  101. func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
  102. return filteredContacts.count
  103. }
  104. func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
  105. return 60
  106. }
  107. func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
  108. let cell = tableView.dequeueReusableCell(withIdentifier: "ContactCell", for: indexPath) as! ContactCell
  109. cell.separatorInset = UIEdgeInsets(top: 0, left: 65, bottom: 0, right: 25)
  110. let contact = filteredContacts[indexPath.row]
  111. cell.configure(with: contact)
  112. return cell
  113. }
  114. // Handle Contact Selection
  115. func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
  116. tableView.deselectRow(at: indexPath, animated: true)
  117. selectedContact = filteredContacts[indexPath.row]
  118. handleSharedContent(selectedContact)
  119. }
  120. // Cancel Button Action
  121. @objc func cancelAction() {
  122. self.extensionContext?.completeRequest(returningItems: nil, completionHandler: nil)
  123. }
  124. @objc func sendAction() {
  125. if let userDefaults = UserDefaults(suiteName: "group.nexilis.share") {
  126. do {
  127. var dataShared: [String: Any] = [:]
  128. dataShared["typeShare"] = typeShareNum
  129. dataShared["typeContact"] = selectedContact.typeContact
  130. dataShared["idContact"] = selectedContact.id
  131. dataShared["data"] = textView.text
  132. if typeShareNum == TypeShare.image {
  133. let compressedImageName = "Nexilis_image_\(Int(Date().timeIntervalSince1970 * 1000))_\(selectedImage.lastPathComponent)"
  134. let thumbName = "THUMB_Nexilis_image_\(Int(Date().timeIntervalSince1970 * 1000))_\(selectedImage.lastPathComponent)"
  135. if let appGroupURL = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "group.nexilis.share") {
  136. let sharedImageURL = appGroupURL.appendingPathComponent(compressedImageName)
  137. let sharedThumbURL = appGroupURL.appendingPathComponent(thumbName)
  138. try? UIImage(contentsOfFile: selectedImage.path)?.jpegData(compressionQuality: 0.25)?.write(to: sharedThumbURL)
  139. try? UIImage(contentsOfFile: selectedImage.path)?.jpegData(compressionQuality: 0.5)?.write(to: sharedImageURL)
  140. }
  141. dataShared["thumb"] = thumbName
  142. dataShared["image"] = compressedImageName
  143. let jsonData = try JSONSerialization.data(withJSONObject: dataShared, options: .prettyPrinted)
  144. if let jsonString = String(data: jsonData, encoding: .utf8) {
  145. userDefaults.set(jsonString, forKey: "sharedItem")
  146. userDefaults.synchronize()
  147. let notificationName = "realtimeShareExtensionNexilis" as CFString
  148. CFNotificationCenterPostNotification(
  149. CFNotificationCenterGetDarwinNotifyCenter(),
  150. CFNotificationName(notificationName),
  151. nil,
  152. nil,
  153. true
  154. )
  155. }
  156. } else if typeShareNum == TypeShare.video {
  157. let dataVideo = try? Data(contentsOf: selectedVideo)
  158. if let dataVideotoCompress = dataVideo {
  159. let sizeInKB = Double(dataVideotoCompress.count) / 1024.0
  160. let sizeOfVideo = sizeInKB / 1024.0
  161. if (sizeOfVideo > 10.0) {
  162. let compressedURL = NSURL.fileURL(withPath: NSTemporaryDirectory() + UUID().uuidString + ".mp4")
  163. compressVideo(inputURL: selectedVideo,
  164. outputURL: compressedURL) { exportSession in
  165. guard let session = exportSession else {
  166. return
  167. }
  168. switch session.status {
  169. case .unknown:
  170. break
  171. case .waiting:
  172. break
  173. case .exporting:
  174. break
  175. case .completed:
  176. guard let compressedData = try? Data(contentsOf: compressedURL) else {
  177. return
  178. }
  179. self.sendVideoToMainApp(compressedData, dataShared)
  180. case .failed:
  181. break
  182. case .cancelled:
  183. break
  184. @unknown default:
  185. break
  186. }
  187. }
  188. return
  189. } else {
  190. self.sendVideoToMainApp(dataVideotoCompress, dataShared)
  191. }
  192. }
  193. } else if typeShareNum == TypeShare.file {
  194. let fileName = selectedFile.lastPathComponent
  195. if let appGroupURL = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "group.nexilis.share") {
  196. let sharedFileURL = appGroupURL.appendingPathComponent(fileName)
  197. try? Data(contentsOf: selectedFile).write(to: sharedFileURL)
  198. }
  199. dataShared["file"] = fileName
  200. let jsonData = try JSONSerialization.data(withJSONObject: dataShared, options: .prettyPrinted)
  201. if let jsonString = String(data: jsonData, encoding: .utf8) {
  202. userDefaults.set(jsonString, forKey: "sharedItem")
  203. userDefaults.synchronize()
  204. let notificationName = "realtimeShareExtensionNexilis" as CFString
  205. CFNotificationCenterPostNotification(
  206. CFNotificationCenterGetDarwinNotifyCenter(),
  207. CFNotificationName(notificationName),
  208. nil,
  209. nil,
  210. true
  211. )
  212. }
  213. } else {
  214. let jsonData = try JSONSerialization.data(withJSONObject: dataShared, options: .prettyPrinted)
  215. if let jsonString = String(data: jsonData, encoding: .utf8) {
  216. userDefaults.set(jsonString, forKey: "sharedItem")
  217. userDefaults.synchronize()
  218. let notificationName = "realtimeShareExtensionNexilis" as CFString
  219. CFNotificationCenterPostNotification(
  220. CFNotificationCenterGetDarwinNotifyCenter(),
  221. CFNotificationName(notificationName),
  222. nil,
  223. nil,
  224. true
  225. )
  226. }
  227. }
  228. } catch {
  229. }
  230. }
  231. self.extensionContext?.completeRequest(returningItems: nil, completionHandler: nil)
  232. }
  233. private func sendVideoToMainApp(_ data: Data, _ dataShared: [String: Any]) {
  234. do {
  235. var dataShared = dataShared
  236. let originalVideoName = self.selectedVideo.lastPathComponent
  237. let renamedVideoName = "Nexilis_video_\(Int(Date().timeIntervalSince1970 * 1000))_\(originalVideoName)"
  238. let thumbName = "THUMB_Nexilis_video_\(Int(Date().timeIntervalSince1970 * 1000))_\(originalVideoName)"
  239. if let appGroupURL = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "group.nexilis.share") {
  240. let sharedVideoURL = appGroupURL.appendingPathComponent(renamedVideoName)
  241. let sharedThumbURL = appGroupURL.appendingPathComponent(thumbName)
  242. try? data.write(to: sharedVideoURL)
  243. let asset = AVURLAsset(url: self.selectedVideo, options: nil)
  244. let imgGenerator = AVAssetImageGenerator(asset: asset)
  245. imgGenerator.appliesPreferredTrackTransform = true
  246. let cgImage = try imgGenerator.copyCGImage(at: CMTimeMake(value: 0, timescale: 1), actualTime: nil)
  247. let thumbnail = UIImage(cgImage: cgImage)
  248. try? thumbnail.jpegData(compressionQuality: 1.0)?.write(to: sharedThumbURL)
  249. dataShared["thumb"] = thumbName
  250. dataShared["video"] = renamedVideoName
  251. let jsonData = try JSONSerialization.data(withJSONObject: dataShared, options: .prettyPrinted)
  252. if let jsonString = String(data: jsonData, encoding: .utf8) {
  253. let userDefaults = UserDefaults(suiteName: "group.nexilis.share")
  254. userDefaults!.set(jsonString, forKey: "sharedItem")
  255. userDefaults!.synchronize()
  256. let notificationName = "realtimeShareExtensionNexilis" as CFString
  257. CFNotificationCenterPostNotification(
  258. CFNotificationCenterGetDarwinNotifyCenter(),
  259. CFNotificationName(notificationName),
  260. nil,
  261. nil,
  262. true
  263. )
  264. }
  265. }
  266. } catch {
  267. }
  268. }
  269. func compressVideo(inputURL: URL,
  270. outputURL: URL,
  271. handler:@escaping (_ exportSession: AVAssetExportSession?) -> Void) {
  272. let urlAsset = AVURLAsset(url: inputURL, options: nil)
  273. guard let exportSession = AVAssetExportSession(asset: urlAsset,
  274. presetName: AVAssetExportPresetMediumQuality) else {
  275. handler(nil)
  276. return
  277. }
  278. exportSession.outputURL = outputURL
  279. exportSession.outputFileType = .mp4
  280. exportSession.shouldOptimizeForNetworkUse = true
  281. exportSession.exportAsynchronously {
  282. handler(exportSession)
  283. }
  284. }
  285. @objc func backAction() {
  286. if let previewView = previewView {
  287. previewView.stopVideo()
  288. }
  289. self.dismiss(animated: false, completion: nil)
  290. }
  291. // SearchBar Delegate Methods
  292. func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
  293. if searchText.isEmpty {
  294. filteredContacts = contacts
  295. } else {
  296. filteredContacts = contacts.filter { $0.name.lowercased().contains(searchText.lowercased()) }
  297. }
  298. tableView.reloadData()
  299. }
  300. private func registerKeyboardNotifications() {
  301. NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(_:)), name: UIResponder.keyboardWillShowNotification, object: nil)
  302. NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(_:)), name: UIResponder.keyboardWillHideNotification, object: nil)
  303. }
  304. @objc private func keyboardWillShow(_ notification: Notification) {
  305. if let keyboardFrame = notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? CGRect {
  306. let keyboardHeight = keyboardFrame.height
  307. let info:NSDictionary = notification.userInfo! as NSDictionary
  308. let duration: CGFloat = info[UIResponder.keyboardAnimationDurationUserInfoKey] as! NSNumber as! CGFloat
  309. updateTextViewBottomConstraint(-keyboardHeight - 20, duration)
  310. }
  311. }
  312. @objc private func keyboardWillHide(_ notification: Notification) {
  313. let info:NSDictionary = notification.userInfo! as NSDictionary
  314. let duration: CGFloat = info[UIResponder.keyboardAnimationDurationUserInfoKey] as! NSNumber as! CGFloat
  315. updateTextViewBottomConstraint(-20, duration) // Reset bottom constraint
  316. }
  317. private func updateTextViewBottomConstraint(_ constant: CGFloat, _ duration: CGFloat) {
  318. if typeShareNum == TypeShare.text {
  319. textViewBottomConstraint?.constant = constant
  320. } else {
  321. containerBottomConstraint?.constant = constant + 20
  322. }
  323. UIView.animate(withDuration: TimeInterval(duration)) { // Smooth animation
  324. self.view.layoutIfNeeded()
  325. }
  326. }
  327. func textViewDidChange(_ textView: UITextView) {
  328. vcHandleText.navigationItem.rightBarButtonItem?.isEnabled = !textView.text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
  329. }
  330. func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
  331. if text == "\n" {
  332. textView.resignFirstResponder()
  333. return false
  334. }
  335. return true
  336. }
  337. func textViewDidChangeSelection(_ textView: UITextView) {
  338. if typeShareNum == TypeShare.text {
  339. return
  340. }
  341. let cursorPosition = textView.caretRect(for: textView.selectedTextRange!.start).origin
  342. let doubleCurrentLine = cursorPosition.y / textView.font!.lineHeight
  343. if doubleCurrentLine.isFinite {
  344. let currentLine = Int(doubleCurrentLine)
  345. UIView.animate(withDuration: 0.3) {
  346. let numberOfLines = textView.textContainer.lineBreakMode == .byWordWrapping ? Int(textView.contentSize.height / textView.font!.lineHeight) - 1 : 1
  347. if currentLine == 0 && numberOfLines == 1 {
  348. self.heightTextView?.constant = 45
  349. } else if currentLine >= 4 {
  350. self.heightTextView?.constant = 95.0
  351. } else if currentLine < 4 && numberOfLines < 5 {
  352. self.heightTextView?.constant = textView.contentSize.height
  353. }
  354. }
  355. }
  356. }
  357. func numberOfPreviewItems(in controller: QLPreviewController) -> Int {
  358. return 1
  359. }
  360. func previewController(_ controller: QLPreviewController, previewItemAt index: Int) -> QLPreviewItem {
  361. return selectedFile as QLPreviewItem
  362. }
  363. private func buildAppearance(_ contact: Contact, _ viewVc: UIView) {
  364. viewVc.backgroundColor = self.traitCollection.userInterfaceStyle == .dark ? .black : .white
  365. let buttonClose = UIButton(type: .system)
  366. buttonClose.setImage(UIImage(systemName: "xmark.circle.fill")?.withConfiguration(UIImage.SymbolConfiguration(pointSize: 40)), for: .normal)
  367. buttonClose.tintColor = .gray.withAlphaComponent(0.8)
  368. buttonClose.imageView?.contentMode = .scaleAspectFit
  369. buttonClose.clipsToBounds = true
  370. buttonClose.addTarget(self, action: #selector(backAction), for: .touchUpInside)
  371. viewVc.addSubview(buttonClose)
  372. buttonClose.translatesAutoresizingMaskIntoConstraints = false
  373. NSLayoutConstraint.activate([
  374. buttonClose.leadingAnchor.constraint(equalTo: viewVc.leadingAnchor, constant: 20.0),
  375. buttonClose.topAnchor.constraint(equalTo: viewVc.topAnchor, constant: 20.0),
  376. buttonClose.widthAnchor.constraint(equalToConstant: 40.0),
  377. buttonClose.heightAnchor.constraint(equalToConstant: 40.0),
  378. ])
  379. let containerView = UIView()
  380. containerView.backgroundColor = self.traitCollection.userInterfaceStyle == .dark ? .black : .white
  381. viewVc.addSubview(containerView)
  382. containerView.translatesAutoresizingMaskIntoConstraints = false
  383. NSLayoutConstraint.activate([
  384. containerView.leadingAnchor.constraint(equalTo: viewVc.leadingAnchor),
  385. containerView.trailingAnchor.constraint(equalTo: viewVc.trailingAnchor),
  386. containerView.heightAnchor.constraint(equalToConstant: 55)
  387. ])
  388. containerBottomConstraint = containerView.bottomAnchor.constraint(equalTo: viewVc.bottomAnchor)
  389. containerBottomConstraint?.isActive = true
  390. let containerTo = UIView()
  391. containerView.addSubview(containerTo)
  392. containerTo.translatesAutoresizingMaskIntoConstraints = false
  393. containerTo.layer.cornerRadius = 8
  394. containerTo.clipsToBounds = true
  395. containerTo.backgroundColor = .darkGray
  396. NSLayoutConstraint.activate([
  397. containerTo.leadingAnchor.constraint(equalTo: containerView.leadingAnchor, constant: 15),
  398. containerTo.bottomAnchor.constraint(equalTo: containerView.bottomAnchor, constant: -10),
  399. containerTo.heightAnchor.constraint(equalToConstant: 30),
  400. containerTo.widthAnchor.constraint(greaterThanOrEqualToConstant: 50)
  401. ])
  402. let textTo = UILabel()
  403. containerTo.addSubview(textTo)
  404. textTo.text = contact.name
  405. textTo.textColor = .white
  406. textTo.font = .systemFont(ofSize: 15)
  407. textTo.textAlignment = .center
  408. textTo.translatesAutoresizingMaskIntoConstraints = false
  409. NSLayoutConstraint.activate([
  410. textTo.leadingAnchor.constraint(equalTo: containerTo.leadingAnchor, constant: 10),
  411. textTo.trailingAnchor.constraint(equalTo: containerTo.trailingAnchor, constant: -10),
  412. textTo.centerYAnchor.constraint(equalTo: containerTo.centerYAnchor)
  413. ])
  414. let buttonTo = UIButton(type: .system)
  415. buttonTo.setImage(UIImage(systemName: "paperplane.circle.fill")?.withConfiguration(UIImage.SymbolConfiguration(pointSize: 35)), for: .normal)
  416. buttonTo.tintColor = .systemBlue
  417. buttonTo.addTarget(self, action: #selector(sendAction), for: .touchUpInside)
  418. containerView.addSubview(buttonTo)
  419. buttonTo.translatesAutoresizingMaskIntoConstraints = false
  420. NSLayoutConstraint.activate([
  421. buttonTo.trailingAnchor.constraint(equalTo: containerView.trailingAnchor, constant: -15),
  422. buttonTo.bottomAnchor.constraint(equalTo: containerView.bottomAnchor, constant: -10),
  423. buttonTo.widthAnchor.constraint(equalToConstant: 35),
  424. buttonTo.heightAnchor.constraint(equalToConstant: 35),
  425. ])
  426. textView = UITextView()
  427. viewVc.addSubview(textView)
  428. textView.textColor = .white
  429. textView.font = .systemFont(ofSize: 17)
  430. textView.textContainerInset = UIEdgeInsets(top: 10.5, left: 15, bottom: 10.5, right: 15)
  431. textView.translatesAutoresizingMaskIntoConstraints = false
  432. textView.layer.cornerRadius = 22.5
  433. textView.clipsToBounds = true
  434. textView.layer.borderColor = UIColor.gray.cgColor
  435. textView.layer.borderWidth = 1
  436. textView.delegate = self
  437. NSLayoutConstraint.activate([
  438. textView.trailingAnchor.constraint(equalTo: containerView.trailingAnchor, constant: -15),
  439. textView.leadingAnchor.constraint(equalTo: containerView.leadingAnchor, constant: 15),
  440. textView.bottomAnchor.constraint(equalTo: containerView.topAnchor, constant: -20),
  441. ])
  442. heightTextView = textView.heightAnchor.constraint(equalToConstant: 45)
  443. heightTextView?.isActive = true
  444. }
  445. func handleSharedContent(_ contact: Contact) {
  446. guard let extensionItem = extensionContext?.inputItems.first as? NSExtensionItem else { return }
  447. for attachment in extensionItem.attachments ?? [] {
  448. if attachment.hasItemConformingToTypeIdentifier(UTType.text.identifier) {
  449. // Handle Text
  450. attachment.loadItem(forTypeIdentifier: UTType.text.identifier, options: nil) { (textItem, error) in
  451. if let sharedText = textItem as? String {
  452. DispatchQueue.main.async { [self] in
  453. typeShareNum = TypeShare.text
  454. if let viewVc = vcHandleText.view {
  455. viewVc.backgroundColor = self.traitCollection.userInterfaceStyle == .dark ? .black : .white
  456. self.navigationItem.backButtonTitle = ""
  457. let sendButton = UIBarButtonItem(title: "Send", style: .plain, target: self, action: #selector(sendAction))
  458. sendButton.tintColor = .label
  459. vcHandleText.navigationItem.rightBarButtonItem = sendButton
  460. let containerTo = UIView()
  461. viewVc.addSubview(containerTo)
  462. containerTo.translatesAutoresizingMaskIntoConstraints = false
  463. NSLayoutConstraint.activate([
  464. containerTo.topAnchor.constraint(equalTo: viewVc.safeAreaLayoutGuide.topAnchor, constant: 8.0),
  465. containerTo.leadingAnchor.constraint(equalTo: viewVc.leadingAnchor),
  466. containerTo.trailingAnchor.constraint(equalTo: viewVc.trailingAnchor),
  467. containerTo.heightAnchor.constraint(equalToConstant: 44)
  468. ])
  469. containerTo.backgroundColor = self.traitCollection.userInterfaceStyle == .dark ? .systemBackground : .gray
  470. let textTo = UILabel()
  471. containerTo.addSubview(textTo)
  472. textTo.translatesAutoresizingMaskIntoConstraints = false
  473. NSLayoutConstraint.activate([
  474. textTo.leadingAnchor.constraint(equalTo: viewVc.leadingAnchor, constant: 10.0),
  475. textTo.centerYAnchor.constraint(equalTo: containerTo.centerYAnchor)
  476. ])
  477. textTo.text = "To: \(contact.name)"
  478. textTo.font = .systemFont(ofSize: 13)
  479. textTo.textColor = .label
  480. textView = UITextView()
  481. textView.translatesAutoresizingMaskIntoConstraints = false
  482. textView.isScrollEnabled = true
  483. textView.text = sharedText
  484. textView.textColor = .label
  485. textView.font = .systemFont(ofSize: 16)
  486. textView.backgroundColor = .clear
  487. textView.delegate = self
  488. viewVc.addSubview(textView)
  489. NSLayoutConstraint.activate([
  490. textView.leadingAnchor.constraint(equalTo: viewVc.leadingAnchor),
  491. textView.trailingAnchor.constraint(equalTo: viewVc.trailingAnchor),
  492. textView.topAnchor.constraint(equalTo: containerTo.bottomAnchor, constant: 5)
  493. ])
  494. textViewBottomConstraint = textView.bottomAnchor.constraint(equalTo: viewVc.bottomAnchor, constant: -20)
  495. textViewBottomConstraint?.isActive = true
  496. self.navigationController?.pushViewController(vcHandleText, animated: true)
  497. }
  498. }
  499. }
  500. }
  501. return
  502. } else if attachment.hasItemConformingToTypeIdentifier(UTType.image.identifier) {
  503. // Handle Image
  504. attachment.loadItem(forTypeIdentifier: UTType.image.identifier, options: nil) { (imageItem, error) in
  505. if let imageURL = imageItem as? URL {
  506. DispatchQueue.main.async { [self] in
  507. typeShareNum = TypeShare.image
  508. selectedImage = imageURL
  509. if let viewVc = vcHandleImage.view {
  510. let imageView = UIImageView()
  511. imageView.image = UIImage(contentsOfFile: imageURL.path)
  512. imageView.contentMode = .scaleAspectFit
  513. imageView.clipsToBounds = true
  514. viewVc.addSubview(imageView)
  515. imageView.frame = CGRect(x: 0, y: 70, width: viewVc.bounds.size.width, height: self.view.bounds.height - 150)
  516. buildAppearance(contact, viewVc)
  517. vcHandleImage.modalPresentationStyle = .fullScreen
  518. self.navigationController?.present(vcHandleImage, animated: true)
  519. }
  520. }
  521. }
  522. }
  523. return
  524. } else if attachment.hasItemConformingToTypeIdentifier(UTType.movie.identifier) {
  525. // Handle Video
  526. attachment.loadItem(forTypeIdentifier: UTType.movie.identifier, options: nil) { (videoItem, error) in
  527. if let videoURL = videoItem as? URL {
  528. DispatchQueue.main.async { [self] in
  529. typeShareNum = TypeShare.video
  530. selectedVideo = videoURL
  531. if let viewVc = vcHandleVideo.view {
  532. previewView = VideoPreviewView(frame: CGRect(x: 0, y: 70, width: viewVc.bounds.size.width, height: self.view.bounds.height - 190))
  533. viewVc.addSubview(previewView!)
  534. previewView!.configure(with: videoURL)
  535. buildAppearance(contact, viewVc)
  536. vcHandleVideo.modalPresentationStyle = .fullScreen
  537. self.navigationController?.present(vcHandleVideo, animated: true)
  538. }
  539. }
  540. }
  541. }
  542. return
  543. } else if attachment.hasItemConformingToTypeIdentifier(UTType.data.identifier) {
  544. // Handle Other Files
  545. attachment.loadItem(forTypeIdentifier: UTType.data.identifier, options: nil) { (fileItem, error) in
  546. if let fileURL = fileItem as? URL {
  547. DispatchQueue.main.async { [self] in
  548. typeShareNum = TypeShare.file
  549. selectedFile = fileURL
  550. if let viewVc = vcHandleFile.view {
  551. vcHandleFile.addChild(previewController)
  552. previewController.dataSource = self
  553. previewController.view.frame = CGRect(x: 0, y: 70, width: viewVc.bounds.size.width, height: viewVc.bounds.size.height - 190)
  554. previewController.view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
  555. viewVc.addSubview(previewController.view)
  556. previewController.didMove(toParent: vcHandleFile)
  557. buildAppearance(contact, viewVc)
  558. vcHandleFile.modalPresentationStyle = .fullScreen
  559. self.navigationController?.present(vcHandleFile, animated: true)
  560. }
  561. }
  562. } else {
  563. attachment.loadItem(forTypeIdentifier: "public.file-url", options: nil) { (urlData, error) in
  564. if let url = urlData as? URL {
  565. DispatchQueue.main.async { [self] in
  566. typeShareNum = TypeShare.file
  567. selectedFile = url
  568. if let viewVc = vcHandleFile.view {
  569. vcHandleFile.addChild(previewController)
  570. previewController.dataSource = self
  571. previewController.view.frame = CGRect(x: 0, y: 70, width: viewVc.bounds.size.width, height: viewVc.bounds.size.height - 190)
  572. previewController.view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
  573. viewVc.addSubview(previewController.view)
  574. previewController.didMove(toParent: vcHandleFile)
  575. buildAppearance(contact, viewVc)
  576. vcHandleFile.modalPresentationStyle = .fullScreen
  577. self.navigationController?.present(vcHandleFile, animated: true)
  578. }
  579. }
  580. }
  581. }
  582. }
  583. }
  584. return
  585. }
  586. }
  587. }
  588. }
  589. struct Contact {
  590. let id: String
  591. let name: String
  592. let profileImage: UIImage?
  593. let imageId: String
  594. let typeContact: String
  595. }
  596. class TypeShare {
  597. static let text = 1
  598. static let image = 2
  599. static let video = 3
  600. static let file = 4
  601. }
  602. class VideoPreviewView: UIView {
  603. private var player: AVPlayer?
  604. private var playerLayer: AVPlayerLayer?
  605. private var isPlaying = false
  606. private let playPauseButton: UIButton = {
  607. let button = UIButton(type: .system)
  608. button.setImage(UIImage(systemName: "play.fill"), for: .normal)
  609. button.tintColor = .white
  610. button.backgroundColor = UIColor.black.withAlphaComponent(0.5)
  611. button.layer.cornerRadius = 25
  612. button.clipsToBounds = true
  613. return button
  614. }()
  615. override init(frame: CGRect) {
  616. super.init(frame: frame)
  617. setupUI()
  618. }
  619. required init?(coder: NSCoder) {
  620. super.init(coder: coder)
  621. setupUI()
  622. }
  623. private func setupUI() {
  624. playPauseButton.frame = CGRect(x: (bounds.width - 50) / 2, y: (bounds.height - 50) / 2, width: 50, height: 50)
  625. playPauseButton.addTarget(self, action: #selector(playPauseTapped), for: .touchUpInside)
  626. addSubview(playPauseButton)
  627. }
  628. func configure(with url: URL) {
  629. // Setup AVPlayer
  630. player = AVPlayer(url: url)
  631. playerLayer = AVPlayerLayer(player: player)
  632. playerLayer?.frame = bounds
  633. playerLayer?.videoGravity = .resizeAspect
  634. if let playerLayer = playerLayer {
  635. layer.insertSublayer(playerLayer, below: playPauseButton.layer)
  636. }
  637. // Observe when video ends
  638. NotificationCenter.default.addObserver(self, selector: #selector(videoDidEnd), name: .AVPlayerItemDidPlayToEndTime, object: player?.currentItem)
  639. }
  640. @objc private func playPauseTapped() {
  641. guard let player = player else { return }
  642. if isPlaying {
  643. player.pause()
  644. playPauseButton.setImage(UIImage(systemName: "play.fill"), for: .normal)
  645. } else {
  646. player.play()
  647. playPauseButton.setImage(UIImage(systemName: "pause.fill"), for: .normal)
  648. }
  649. isPlaying.toggle()
  650. }
  651. @objc private func videoDidEnd() {
  652. guard let player = player else { return }
  653. // Replay video from start
  654. player.seek(to: .zero)
  655. player.play()
  656. playPauseButton.setImage(UIImage(systemName: "pause.fill"), for: .normal)
  657. isPlaying = true
  658. }
  659. func stopVideo() {
  660. player?.pause()
  661. player?.seek(to: .zero)
  662. playPauseButton.setImage(UIImage(systemName: "play.fill"), for: .normal)
  663. isPlaying = false
  664. }
  665. deinit {
  666. NotificationCenter.default.removeObserver(self)
  667. }
  668. }
  669. class ContactCell: UITableViewCell {
  670. let profileImageView = UIImageView()
  671. let nameLabel = UILabel()
  672. override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
  673. super.init(style: style, reuseIdentifier: reuseIdentifier)
  674. setupUI()
  675. }
  676. required init?(coder: NSCoder) {
  677. fatalError("init(coder:) has not been implemented")
  678. }
  679. func setupUI() {
  680. profileImageView.translatesAutoresizingMaskIntoConstraints = false
  681. profileImageView.layer.cornerRadius = 25
  682. profileImageView.clipsToBounds = true
  683. profileImageView.contentMode = .center
  684. nameLabel.translatesAutoresizingMaskIntoConstraints = false
  685. nameLabel.font = UIFont.systemFont(ofSize: 16, weight: .medium)
  686. contentView.addSubview(profileImageView)
  687. contentView.addSubview(nameLabel)
  688. NSLayoutConstraint.activate([
  689. profileImageView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 15),
  690. profileImageView.centerYAnchor.constraint(equalTo: contentView.centerYAnchor),
  691. profileImageView.widthAnchor.constraint(equalToConstant: 50),
  692. profileImageView.heightAnchor.constraint(equalToConstant: 50),
  693. nameLabel.leadingAnchor.constraint(equalTo: profileImageView.trailingAnchor, constant: 15),
  694. nameLabel.centerYAnchor.constraint(equalTo: contentView.centerYAnchor)
  695. ])
  696. }
  697. func configure(with contact: Contact) {
  698. nameLabel.text = contact.name
  699. profileImageView.image = contact.profileImage ?? UIImage(systemName: "person.circle")
  700. if !contact.imageId.isEmpty {
  701. profileImageView.contentMode = .scaleAspectFill
  702. }
  703. }
  704. }