Skip to content

Instantly share code, notes, and snippets.

@camdeardorff
Created February 13, 2020 01:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save camdeardorff/615a04b96b1c22e95394f84be3eebc9d to your computer and use it in GitHub Desktop.
Save camdeardorff/615a04b96b1c22e95394f84be3eebc9d to your computer and use it in GitHub Desktop.
//
// UIImagable.swift
// Landscape
//
// Created by Cameron Deardorff on 1/31/20.
// Copyright © 2020 Cameron Deardorff. All rights reserved.
//
import UIKit
import Photos
fileprivate enum UIImagableSource {
// image in a user's photo collection
case photos(asset: PHAsset)
// url of image on disk or internet
case path(url: URL)
var identifier: String {
switch self {
case .photos(let asset):
return asset.localIdentifier
case .path(let url):
return url.absoluteString
}
}
}
struct UIImagable {
private var source: UIImagableSource
var id: String {
return source.identifier
}
init(asset: PHAsset) {
source = .photos(asset: asset)
}
init(url: URL) {
source = .path(url: url)
}
func getImage(with size: CGSize, completion: @escaping (UIImage?) -> ()) {
DispatchQueue.global(qos: .userInteractive).async {
switch self.source {
case .photos(let asset):
let imageRequestOptions = PHImageRequestOptions()
imageRequestOptions.isSynchronous = false
imageRequestOptions.isNetworkAccessAllowed = true
let greaterDetailSize = size.applying(.init(scaleX: 3, y: 3))
PHImageManager.default().requestImage(for: asset, targetSize: greaterDetailSize, contentMode: .aspectFit, options: imageRequestOptions, resultHandler: { image, metadata in
guard let image = image else { return }
completion(image)
})
case .path(let url):
guard let data = try? Data(contentsOf: url) else {
completion(nil)
return
}
completion(UIImage(data: data))
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment