From 519629cd560ddd039f53fb751fae8cefa821de7a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Elvis=20Nu=C3=B1ez?= Date: Mon, 23 Oct 2017 22:39:39 +0200 Subject: [PATCH] Run SwiftFormat --- Example/AppDelegate.swift | 3 +- Example/ViewController.swift | 30 +++-- Finjinon/AssetResolver.swift | 2 +- Finjinon/Buttons.swift | 12 +- Finjinon/CaptureManager.swift | 30 ++--- Finjinon/ImagePickerAdapter.swift | 9 +- Finjinon/PhotoCaptureViewController.swift | 139 +++++++++++----------- Finjinon/PhotoCollectionViewCell.swift | 19 ++- Finjinon/PhotoCollectionViewLayout.swift | 62 +++++----- Finjinon/PhotoStorage.swift | 52 ++++---- FinjinonTests/FinjinonTests.swift | 3 - 11 files changed, 175 insertions(+), 186 deletions(-) diff --git a/Example/AppDelegate.swift b/Example/AppDelegate.swift index 01f2a6a..034cff7 100644 --- a/Example/AppDelegate.swift +++ b/Example/AppDelegate.swift @@ -9,8 +9,7 @@ class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? - func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { + func application(_: UIApplication, didFinishLaunchingWithOptions _: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { return true } } - diff --git a/Example/ViewController.swift b/Example/ViewController.swift index 3aed87a..427cc1d 100644 --- a/Example/ViewController.swift +++ b/Example/ViewController.swift @@ -13,8 +13,8 @@ class ViewController: UITableViewController { captureController.delegate = self - for i in 0..<6 { - self.captureController.createAssetFromImage(UIImage(named: "hoff.jpeg")!) { asset in + for i in 0 ..< 6 { + captureController.createAssetFromImage(UIImage(named: "hoff.jpeg")!) { asset in self.assets.append(asset) self.tableView.insertRows(at: [IndexPath(row: i, section: 0)], with: .automatic) } @@ -26,16 +26,16 @@ class ViewController: UITableViewController { tableView.reloadData() } - @IBAction func addPhotosTapped(_ sender: AnyObject) { + @IBAction func addPhotosTapped(_: AnyObject) { present(captureController, animated: true, completion: nil) } - override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { + override func tableView(_: UITableView, numberOfRowsInSection _: Int) -> Int { return assets.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { - let cell = tableView.dequeueReusableCell(withIdentifier: "ItemCell", for: indexPath) + let cell = tableView.dequeueReusableCell(withIdentifier: "ItemCell", for: indexPath) let asset = assets[indexPath.row] cell.textLabel?.text = asset.UUID cell.imageView?.image = nil @@ -48,7 +48,6 @@ class ViewController: UITableViewController { } } - extension ViewController: PhotoCaptureViewControllerDelegate { func photoCaptureViewController(_ controller: PhotoCaptureViewController, cellForItemAtIndexPath indexPath: IndexPath) -> PhotoCollectionViewCell? { return controller.dequeuedReusableCellForClass(PhotoCollectionViewCell.self, indexPath: indexPath) { cell in @@ -64,42 +63,41 @@ extension ViewController: PhotoCaptureViewControllerDelegate { } } - func photoCaptureViewControllerDidFinish(_ controller: PhotoCaptureViewController) { - + func photoCaptureViewControllerDidFinish(_: PhotoCaptureViewController) { } - func photoCaptureViewController(_ controller: PhotoCaptureViewController, didSelectAssetAtIndexPath indexPath: IndexPath) { + func photoCaptureViewController(_: PhotoCaptureViewController, didSelectAssetAtIndexPath indexPath: IndexPath) { NSLog("tapped in \(indexPath.row)") } - func photoCaptureViewController(_ controller: PhotoCaptureViewController, didFailWithError error: NSError) { + func photoCaptureViewController(_: PhotoCaptureViewController, didFailWithError error: NSError) { NSLog("failure: \(error)") } - func photoCaptureViewController(_ controller: PhotoCaptureViewController, didMoveItemFromIndexPath fromIndexPath: IndexPath, toIndexPath: IndexPath) { + func photoCaptureViewController(_: PhotoCaptureViewController, didMoveItemFromIndexPath fromIndexPath: IndexPath, toIndexPath: IndexPath) { NSLog("moved from #\(fromIndexPath.item) to #\(toIndexPath.item)") tableView.moveRow(at: fromIndexPath, to: toIndexPath) } - func photoCaptureViewControllerNumberOfAssets(_ controller: PhotoCaptureViewController) -> Int { + func photoCaptureViewControllerNumberOfAssets(_: PhotoCaptureViewController) -> Int { return assets.count } - func photoCaptureViewController(_ controller: PhotoCaptureViewController, assetForIndexPath indexPath: IndexPath) -> Asset { + func photoCaptureViewController(_: PhotoCaptureViewController, assetForIndexPath indexPath: IndexPath) -> Asset { return assets[indexPath.item] } - func photoCaptureViewController(_ controller: PhotoCaptureViewController, didAddAsset asset: Asset) { + func photoCaptureViewController(_: PhotoCaptureViewController, didAddAsset asset: Asset) { assets.append(asset) tableView.insertRows(at: [IndexPath(row: 0, section: 0)], with: .automatic) } - func photoCaptureViewController(_ controller: PhotoCaptureViewController, deleteAssetAtIndexPath indexPath: IndexPath) { + func photoCaptureViewController(_: PhotoCaptureViewController, deleteAssetAtIndexPath indexPath: IndexPath) { assets.remove(at: indexPath.item) tableView.deleteRows(at: [IndexPath(row: 0, section: 0)], with: .automatic) } - func photoCaptureViewController(_ controller: PhotoCaptureViewController, canMoveItemAtIndexPath indexPath: IndexPath) -> Bool { + func photoCaptureViewController(_: PhotoCaptureViewController, canMoveItemAtIndexPath _: IndexPath) -> Bool { return true } } diff --git a/Finjinon/AssetResolver.swift b/Finjinon/AssetResolver.swift index e3e7971..5cd0981 100644 --- a/Finjinon/AssetResolver.swift +++ b/Finjinon/AssetResolver.swift @@ -9,7 +9,7 @@ internal struct AssetResolver { let queue = DispatchQueue(label: "com.finjinon.asset-resolvement", attributes: []) var defaultTargetSize = CGSize(width: 720, height: 1280) - func enqueueResolve(_ asset: PHAsset, targetSize: CGSize? = nil, completion: @escaping (UIImage) -> Void) { + func enqueueResolve(_ asset: PHAsset, targetSize _: CGSize? = nil, completion: @escaping (UIImage) -> Void) { queue.async { self.resolve(asset, completion: completion) } diff --git a/Finjinon/Buttons.swift b/Finjinon/Buttons.swift index ec94fa5..59f7903 100644 --- a/Finjinon/Buttons.swift +++ b/Finjinon/Buttons.swift @@ -10,6 +10,7 @@ class TriggerButton: UIButton { setNeedsDisplay() } } + override var isEnabled: Bool { didSet { setNeedsDisplay() @@ -22,7 +23,7 @@ class TriggerButton: UIButton { backgroundColor = UIColor.clear } - required init?(coder aDecoder: NSCoder) { + required init?(coder _: NSCoder) { fatalError("init(coder:) has not been implemented") } @@ -30,7 +31,7 @@ class TriggerButton: UIButton { super.draw(dirtyRect) let length = min(bounds.width, bounds.height) - let outerRect = CGRect(x: (bounds.width/2)-(length/2), y: (bounds.height/2)-(length/2), width: length, height: length) + let outerRect = CGRect(x: (bounds.width / 2) - (length / 2), y: (bounds.height / 2) - (length / 2), width: length, height: length) let borderWidth: CGFloat = 6.0 let outerPath = UIBezierPath(ovalIn: outerRect.insetBy(dx: borderWidth, dy: borderWidth)) outerPath.lineWidth = borderWidth @@ -48,7 +49,6 @@ class TriggerButton: UIButton { } } - class CloseButton: UIButton { var strokeColor = UIColor.black { didSet { setNeedsDisplay() } @@ -60,14 +60,14 @@ class CloseButton: UIButton { backgroundColor = UIColor.lightGray.withAlphaComponent(0.9) } - required init?(coder aDecoder: NSCoder) { + required init?(coder _: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { super.layoutSubviews() - layer.cornerRadius = bounds.height/2 + layer.cornerRadius = bounds.height / 2 layer.masksToBounds = true } @@ -76,7 +76,7 @@ class CloseButton: UIButton { // Draw a + let centerPoint = CGPoint(x: bounds.midX, y: bounds.midY) - let radius: CGFloat = bounds.insetBy(dx: floor(bounds.width/8), dy: floor(bounds.width/8)).width / 2 + let radius: CGFloat = bounds.insetBy(dx: floor(bounds.width / 8), dy: floor(bounds.width / 8)).width / 2 let ratio: CGFloat = 0.5 let xPath = UIBezierPath() xPath.move(to: centerPoint) diff --git a/Finjinon/CaptureManager.swift b/Finjinon/CaptureManager.swift index 1f5b7ab..579bbdd 100644 --- a/Finjinon/CaptureManager.swift +++ b/Finjinon/CaptureManager.swift @@ -13,13 +13,13 @@ enum CaptureManagerViewfinderMode { class CaptureManager: NSObject { let previewLayer: AVCaptureVideoPreviewLayer var flashMode: AVCaptureFlashMode { - get { - return cameraDevice?.flashMode ?? .off - } + return cameraDevice?.flashMode ?? .off } + var hasFlash: Bool { return cameraDevice?.hasFlash ?? false && cameraDevice?.isFlashAvailable ?? false } + var supportedFlashModes: [AVCaptureFlashMode] { var modes: [AVCaptureFlashMode] = [] for mode in [AVCaptureFlashMode.off, AVCaptureFlashMode.auto, AVCaptureFlashMode.on] { @@ -29,7 +29,8 @@ class CaptureManager: NSObject { } return modes } - let viewfinderMode : CaptureManagerViewfinderMode + + let viewfinderMode: CaptureManagerViewfinderMode fileprivate let session = AVCaptureSession() fileprivate let captureQueue = DispatchQueue(label: "no.finn.finjinon-captures", attributes: []) @@ -39,7 +40,7 @@ class CaptureManager: NSObject { override init() { session.sessionPreset = AVCaptureSessionPresetPhoto - var viewfinderMode : CaptureManagerViewfinderMode { + var viewfinderMode: CaptureManagerViewfinderMode { let screenBounds = UIScreen.main.nativeBounds let ratio = screenBounds.height / screenBounds.width return ratio <= 1.5 ? .fullScreen : .window @@ -79,7 +80,7 @@ class CaptureManager: NSObject { } }) case .denied, .restricted: - completion(self.accessDeniedError()) + completion(accessDeniedError()) } } @@ -99,7 +100,7 @@ class CaptureManager: NSObject { } connection.videoOrientation = self.orientation - self.stillImageOutput?.captureStillImageAsynchronously(from: connection, completionHandler: { (sampleBuffer, error) in + self.stillImageOutput?.captureStillImageAsynchronously(from: connection, completionHandler: { sampleBuffer, error in if error == nil { if let sampleBuffer = sampleBuffer, let data = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(sampleBuffer) { if let metadata = CMCopyDictionaryOfAttachments(nil, sampleBuffer, CMAttachmentMode(kCMAttachmentMode_ShouldPropagate)) as NSDictionary? { @@ -112,7 +113,7 @@ class CaptureManager: NSObject { } } else { NSLog("Failed capturing still imagE: \(String(describing: error))") - // TODO + // TODO: } }) } @@ -120,7 +121,7 @@ class CaptureManager: NSObject { func lockFocusAtPointOfInterest(_ pointInLayer: CGPoint) { let pointInCamera = previewLayer.captureDevicePointOfInterest(for: pointInLayer) - self.lockCurrentCameraDeviceForConfiguration { cameraDevice in + lockCurrentCameraDeviceForConfiguration { cameraDevice in if let cameraDevice = self.cameraDevice, cameraDevice.isFocusPointOfInterestSupported { cameraDevice.focusPointOfInterest = pointInCamera cameraDevice.focusMode = .autoFocus @@ -149,14 +150,14 @@ class CaptureManager: NSObject { nextIndex = idx + 1 } let startIndex = min(nextIndex, supportedFlashModes.count) - let next = supportedFlashModes[startIndex.. Void, completion: @escaping (Bool) -> Void) -> UIViewController } - open class ImagePickerControllerAdapter: NSObject, ImagePickerAdapter, UIImagePickerControllerDelegate, UINavigationControllerDelegate { var selectionHandler: ([PHAsset]) -> Void = { _ in } var completionHandler: (_ didCancel: Bool) -> Void = { _ in } open func viewControllerForImageSelection(_ selectedAssetsHandler: @escaping ([PHAsset]) -> Void, completion: @escaping (Bool) -> Void) -> UIViewController { - self.selectionHandler = selectedAssetsHandler - self.completionHandler = completion + selectionHandler = selectedAssetsHandler + completionHandler = completion let picker = UIImagePickerController() picker.mediaTypes = [kUTTypeImage as String] @@ -32,7 +31,7 @@ open class ImagePickerControllerAdapter: NSObject, ImagePickerAdapter, UIImagePi return picker } - open func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) { + open func imagePickerController(_: UIImagePickerController, didFinishPickingMediaWithInfo info: [String: Any]) { guard let referenceURL = info[UIImagePickerControllerReferenceURL] as? URL else { completionHandler(true) return @@ -48,7 +47,7 @@ open class ImagePickerControllerAdapter: NSObject, ImagePickerAdapter, UIImagePi } } - open func imagePickerControllerDidCancel(_ picker: UIImagePickerController) { + open func imagePickerControllerDidCancel(_: UIImagePickerController) { completionHandler(true) } } diff --git a/Finjinon/PhotoCaptureViewController.swift b/Finjinon/PhotoCaptureViewController.swift index ee81113..9fff661 100644 --- a/Finjinon/PhotoCaptureViewController.swift +++ b/Finjinon/PhotoCaptureViewController.swift @@ -32,7 +32,7 @@ public protocol PhotoCaptureViewControllerDelegate: NSObjectProtocol { open class PhotoCaptureViewController: UIViewController, PhotoCollectionViewLayoutDelegate { open weak var delegate: PhotoCaptureViewControllerDelegate? open var imagePickerAdapter: ImagePickerAdapter = ImagePickerControllerAdapter() - + /// Optional view to display when returning from imagePicker not finished retrieving data. /// Use constraints to position elements dynamically, as the view will be rotated and sized with the device. open var imagePickerWaitingForImageDataView: UIView? @@ -45,16 +45,16 @@ open class PhotoCaptureViewController: UIViewController, PhotoCollectionViewLayo fileprivate var containerView: UIView! fileprivate var focusIndicatorView: UIView! fileprivate var flashButton: UIButton! - fileprivate var pickerButton : UIButton! - fileprivate var closeButton : UIButton! - fileprivate let buttonMargin : CGFloat = 12 - fileprivate var orientation : UIDeviceOrientation = .portrait + fileprivate var pickerButton: UIButton! + fileprivate var closeButton: UIButton! + fileprivate let buttonMargin: CGFloat = 12 + fileprivate var orientation: UIDeviceOrientation = .portrait deinit { captureManager.stop(nil) } - override open func viewDidLoad() { + open override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor.black @@ -67,7 +67,7 @@ open class PhotoCaptureViewController: UIViewController, PhotoCollectionViewLayo let previewLayer = captureManager.previewLayer // We are using AVCaptureSessionPresetPhoto which has a 4:3 aspect ratio let viewFinderWidth = view.bounds.size.width - var viewFinderHeight = (viewFinderWidth/3) * 4 + var viewFinderHeight = (viewFinderWidth / 3) * 4 if captureManager.viewfinderMode == .fullScreen { viewFinderHeight = view.bounds.size.height } @@ -83,7 +83,7 @@ open class PhotoCaptureViewController: UIViewController, PhotoCollectionViewLayo flashButton = UIButton(frame: CGRect(x: buttonMargin, y: buttonMargin, width: 70, height: 38)) flashButton.setImage(UIImage(named: "LightningIcon"), for: UIControlState()) - flashButton.setTitle(NSLocalizedString("Off", comment:"flash off"), for: UIControlState()) + flashButton.setTitle(NSLocalizedString("Off", comment: "flash off"), for: UIControlState()) flashButton.addTarget(self, action: #selector(flashButtonTapped(_:)), for: .touchUpInside) flashButton.titleLabel?.font = UIFont.preferredFont(forTextStyle: UIFontTextStyle.footnote) flashButton.tintColor = UIColor.white @@ -93,11 +93,11 @@ open class PhotoCaptureViewController: UIViewController, PhotoCollectionViewLayo let tapper = UITapGestureRecognizer(target: self, action: #selector(focusTapGestureRecognized(_:))) previewView.addGestureRecognizer(tapper) - var collectionViewHeight: CGFloat = min(view.frame.size.height/6, 120) - let collectionViewBottomMargin : CGFloat = 70 - let cameraButtonHeight : CGFloat = 66 + var collectionViewHeight: CGFloat = min(view.frame.size.height / 6, 120) + let collectionViewBottomMargin: CGFloat = 70 + let cameraButtonHeight: CGFloat = 66 - var containerFrame = CGRect(x: 0, y: view.frame.height-collectionViewBottomMargin-collectionViewHeight, width: view.frame.width, height: collectionViewBottomMargin+collectionViewHeight) + var containerFrame = CGRect(x: 0, y: view.frame.height - collectionViewBottomMargin - collectionViewHeight, width: view.frame.width, height: collectionViewBottomMargin + collectionViewHeight) if captureManager.viewfinderMode == .window { let containerHeight = view.frame.height - viewFinderHeight containerFrame.origin.y = view.frame.height - containerHeight @@ -114,11 +114,11 @@ open class PhotoCaptureViewController: UIViewController, PhotoCollectionViewLayo layout.scrollDirection = .horizontal let inset: CGFloat = 8 - layout.itemSize = CGSize(width: collectionView.frame.height - (inset*2), height: collectionView.frame.height - (inset*2)) + layout.itemSize = CGSize(width: collectionView.frame.height - (inset * 2), height: collectionView.frame.height - (inset * 2)) layout.sectionInset = UIEdgeInsets(top: inset, left: inset, bottom: inset, right: inset) layout.minimumInteritemSpacing = inset layout.minimumLineSpacing = inset - layout.didReorderHandler = { [weak self] (fromIndexPath, toIndexPath) in + layout.didReorderHandler = { [weak self] fromIndexPath, toIndexPath in if let welf = self { welf.delegate?.photoCaptureViewController(welf, didMoveItemFromIndexPath: fromIndexPath as IndexPath, toIndexPath: toIndexPath as IndexPath) } @@ -131,8 +131,8 @@ open class PhotoCaptureViewController: UIViewController, PhotoCollectionViewLayo collectionView.dataSource = self collectionView.delegate = self - captureButton = TriggerButton(frame: CGRect(x: (containerView.frame.width/2)-cameraButtonHeight/2, y: containerView.frame.height - cameraButtonHeight - 4, width: cameraButtonHeight, height: cameraButtonHeight)) - captureButton.layer.cornerRadius = cameraButtonHeight/2 + captureButton = TriggerButton(frame: CGRect(x: (containerView.frame.width / 2) - cameraButtonHeight / 2, y: containerView.frame.height - cameraButtonHeight - 4, width: cameraButtonHeight, height: cameraButtonHeight)) + captureButton.layer.cornerRadius = cameraButtonHeight / 2 captureButton.addTarget(self, action: #selector(capturePhotoTapped(_:)), for: .touchUpInside) containerView.addSubview(captureButton) captureButton.isEnabled = false @@ -170,10 +170,10 @@ open class PhotoCaptureViewController: UIViewController, PhotoCollectionViewLayo UIView.animate(withDuration: 0.2, animations: { self.captureButton.isEnabled = true self.previewView.alpha = 1.0 - }) + }) } - NotificationCenter.default.addObserver(forName: NSNotification.Name.UIDeviceOrientationDidChange, object: nil, queue: nil) { (NSNotification) -> Void in + NotificationCenter.default.addObserver(forName: NSNotification.Name.UIDeviceOrientationDidChange, object: nil, queue: nil) { (_) -> Void in switch UIDevice.current.orientation { case .faceDown, .faceUp, .unknown: () @@ -201,19 +201,19 @@ open class PhotoCaptureViewController: UIViewController, PhotoCollectionViewLayo UIApplication.shared.setStatusBarHidden(false, with: .slide) } - open override var preferredStatusBarUpdateAnimation : UIStatusBarAnimation { + open override var preferredStatusBarUpdateAnimation: UIStatusBarAnimation { return .slide } - open override var prefersStatusBarHidden : Bool { + open override var prefersStatusBarHidden: Bool { return true } - open override var shouldAutorotate : Bool { + open override var shouldAutorotate: Bool { return false } - open override var supportedInterfaceOrientations : UIInterfaceOrientationMask { + open override var supportedInterfaceOrientations: UIInterfaceOrientationMask { return UIInterfaceOrientationMask.portrait } @@ -223,7 +223,7 @@ open class PhotoCaptureViewController: UIViewController, PhotoCollectionViewLayo collectionView.register(cellClass, forCellWithReuseIdentifier: identifier) } - open func dequeuedReusableCellForClass(_ clazz: T.Type, indexPath: IndexPath, config: ((T) -> Void)) -> T { + open func dequeuedReusableCellForClass(_ clazz: T.Type, indexPath: IndexPath, config: ((T) -> Void)) -> T { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: clazz.cellIdentifier(), for: indexPath) as! T config(cell) return cell @@ -246,7 +246,7 @@ open class PhotoCaptureViewController: UIViewController, PhotoCollectionViewLayo return nil } - open func cellForpreviewAtIndexPath(_ indexPath: IndexPath) -> T? { + open func cellForpreviewAtIndexPath(_ indexPath: IndexPath) -> T? { return collectionView.cellForItem(at: indexPath) as? T } @@ -278,13 +278,13 @@ open class PhotoCaptureViewController: UIViewController, PhotoCollectionViewLayo open func deleteAssetAtIndex(_ idx: Int, handler: @escaping () -> Void) { let indexPath = IndexPath(item: idx, section: 0) if let asset = delegate?.photoCaptureViewController(self, assetForIndexPath: indexPath) { - self.collectionView.performBatchUpdates({ + collectionView.performBatchUpdates({ handler() self.collectionView.deleteItems(at: [indexPath]) - }, completion: { finished in - if asset.imageURL == nil { - self.storage.deleteAsset(asset, completion: {}) - } + }, completion: { _ in + if asset.imageURL == nil { + self.storage.deleteAsset(asset, completion: {}) + } }) } } @@ -299,54 +299,54 @@ open class PhotoCaptureViewController: UIViewController, PhotoCollectionViewLayo // MARK: - Actions - func flashButtonTapped(_ sender: UIButton) { + func flashButtonTapped(_: UIButton) { let mode = captureManager.nextAvailableFlashMode() ?? .off captureManager.changeFlashMode(mode) { switch mode { case .off: - self.flashButton.setTitle(NSLocalizedString("Off", comment:"flash off"), for: UIControlState()) + self.flashButton.setTitle(NSLocalizedString("Off", comment: "flash off"), for: UIControlState()) case .on: - self.flashButton.setTitle(NSLocalizedString("On", comment:"flash on"), for: UIControlState()) + self.flashButton.setTitle(NSLocalizedString("On", comment: "flash on"), for: UIControlState()) case .auto: - self.flashButton.setTitle(NSLocalizedString("Auto", comment:"flash Auto"), for: UIControlState()) + self.flashButton.setTitle(NSLocalizedString("Auto", comment: "flash Auto"), for: UIControlState()) } } } - func presentImagePickerTapped(_ sender: AnyObject) { + func presentImagePickerTapped(_: AnyObject) { if libraryAuthorizationStatus() == .denied || libraryAuthorizationStatus() == .restricted { let error = NSError(domain: FinjinonLibraryAccessErrorDomain, code: 0, userInfo: nil) delegate?.photoCaptureViewController(self, didFailWithError: error) return } - + let controller = imagePickerAdapter.viewControllerForImageSelection({ assets in if let waitView = self.imagePickerWaitingForImageDataView, assets.count > 0 { waitView.translatesAutoresizingMaskIntoConstraints = false self.view.addSubview(waitView) - + waitView.removeConstraints(waitView.constraints.filter({ (constraint: NSLayoutConstraint) -> Bool in - return constraint.secondItem as! UIView == self.view + constraint.secondItem as! UIView == self.view })) self.view.addConstraint(NSLayoutConstraint(item: waitView, attribute: .centerX, relatedBy: .equal, toItem: self.view, attribute: .centerX, multiplier: 1, constant: 0)) self.view.addConstraint(NSLayoutConstraint(item: waitView, attribute: .centerY, relatedBy: .equal, toItem: self.view, attribute: .centerY, multiplier: 1, constant: 0)) - + switch UIDevice.current.orientation { case .landscapeRight: self.view.addConstraint(NSLayoutConstraint(item: waitView, attribute: .height, relatedBy: .equal, toItem: self.view, attribute: .width, multiplier: 1, constant: 0)) self.view.addConstraint(NSLayoutConstraint(item: waitView, attribute: .width, relatedBy: .equal, toItem: self.view, attribute: .height, multiplier: 1, constant: 0)) - + case .landscapeLeft: self.view.addConstraint(NSLayoutConstraint(item: waitView, attribute: .height, relatedBy: .equal, toItem: self.view, attribute: .width, multiplier: 1, constant: 0)) self.view.addConstraint(NSLayoutConstraint(item: waitView, attribute: .width, relatedBy: .equal, toItem: self.view, attribute: .height, multiplier: 1, constant: 0)) - + default: self.view.addConstraint(NSLayoutConstraint(item: waitView, attribute: .height, relatedBy: .equal, toItem: self.view, attribute: .height, multiplier: 1, constant: 0)) self.view.addConstraint(NSLayoutConstraint(item: waitView, attribute: .width, relatedBy: .equal, toItem: self.view, attribute: .width, multiplier: 1, constant: 0)) } waitView.rotateToCurrentDeviceOrientation() } - + let resolver = AssetResolver() var count = assets.count assets.forEach { asset in @@ -355,7 +355,7 @@ open class PhotoCaptureViewController: UIViewController, PhotoCollectionViewLayo var mutableAsset = asset mutableAsset.imageDataSourceType = .library self.didAddAsset(mutableAsset) - + count -= 1 if count == 0 { self.imagePickerWaitingForImageDataView?.removeFromSuperview() @@ -363,25 +363,25 @@ open class PhotoCaptureViewController: UIViewController, PhotoCollectionViewLayo }) }) } - }, completion: { cancelled in + }, completion: { _ in DispatchQueue.main.async { self.dismiss(animated: true, completion: nil) } }) - + present(controller, animated: true, completion: nil) } func capturePhotoTapped(_ sender: UIButton) { sender.isEnabled = false - UIView.animate(withDuration: 0.1, animations: { self.previewView.alpha = 0.0 }, completion: { finished in - UIView.animate(withDuration: 0.1, animations: {self.previewView.alpha = 1.0}) + UIView.animate(withDuration: 0.1, animations: { self.previewView.alpha = 0.0 }, completion: { _ in + UIView.animate(withDuration: 0.1, animations: { self.previewView.alpha = 1.0 }) }) - captureManager.captureImage { (data, metadata) in + captureManager.captureImage { data, _ in sender.isEnabled = true - self.createAssetFromImageData(data as Data, completion: { ( asset: Asset) in + self.createAssetFromImageData(data as Data, completion: { (asset: Asset) in var mutableAsset = asset mutableAsset.imageDataSourceType = .camera self.didAddAsset(mutableAsset) @@ -395,12 +395,12 @@ open class PhotoCaptureViewController: UIViewController, PhotoCollectionViewLayo self.delegate?.photoCaptureViewController(self, didAddAsset: asset) let insertedIndexPath: IndexPath if let count = self.delegate?.photoCaptureViewControllerNumberOfAssets(self) { - insertedIndexPath = IndexPath(item: count-1, section: 0) + insertedIndexPath = IndexPath(item: count - 1, section: 0) } else { insertedIndexPath = IndexPath(item: 0, section: 0) } self.collectionView.insertItems(at: [insertedIndexPath]) - }, completion: { finished in + }, completion: { _ in self.scrollToLastAddedAssetAnimated(true) }) } @@ -408,12 +408,12 @@ open class PhotoCaptureViewController: UIViewController, PhotoCollectionViewLayo fileprivate func scrollToLastAddedAssetAnimated(_ animated: Bool) { if let count = self.delegate?.photoCaptureViewControllerNumberOfAssets(self), count > 0 { - self.collectionView.scrollToItem(at: IndexPath(item: count-1, section: 0), at: .left, animated: animated) + collectionView.scrollToItem(at: IndexPath(item: count - 1, section: 0), at: .left, animated: animated) } } - func doneButtonTapped(_ sender: UIButton) { - self.delegate?.photoCaptureViewControllerDidFinish(self) + func doneButtonTapped(_: UIButton) { + delegate?.photoCaptureViewControllerDidFinish(self) dismiss(animated: true, completion: nil) } @@ -425,10 +425,10 @@ open class PhotoCaptureViewController: UIViewController, PhotoCollectionViewLayo focusIndicatorView.center = point UIView.animate(withDuration: 0.3, delay: 0.0, options: .beginFromCurrentState, animations: { self.focusIndicatorView.alpha = 1.0 - }, completion: { finished in - UIView.animate(withDuration: 0.2, delay: 1.6, options: .beginFromCurrentState, animations: { - self.focusIndicatorView.alpha = 0.0 - }, completion: nil) + }, completion: { _ in + UIView.animate(withDuration: 0.2, delay: 1.6, options: .beginFromCurrentState, animations: { + self.focusIndicatorView.alpha = 0.0 + }, completion: nil) }) captureManager.lockFocusAtPointOfInterest(point) @@ -437,7 +437,7 @@ open class PhotoCaptureViewController: UIViewController, PhotoCollectionViewLayo // MARK: - PhotoCollectionViewLayoutDelegate - open func photoCollectionViewLayout(_ layout: UICollectionViewLayout, canMoveItemAtIndexPath indexPath: IndexPath) -> Bool { + open func photoCollectionViewLayout(_: UICollectionViewLayout, canMoveItemAtIndexPath indexPath: IndexPath) -> Bool { return delegate?.photoCaptureViewController(self, canMoveItemAtIndexPath: indexPath) ?? true } @@ -449,7 +449,7 @@ open class PhotoCaptureViewController: UIViewController, PhotoCollectionViewLayo button.backgroundColor = UIColor.black.withAlphaComponent(0.3) button.layer.borderColor = button.tintColor!.cgColor button.layer.borderWidth = 1.0 - button.layer.cornerRadius = button.bounds.height/2 + button.layer.cornerRadius = button.bounds.height / 2 var insets = button.imageEdgeInsets insets.left -= inset @@ -460,8 +460,8 @@ open class PhotoCaptureViewController: UIViewController, PhotoCollectionViewLayo var flashPosition = flashButton.frame.origin var pickerPosition = pickerButton.frame.origin if orientation == .landscapeLeft || orientation == .landscapeRight { - flashPosition = CGPoint(x: buttonMargin - (buttonMargin/3), y: buttonMargin) - pickerPosition = CGPoint(x: view.bounds.width - (pickerButton.bounds.size.width/2 - buttonMargin), y: buttonMargin) + flashPosition = CGPoint(x: buttonMargin - (buttonMargin / 3), y: buttonMargin) + pickerPosition = CGPoint(x: view.bounds.width - (pickerButton.bounds.size.width / 2 - buttonMargin), y: buttonMargin) } else if orientation == .portrait || orientation == .portraitUpsideDown { pickerPosition = CGPoint(x: view.bounds.width - (pickerButton.bounds.size.width + buttonMargin), y: buttonMargin) flashPosition = CGPoint(x: buttonMargin, y: buttonMargin) @@ -481,9 +481,8 @@ open class PhotoCaptureViewController: UIViewController, PhotoCollectionViewLayo } } - extension PhotoCaptureViewController: UICollectionViewDataSource, PhotoCollectionViewCellDelegate { - public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { + public func collectionView(_: UICollectionView, numberOfItemsInSection _: Int) -> Int { return delegate?.photoCaptureViewControllerNumberOfAssets(self) ?? 0 } @@ -502,24 +501,22 @@ extension PhotoCaptureViewController: UICollectionViewDataSource, PhotoCollectio func collectionViewCellDidTapDelete(_ cell: PhotoCollectionViewCell) { if let indexPath = collectionView.indexPath(for: cell) { - self.deleteAssetAtIndex(indexPath.item, handler: { + deleteAssetAtIndex(indexPath.item, handler: { self.delegate?.photoCaptureViewController(self, deleteAssetAtIndexPath: indexPath) }) } } } - extension PhotoCaptureViewController: UICollectionViewDelegate { - public func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { + public func collectionView(_: UICollectionView, didSelectItemAt indexPath: IndexPath) { delegate?.photoCaptureViewController(self, didSelectAssetAtIndexPath: indexPath) } } - extension UIView { public func rotateToCurrentDeviceOrientation() { - self.rotateToDeviceOrientation(UIDevice.current.orientation) + rotateToDeviceOrientation(UIDevice.current.orientation) } public func rotateToDeviceOrientation(_ orientation: UIDeviceOrientation) { @@ -527,11 +524,11 @@ extension UIView { case .faceDown, .faceUp, .unknown: () case .landscapeLeft: - self.transform = CGAffineTransform(rotationAngle: CGFloat(Double.pi/2)) + transform = CGAffineTransform(rotationAngle: CGFloat(Double.pi / 2)) case .landscapeRight: - self.transform = CGAffineTransform(rotationAngle: CGFloat(-Double.pi/2)) + transform = CGAffineTransform(rotationAngle: CGFloat(-Double.pi / 2)) case .portrait, .portraitUpsideDown: - self.transform = CGAffineTransform(rotationAngle: 0) + transform = CGAffineTransform(rotationAngle: 0) } } } diff --git a/Finjinon/PhotoCollectionViewCell.swift b/Finjinon/PhotoCollectionViewCell.swift index 0b18124..74749fa 100644 --- a/Finjinon/PhotoCollectionViewCell.swift +++ b/Finjinon/PhotoCollectionViewCell.swift @@ -8,7 +8,6 @@ internal protocol PhotoCollectionViewCellDelegate: NSObjectProtocol { func collectionViewCellDidTapDelete(_ cell: PhotoCollectionViewCell) } - open class PhotoCollectionViewCell: UICollectionViewCell { open class func cellIdentifier() -> String { return "PhotoCell" } @@ -21,8 +20,8 @@ open class PhotoCollectionViewCell: UICollectionViewCell { public override init(frame: CGRect) { super.init(frame: frame) - let offset = self.closeButton.bounds.height/3 - imageView.frame = CGRect(x: offset, y: offset, width: contentView.bounds.width - (offset*2), height: contentView.bounds.height - (offset*2)) + let offset = closeButton.bounds.height / 3 + imageView.frame = CGRect(x: offset, y: offset, width: contentView.bounds.width - (offset * 2), height: contentView.bounds.height - (offset * 2)) imageView.autoresizingMask = [.flexibleWidth, .flexibleHeight] imageView.contentMode = .scaleAspectFill imageView.clipsToBounds = true @@ -32,7 +31,7 @@ open class PhotoCollectionViewCell: UICollectionViewCell { contentView.addSubview(closeButton) } - required public init?(coder aDecoder: NSCoder) { + public required init?(coder _: NSCoder) { fatalError("init(coder:) has not been implemented") } @@ -43,33 +42,33 @@ open class PhotoCollectionViewCell: UICollectionViewCell { asset = nil } - internal func closeButtonTapped(_ sender: UIButton) { + internal func closeButtonTapped(_: UIButton) { delegate?.collectionViewCellDidTapDelete(self) } internal func proxy() -> UIView { var wrapperFrame = self.imageView.bounds - wrapperFrame.origin.x = (bounds.size.width - wrapperFrame.size.width)/2 - wrapperFrame.origin.y = (bounds.size.height - wrapperFrame.size.height)/2 + wrapperFrame.origin.x = (bounds.size.width - wrapperFrame.size.width) / 2 + wrapperFrame.origin.y = (bounds.size.height - wrapperFrame.size.height) / 2 let imageWrapper = UIView(frame: wrapperFrame) imageWrapper.clipsToBounds = true let image = UIImage(cgImage: self.imageView.image!.cgImage!, scale: self.imageView.image!.scale, orientation: self.imageView.image!.imageOrientation) // Cumbersome indeed, but unfortunately re-rendering through begin graphicContext etc. fails quite often in iOS9 - var imageRect : CGRect { + var imageRect: CGRect { let viewSize = self.imageView.frame.size let imageIsLandscape = image.size.width > image.size.height if imageIsLandscape { let ratio = image.size.height / viewSize.height let width = image.size.width / ratio - let x = -(width - viewSize.width)/2 + let x = -(width - viewSize.width) / 2 return CGRect(x: x, y: 0, width: width, height: viewSize.height) } else { let ratio = image.size.width / viewSize.width let height = image.size.height / ratio - let y = -(height - viewSize.height)/2 + let y = -(height - viewSize.height) / 2 return CGRect(x: 0, y: y, width: viewSize.width, height: height) } } diff --git a/Finjinon/PhotoCollectionViewLayout.swift b/Finjinon/PhotoCollectionViewLayout.swift index bfcde9a..75c0592 100644 --- a/Finjinon/PhotoCollectionViewLayout.swift +++ b/Finjinon/PhotoCollectionViewLayout.swift @@ -23,7 +23,7 @@ private class DraggingProxy: UIView { addSubview(proxyView) } - required init?(coder aDecoder: NSCoder) { + required init?(coder _: NSCoder) { fatalError("init(coder:) has not been implemented") } } @@ -33,7 +33,7 @@ public protocol PhotoCollectionViewLayoutDelegate: NSObjectProtocol { } internal class PhotoCollectionViewLayout: UICollectionViewFlowLayout, UIGestureRecognizerDelegate { - internal var didReorderHandler: (_ fromIndexPath: IndexPath, _ toIndexPath: IndexPath) -> Void = { (_,_) in } + internal var didReorderHandler: (_ fromIndexPath: IndexPath, _ toIndexPath: IndexPath) -> Void = { _, _ in } fileprivate var insertedIndexPaths: [IndexPath] = [] fileprivate var deletedIndexPaths: [IndexPath] = [] fileprivate var longPressGestureRecognizer = UILongPressGestureRecognizer() @@ -43,19 +43,19 @@ internal class PhotoCollectionViewLayout: UICollectionViewFlowLayout, UIGestureR override init() { super.init() - self.addObserver(self, forKeyPath: "collectionView", options: [], context: nil) + addObserver(self, forKeyPath: "collectionView", options: [], context: nil) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) - self.addObserver(self, forKeyPath: "collectionView", options: [], context: nil) + addObserver(self, forKeyPath: "collectionView", options: [], context: nil) } deinit { self.removeObserver(self, forKeyPath: "collectionView", context: nil) } - override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { + override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey: Any]?, context: UnsafeMutableRawPointer?) { if keyPath == "collectionView" { setupGestureRecognizers() } else { @@ -98,10 +98,10 @@ internal class PhotoCollectionViewLayout: UICollectionViewFlowLayout, UIGestureR if let attrs = attrs { attrs.alpha = 0.0 attrs.zIndex = itemIndexPath.item - attrs.center.x = self.collectionView!.frame.width / 2 - attrs.center.y = self.collectionView!.frame.height - if self.collectionView!.contentOffset.x > 0.0 { - attrs.center.x += self.collectionView!.contentOffset.x + attrs.center.x = collectionView!.frame.width / 2 + attrs.center.y = collectionView!.frame.height + if collectionView!.contentOffset.x > 0.0 { + attrs.center.x += collectionView!.contentOffset.x } attrs.transform3D = CATransform3DScale(attrs.transform3D, 0.001, 0.001, 1) } @@ -116,10 +116,10 @@ internal class PhotoCollectionViewLayout: UICollectionViewFlowLayout, UIGestureR if deletedIndexPaths.contains(itemIndexPath) { if let attrs = attrs { attrs.alpha = 0.0 - attrs.center.x = self.collectionView!.frame.width / 2 - attrs.center.y = self.collectionView!.frame.height - if self.collectionView!.contentOffset.x > 0.0 { - attrs.center.x += self.collectionView!.contentOffset.x + attrs.center.x = collectionView!.frame.width / 2 + attrs.center.y = collectionView!.frame.height + if collectionView!.contentOffset.x > 0.0 { + attrs.center.x += collectionView!.contentOffset.x } attrs.transform3D = CATransform3DScale(attrs.transform3D, 0.001, 0.001, 1) } @@ -209,16 +209,16 @@ internal class PhotoCollectionViewLayout: UICollectionViewFlowLayout, UIGestureR UIView.animate(withDuration: 0.2, delay: 0.0, options: [.beginFromCurrentState, .curveEaseIn], animations: { proxy.center = proxy.dragCenter proxy.transform = CGAffineTransform.identity - }, completion: { finished in - proxy.removeFromSuperview() + }, completion: { _ in + proxy.removeFromSuperview() - if let fromIndexPath = proxy.fromIndexPath, let toIndexPath = proxy.toIndexPath { - self.didReorderHandler(fromIndexPath, toIndexPath) - } + if let fromIndexPath = proxy.fromIndexPath, let toIndexPath = proxy.toIndexPath { + self.didReorderHandler(fromIndexPath, toIndexPath) + } - self.dragProxy = nil + self.dragProxy = nil - self.invalidateLayout() + self.invalidateLayout() }) } default: @@ -232,21 +232,21 @@ internal class PhotoCollectionViewLayout: UICollectionViewFlowLayout, UIGestureR case .changed: if let proxy = dragProxy { proxy.center.x = proxy.initialCenter.x + translation.x - //TODO: Constrain to be within collectionView.frame: + // TODO: Constrain to be within collectionView.frame: // proxy.center.y = proxy.originalCenter.y + translation.y if let fromIndexPath = proxy.dragIndexPath, let toIndexPath = collectionView!.indexPathForItem(at: proxy.center), let targetLayoutAttributes = layoutAttributesForItem(at: toIndexPath) { - proxy.dragIndexPath = toIndexPath - proxy.dragCenter = targetLayoutAttributes.center - proxy.bounds = targetLayoutAttributes.bounds - proxy.toIndexPath = toIndexPath - - collectionView?.performBatchUpdates({ - self.collectionView?.moveItem(at: fromIndexPath, to: toIndexPath) - }, completion: nil - ) + proxy.dragIndexPath = toIndexPath + proxy.dragCenter = targetLayoutAttributes.center + proxy.bounds = targetLayoutAttributes.bounds + proxy.toIndexPath = toIndexPath + + collectionView?.performBatchUpdates({ + self.collectionView?.moveItem(at: fromIndexPath, to: toIndexPath) + }, completion: nil + ) } } default: @@ -263,7 +263,7 @@ internal class PhotoCollectionViewLayout: UICollectionViewFlowLayout, UIGestureR longPressGestureRecognizer = UILongPressGestureRecognizer(target: self, action: #selector(handleLongPressGestureRecognized(_:))) longPressGestureRecognizer.delegate = self collectionView!.addGestureRecognizer(longPressGestureRecognizer) - + panGestureRecognizer = UIPanGestureRecognizer(target: self, action: #selector(handlePanGestureRecognized(_:))) panGestureRecognizer.delegate = self panGestureRecognizer.maximumNumberOfTouches = 1 diff --git a/Finjinon/PhotoStorage.swift b/Finjinon/PhotoStorage.swift index 00476aa..fada18b 100644 --- a/Finjinon/PhotoStorage.swift +++ b/Finjinon/PhotoStorage.swift @@ -10,7 +10,7 @@ public enum AssetImageDataSourceTypes { case camera, library, unknown } -// TODO also support ALAsset/PHPhoto +// TODO: also support ALAsset/PHPhoto public struct Asset: Equatable, CustomStringConvertible { public let UUID = Foundation.UUID().uuidString @@ -19,6 +19,7 @@ public struct Asset: Equatable, CustomStringConvertible { let url: URL let originalDimensions: CGSize } + fileprivate let remoteReference: Remote? public var imageURL: URL? { return remoteReference?.url @@ -26,12 +27,12 @@ public struct Asset: Equatable, CustomStringConvertible { internal init(storage: PhotoStorage, imageURL: URL, originalDimensions: CGSize) { self.storage = storage - self.remoteReference = Remote(url: imageURL, originalDimensions: originalDimensions) + remoteReference = Remote(url: imageURL, originalDimensions: originalDimensions) } internal init(storage: PhotoStorage) { self.storage = storage - self.remoteReference = nil + remoteReference = nil } public func originalImage(_ result: @escaping (UIImage) -> Void) { @@ -49,7 +50,7 @@ public struct Asset: Equatable, CustomStringConvertible { return storage.dimensionsforAsset(self) } } - + public var imageDataSourceType: AssetImageDataSourceTypes = .unknown public var description: String { @@ -61,7 +62,6 @@ public func ==(lhs: Asset, rhs: Asset) -> Bool { return lhs.UUID == rhs.UUID } - // Public API for creating Asset's open class PhotoStorage { fileprivate let baseURL: URL @@ -73,8 +73,8 @@ open class PhotoStorage { init() { var cacheURL = fileManager.urls(for: .cachesDirectory, in: .userDomainMask).last! - cacheURL = cacheURL.appendingPathComponent("no.finn.finjonon.disk-cache") - self.baseURL = cacheURL.appendingPathComponent(NSUUID().uuidString) + cacheURL = cacheURL.appendingPathComponent("no.finn.finjonon.disk-cache") + baseURL = cacheURL.appendingPathComponent(NSUUID().uuidString) } deinit { @@ -148,9 +148,9 @@ open class PhotoStorage { } else { // On iOS 8.1 [library assetForUrl] for Photo Streams always returns nil. Try to obtain it in an alternative way // http://stackoverflow.com/questions/26480526/alassetslibrary-assetforurl-always-returning-nil-for-photos-in-my-photo-stream - self.assetLibrary.enumerateGroups(withTypes: ALAssetsGroupType(ALAssetsGroupPhotoStream), using: { (group, stop) in + self.assetLibrary.enumerateGroups(withTypes: ALAssetsGroupType(ALAssetsGroupPhotoStream), using: { group, stop in if let group = group { - group.enumerateAssets(options: .reverse, using: { (result, index, innerStop) in + group.enumerateAssets(options: .reverse, using: { result, _, innerStop in if let result = result, result.defaultRepresentation().url() == assetURL { assetHandler(result) innerStop?.initialize(to: true) @@ -158,12 +158,12 @@ open class PhotoStorage { } }) } - }, failureBlock: { error in - NSLog("failed to retrive ALAsset in 8.1 workaround: \(String(describing: error))") + }, failureBlock: { error in + NSLog("failed to retrive ALAsset in 8.1 workaround: \(String(describing: error))") }) } - }, failureBlock: { error in - NSLog("failed to retrive ALAsset: \(String(describing: error))") + }, failureBlock: { error in + NSLog("failed to retrive ALAsset: \(String(describing: error))") }) } @@ -184,21 +184,20 @@ open class PhotoStorage { } func dimensionsforAsset(_ asset: Asset) -> CGSize { - let cacheFileURL = self.cacheURLForAsset(asset) + let cacheFileURL = cacheURLForAsset(asset) if let source = CGImageSourceCreateWithURL(cacheFileURL as CFURL, nil), let imageProperties = CGImageSourceCopyPropertiesAtIndex(source, 0, nil) as NSDictionary? { - if let width = imageProperties[kCGImagePropertyPixelWidth as String] as? CGFloat, - let height = imageProperties[kCGImagePropertyPixelHeight as String] as? CGFloat { - return CGSize(width: width, height: height) - } - return CGSize.zero + if let width = imageProperties[kCGImagePropertyPixelWidth as String] as? CGFloat, + let height = imageProperties[kCGImagePropertyPixelHeight as String] as? CGFloat { + return CGSize(width: width, height: height) + } + return CGSize.zero } else { NSLog("*** Warning: failed to get CGImagePropertyPixel{Width,Height} from \(cacheFileURL)") return CGSize.zero } } - // MARK: - Private fileprivate func imageForAsset(_ asset: Asset, completion: @escaping (UIImage) -> Void) { @@ -212,13 +211,14 @@ open class PhotoStorage { } fileprivate func thumbnailForAsset(_ asset: Asset, forWidth width: CGFloat, completion: @escaping (UIImage) -> Void) { - self.resizeQueue.async { + resizeQueue.async { let imageURL = self.cacheURLForAsset(asset) if let imageSource = CGImageSourceCreateWithURL(imageURL as CFURL, nil) { - let options = [ kCGImageSourceThumbnailMaxPixelSize as NSString: width * UIScreen.main.scale, + let options = [ + kCGImageSourceThumbnailMaxPixelSize as NSString: width * UIScreen.main.scale, kCGImageSourceCreateThumbnailWithTransform as NSString: kCFBooleanTrue, kCGImageSourceCreateThumbnailFromImageAlways as NSString: kCFBooleanTrue, - ] as [NSString : Any] + ] as [NSString: Any] if let thumbnailCGImage = CGImageSourceCreateThumbnailAtIndex(imageSource, 0, options as CFDictionary?) { let thumbnailImage = UIImage(cgImage: thumbnailCGImage) @@ -226,7 +226,7 @@ open class PhotoStorage { completion(thumbnailImage) } } - } // TODO else throws + } // TODO: else throws } } @@ -236,10 +236,10 @@ open class PhotoStorage { } fileprivate func ensureCacheDirectoryExists() { - if !fileManager.fileExists(atPath: self.baseURL.path) { + if !fileManager.fileExists(atPath: baseURL.path) { var error: NSError? do { - try fileManager.createDirectory(at: self.baseURL, withIntermediateDirectories: true, attributes: nil) + try fileManager.createDirectory(at: baseURL, withIntermediateDirectories: true, attributes: nil) } catch let error1 as NSError { error = error1 NSLog("Failed to create cache directory at \(baseURL): \(String(describing: error))") diff --git a/FinjinonTests/FinjinonTests.swift b/FinjinonTests/FinjinonTests.swift index 781798d..4251ee7 100644 --- a/FinjinonTests/FinjinonTests.swift +++ b/FinjinonTests/FinjinonTests.swift @@ -57,7 +57,4 @@ class FinjinonTests: XCTestCase { XCTAssertEqual(unchangeableTransform.b, faceUpTransform.b) XCTAssertEqual(unchangeableTransform.c, faceUpTransform.c) } - - - }