Created
February 29, 2016 21:08
-
-
Save MarcusSmith/7ec6426a42ce78b5aea3 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// 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 | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
hello, great code! But I want ask u a thing... with this code can I use UIImage or UIImageView like CKAsset?