Guest User

Untitled

a guest
Aug 21st, 2019
66
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import UIKit
  2. import CloudKit
  3.  
  4. class CloudManager {
  5.  
  6. private static let privateCloudDatabase = CKContainer.default().publicCloudDatabase
  7.  
  8. static func saveDataToCloud(place: Place, with image: UIImage) {
  9.  
  10. let (image, url) = prepareImageToSaveToCloud(place: place, image: image)
  11.  
  12. guard let imageAsset = image, let imageURL = url else { return }
  13.  
  14. let record = CKRecord(recordType: "Place")
  15. record.setValue(place.name, forKey: "name")
  16. record.setValue(place.location, forKey: "location")
  17. record.setValue(place.type, forKey: "type")
  18. record.setValue(place.rating, forKey: "rating")
  19. record.setValue(imageAsset, forKey: "imageData")
  20.  
  21. privateCloudDatabase.save(record) { (_, error) in
  22. if let error = error { print(error); return }
  23. deleteTempImage(imageURL: imageURL)
  24. }
  25. }
  26.  
  27. // MARK: Private Methods
  28. private static func prepareImageToSaveToCloud(place: Place, image: UIImage) -> (CKAsset?, URL?) {
  29.  
  30. let scale = image.size.width > 1080 ? 1080 / image.size.width : 1
  31. let scaleImage = UIImage(data: image.pngData()!, scale: scale)
  32. let imageFilePath = NSTemporaryDirectory() + place.name
  33. let imageURL = URL(fileURLWithPath: imageFilePath)
  34.  
  35. guard let dataToPath = scaleImage?.jpegData(compressionQuality: 1) else { return (nil, nil)}
  36.  
  37. do {
  38. try dataToPath.write(to: imageURL, options: .atomic)
  39. } catch {
  40. print(error.localizedDescription)
  41. }
  42.  
  43. let imageAsset = CKAsset(fileURL: imageURL)
  44.  
  45. return (imageAsset, imageURL)
  46. }
  47.  
  48. static private func deleteTempImage(imageURL: URL) {
  49. do {
  50. try FileManager.default.removeItem(at: imageURL)
  51. } catch {
  52. print(error.localizedDescription)
  53. }
  54. }
RAW Paste Data