Skip to content

Instantly share code, notes, and snippets.

@MarcusSmith
Created February 29, 2016 21:08
Show Gist options
  • Save MarcusSmith/7ec6426a42ce78b5aea3 to your computer and use it in GitHub Desktop.
Save MarcusSmith/7ec6426a42ce78b5aea3 to your computer and use it in GitHub Desktop.
//
// UIImage+CKAsset.swift
// CloudKitDemo
//
// Created by Marcus Smith on 2/29/16.
// Copyright © 2016 FrozenFireStudios. All rights reserved.
//
import UIKit
import CloudKit
enum ImageFileType {
case JPG(compressionQuality: CGFloat)
case PNG
var fileExtension: String {
switch self {
case .JPG(_):
return ".jpg"
case .PNG:
return ".png"
}
}
}
enum ImageError: ErrorType {
case UnableToConvertImageToData
}
extension CKAsset {
convenience init(image: UIImage, fileType: ImageFileType = .JPG(compressionQuality: 70)) throws {
let url = try image.saveToTempLocationWithFileType(fileType)
self.init(fileURL: url)
}
var image: UIImage? {
guard let data = NSData(contentsOfURL: fileURL), image = UIImage(data: data) else { return nil }
return image
}
}
extension UIImage {
func saveToTempLocationWithFileType(fileType: ImageFileType) throws -> NSURL {
let imageData: NSData?
switch fileType {
case .JPG(let quality):
imageData = UIImageJPEGRepresentation(self, quality)
case .PNG:
imageData = UIImagePNGRepresentation(self)
}
guard let data = imageData else {
throw ImageError.UnableToConvertImageToData
}
let filename = NSProcessInfo.processInfo().globallyUniqueString + fileType.fileExtension
let url = NSURL.fileURLWithPath(NSTemporaryDirectory()).URLByAppendingPathComponent(filename)
try data.writeToURL(url, options: .AtomicWrite)
return url
}
}
@mattia-ui
Copy link

hello, great code! But I want ask u a thing... with this code can I use UIImage or UIImageView like CKAsset?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment