Advertisement
Guest User

Untitled

a guest
Aug 19th, 2019
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 6.37 KB | None | 0 0
  1. //
  2. // ImagesViewController.swift
  3. // CreativeKitSample
  4. //
  5. // Created by Samuel Chow on 3/27/19.
  6. // Copyright © 2019 Snap Inc. All rights reserved.
  7. //
  8.  
  9. import Foundation
  10. import UIKit
  11.  
  12. import SCSDKCreativeKit
  13.  
  14. class ImagesViewController: UIViewController {
  15. fileprivate enum Constants {
  16. static let gridCount = 32
  17. static let reuseIdentifier = "ImageGridCellIdentifer"
  18. }
  19.  
  20. // MARK: - Properties
  21.  
  22. @IBOutlet fileprivate weak var collectionView: UICollectionView?
  23. @IBOutlet fileprivate weak var shareButton: UIBarButtonItem?
  24.  
  25. internal var caption: String?
  26. fileprivate var isSharing = false
  27. fileprivate var indices: [Int]?
  28. fileprivate var selectedIndex: IndexPath?
  29. fileprivate lazy var snapAPI = {
  30. return SCSDKSnapAPI()
  31. }()
  32. }
  33.  
  34. // MARK: - Private helpers
  35.  
  36. extension ImagesViewController {
  37. // We are using https://picsum.photos, a free online photo gallery API to pull
  38. // a list of images for us to send the image URL to Snapchat as an attachment URL.
  39. // A picsum image is represented by an URL bearing its ID as well as the width and
  40. // height, to which you wish to scale.
  41.  
  42. fileprivate func fetchImageMetaData() {
  43. let session = URLSession.shared
  44. let url = URL(string: "https://picsum.photos/list")!
  45. let task = session.dataTask(with: url) { [weak self] (data: Data?, response: URLResponse?, error: Error?) in
  46. guard error == nil,
  47. let data = data,
  48. let jsonArray = try? JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [[String: Any]] else {
  49. print("No or bad data received from picsum.photos.")
  50. return
  51. }
  52.  
  53. #if swift(>=4.1)
  54. self?.indices = jsonArray?.compactMap({ (element: [String: Any]) -> Int? in
  55. return element["id"] as? Int
  56. })
  57. #else
  58. self?.indices = jsonArray?.flatMap({ (element: [String: Any]) -> Int? in
  59. return element["id"] as? Int
  60. })
  61. #endif
  62.  
  63. DispatchQueue.main.async {
  64. self?.collectionView?.reloadData()
  65. }
  66. }
  67. task.resume()
  68. }
  69.  
  70. fileprivate func getURL(width: Int, height: Int, id: Int?) -> URL? {
  71. guard let id = id else {
  72. return nil
  73. }
  74.  
  75. let urlString = String(format: "https://picsum.photos/%d/%d?image=%d", width, height, id)
  76.  
  77. return URL(string: urlString)
  78. }
  79. }
  80.  
  81. // MARK: - Action handlers
  82.  
  83. extension ImagesViewController {
  84. @IBAction func shareDidTap(_ sender: UINavigationItem) {
  85. guard !isSharing,
  86. let url = getURL(width: Int(view.bounds.size.width),
  87. height: Int(view.bounds.size.height),
  88. id: selectedIndex?.row) else {
  89. return
  90. }
  91.  
  92. isSharing = true
  93. let snapPhoto = SCSDKSnapPhoto(imageUrl: url)
  94. let snapContent = SCSDKPhotoSnapContent(snapPhoto: snapPhoto)
  95. snapContent.caption = caption
  96.  
  97. // Send it over to Snapchat
  98.  
  99. // NOTE: startSending() makes use of the global UIPasteboard. Calling the method without synchronization
  100. // might cause the UIPasteboard data to be overwritten, while the pasteboard is being read from Snapchat.
  101. // Either synchronize the method call yourself or disable user interaction until the share is over.
  102. view.isUserInteractionEnabled = false
  103. snapAPI.startSending(snapContent) { [weak self] (error: Error?) in
  104. self?.view.isUserInteractionEnabled = true
  105. self?.isSharing = false
  106. print("Shared \(String(describing: url.absoluteString)) on SnapChat.")
  107. }
  108. }
  109.  
  110. @IBAction func cancelDidTap(_ sender: UINavigationItem) {
  111. dismiss(animated: true)
  112. }
  113. }
  114.  
  115. // MARK: - UIViewController
  116.  
  117. extension ImagesViewController {
  118. override func viewDidLoad() {
  119. super.viewDidLoad()
  120.  
  121. fetchImageMetaData()
  122. }
  123. }
  124.  
  125. // MARK: - UICollectionViewDataSource
  126.  
  127. extension ImagesViewController: UICollectionViewDataSource {
  128. func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
  129. return 1
  130. }
  131.  
  132. func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
  133. // We cap the number of images to the gridCount.
  134. return indices == nil ? 0 : min(indices!.count, Constants.gridCount)
  135. }
  136.  
  137. func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
  138. let cell = collectionView.dequeueReusableCell(withReuseIdentifier: Constants.reuseIdentifier,
  139. for: indexPath)
  140. guard indices != nil,
  141. indices!.count > 0,
  142. let imageCell = cell as? ImageCollectionViewCell else {
  143. return cell
  144. }
  145.  
  146. let index = indices![indexPath.row]
  147. let url = getURL(width: Int(imageCell.bounds.size.width),
  148. height: Int(imageCell.bounds.size.height),
  149. id: index)
  150. imageCell.animView?.setImage(withURL: url)
  151.  
  152. return imageCell
  153. }
  154. }
  155.  
  156. // MARK: - UICollectionViewDelegate
  157.  
  158. extension ImagesViewController: UICollectionViewDelegate {
  159. func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
  160. if let selectedIndex = selectedIndex {
  161. guard let prevSelectedCell = collectionView.cellForItem(at: selectedIndex)
  162. as? ImageCollectionViewCell else {
  163. return
  164. }
  165. prevSelectedCell.animView?.layer.borderColor = UIColor.clear.cgColor
  166. prevSelectedCell.animView?.layer.borderWidth = 0.0
  167. }
  168.  
  169. guard let selectedCell = collectionView.cellForItem(at: indexPath) as?
  170. ImageCollectionViewCell else {
  171. return
  172. }
  173.  
  174. selectedCell.animView?.layer.borderColor = UIColor.orange.cgColor
  175. selectedCell.animView?.layer.borderWidth = 2.0
  176. selectedIndex = indexPath
  177. shareButton?.isEnabled = true
  178. }
  179. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement