diff --git a/AKMediaViewer/AKImageScrollView.swift b/AKMediaViewer/AKImageScrollView.swift index 77aca07..ed170d4 100644 --- a/AKMediaViewer/AKImageScrollView.swift +++ b/AKMediaViewer/AKImageScrollView.swift @@ -13,8 +13,8 @@ public class AKImageScrollView : UIScrollView, UIScrollViewDelegate { public var zoomImageView: UIImageView? - var imageSize: CGSize = CGSizeZero - var pointToCenterAfterResize: CGPoint = CGPointZero + var imageSize: CGSize = CGSize.zero + var pointToCenterAfterResize: CGPoint = CGPoint.zero var scaleToRestoreAfterResize: CGFloat = 0.0 override public init(frame: CGRect) { @@ -23,7 +23,7 @@ public class AKImageScrollView : UIScrollView, UIScrollViewDelegate { showsVerticalScrollIndicator = false showsHorizontalScrollIndicator = false bouncesZoom = true - decelerationRate = UIScrollViewDecelerationRateFast + decelerationRate = UIScrollView.DecelerationRate.fast } required public init?(coder aDecoder: NSCoder) { @@ -58,7 +58,7 @@ public class AKImageScrollView : UIScrollView, UIScrollViewDelegate { return super.frame } set (newFrame) { - let sizeChanging: Bool = !CGSizeEqualToSize(newFrame.size, self.frame.size) + let sizeChanging: Bool = !newFrame.size.equalTo(self.frame.size) if (sizeChanging) { prepareToResize() @@ -74,7 +74,7 @@ public class AKImageScrollView : UIScrollView, UIScrollViewDelegate { // MARK: - Configure scrollView to display new image - public func displayImage(image: UIImage) { + public func displayImage(_ image: UIImage) { if(zoomImageView == nil) { self.zoomScale = 1.0 @@ -87,7 +87,7 @@ public class AKImageScrollView : UIScrollView, UIScrollViewDelegate { configureForImageSize(image.size) } - func configureForImageSize(imageSize: CGSize) { + func configureForImageSize(_ imageSize: CGSize) { self.imageSize = imageSize self.contentSize = imageSize setMaxMinZoomScalesForCurrentBounds() @@ -126,8 +126,8 @@ public class AKImageScrollView : UIScrollView, UIScrollViewDelegate { // MARK: - Rotation support func prepareToResize() { - let boundsCenter: CGPoint = CGPointMake(CGRectGetMidX(self.bounds), CGRectGetMidY(self.bounds)) - pointToCenterAfterResize = self.convertPoint(boundsCenter, toView: zoomImageView) + let boundsCenter: CGPoint = CGPoint(x: self.bounds.midX, y: self.bounds.midY) + pointToCenterAfterResize = self.convert(boundsCenter, to: zoomImageView) scaleToRestoreAfterResize = self.zoomScale @@ -148,10 +148,10 @@ public class AKImageScrollView : UIScrollView, UIScrollViewDelegate { // Step 2: restore center point, first making sure it is within the allowable range. // 2a: convert our desired center point back to our own coordinate space - let boundsCenter: CGPoint = self.convertPoint(pointToCenterAfterResize, toView: zoomImageView) + let boundsCenter: CGPoint = self.convert(pointToCenterAfterResize, to: zoomImageView) // 2b: calculate the content offset that would yield that center point - var offset: CGPoint = CGPointMake(boundsCenter.x - self.bounds.size.width / 2.0, boundsCenter.y - self.bounds.size.height / 2.0) + var offset: CGPoint = CGPoint(x: boundsCenter.x - self.bounds.size.width / 2.0, y: boundsCenter.y - self.bounds.size.height / 2.0) // 2c: restore offset, adjusted to be within the allowable range let maxOffset: CGPoint = maximumContentOffset() @@ -169,10 +169,10 @@ public class AKImageScrollView : UIScrollView, UIScrollViewDelegate { func maximumContentOffset() -> CGPoint { let contentSize: CGSize = self.contentSize let boundsSize: CGSize = self.bounds.size - return CGPointMake(contentSize.width - boundsSize.width, contentSize.height - boundsSize.height) + return CGPoint(x: contentSize.width - boundsSize.width, y: contentSize.height - boundsSize.height) } func minimumContentOffset() -> CGPoint { - return CGPointZero + return CGPoint.zero } } diff --git a/AKMediaViewer/AKMediaFocusBasicToolbarController.swift b/AKMediaViewer/AKMediaFocusBasicToolbarController.swift index f2289d0..713d874 100644 --- a/AKMediaViewer/AKMediaFocusBasicToolbarController.swift +++ b/AKMediaViewer/AKMediaFocusBasicToolbarController.swift @@ -16,14 +16,14 @@ public class AKMediaFocusBasicToolbarController : UIViewController { public override func viewDidLoad() { - doneButton.setTitle(NSLocalizedString("Done", comment: "Done"), forState: UIControlState.Normal) - doneButton.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal) + doneButton.setTitle(NSLocalizedString("Done", comment: "Done"), for: UIControl.State()) + doneButton.setTitleColor(UIColor.white, for: UIControl.State()) doneButton.backgroundColor = UIColor.init(white: 0, alpha: 0.5) doneButton.sizeToFit() - doneButton.frame = CGRectInset(self.doneButton.frame, -20, -4) + doneButton.frame = self.doneButton.frame.insetBy(dx: -20, dy: -4) doneButton.layer.borderWidth = 2 doneButton.layer.cornerRadius = 4 - doneButton.layer.borderColor = UIColor.whiteColor().CGColor + doneButton.layer.borderColor = UIColor.white.cgColor } } diff --git a/AKMediaViewer/AKMediaViewerController.swift b/AKMediaViewer/AKMediaViewerController.swift index 7470a51..7bdd265 100644 --- a/AKMediaViewer/AKMediaViewerController.swift +++ b/AKMediaViewer/AKMediaViewerController.swift @@ -10,22 +10,24 @@ import Foundation import AVFoundation import UIKit -let kDefaultOrientationAnimationDuration: NSTimeInterval = 0.4 +let kDefaultOrientationAnimationDuration: TimeInterval = 0.4 let kDefaultControlMargin: CGFloat = 5 // MARK: - PlayerView public class PlayerView: UIView { - override public class func layerClass() -> AnyClass { - return AVPlayerLayer.self + public override class var layerClass: AnyClass { + get { + AVPlayerLayer.self + } } - + func player() -> AVPlayer { return (layer as! AVPlayerLayer).player! } - func setPlayer(player: AVPlayer) { + func setPlayer(_ player: AVPlayer) { (layer as! AVPlayerLayer).player = player } } @@ -46,12 +48,12 @@ public class AKMediaViewerController : UIViewController, UIScrollViewDelegate { @IBOutlet var accessoryView: UIView! @IBOutlet var contentView: UIView! - var accessoryViewTimer: NSTimer? + var accessoryViewTimer: Timer? var player: AVPlayer? - var previousOrientation: UIDeviceOrientation = UIDeviceOrientation.Unknown + var previousOrientation: UIDeviceOrientation = UIDeviceOrientation.unknown var activityIndicator : UIActivityIndicatorView? - override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) { + override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) doubleTapGesture = UITapGestureRecognizer(target: self, action: #selector(AKMediaViewerController.handleDoubleTap(_:))) @@ -59,7 +61,7 @@ public class AKMediaViewerController : UIViewController, UIScrollViewDelegate { controlMargin = kDefaultControlMargin tapGesture = UITapGestureRecognizer(target: self, action: #selector(AKMediaViewerController.handleTap(_:))) - tapGesture.requireGestureRecognizerToFail(doubleTapGesture) + tapGesture.require(toFail: doubleTapGesture) view.addGestureRecognizer(tapGesture) } @@ -80,48 +82,50 @@ public class AKMediaViewerController : UIViewController, UIScrollViewDelegate { override public func viewDidLoad() { super.viewDidLoad() titleLabel.layer.shadowOpacity = 1 - titleLabel.layer.shadowOffset = CGSizeZero + titleLabel.layer.shadowOffset = CGSize.zero titleLabel.layer.shadowRadius = 1 accessoryView.alpha = 0 } - override public func viewDidAppear(animated: Bool) { - NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(AKMediaViewerController.orientationDidChangeNotification(_:)), name: UIDeviceOrientationDidChangeNotification, object: nil) - UIDevice.currentDevice().beginGeneratingDeviceOrientationNotifications() + override public func viewDidAppear(_ animated: Bool) { + NotificationCenter.default.addObserver(self, selector: #selector(AKMediaViewerController.orientationDidChangeNotification(_:)), name: UIDevice.orientationDidChangeNotification, object: nil) + UIDevice.current.beginGeneratingDeviceOrientationNotifications() super.viewDidAppear(animated) } - override public func viewWillDisappear(animated: Bool) { + override public func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) - NSNotificationCenter.defaultCenter().removeObserver(self, name: UIDeviceOrientationDidChangeNotification, object: nil) - UIDevice.currentDevice().endGeneratingDeviceOrientationNotifications() + NotificationCenter.default.removeObserver(self, name: UIDevice.orientationDidChangeNotification, object: nil) + UIDevice.current.endGeneratingDeviceOrientationNotifications() } - override public func supportedInterfaceOrientations() -> UIInterfaceOrientationMask { - return UIInterfaceOrientationMask.Portrait + public override var supportedInterfaceOrientations: UIInterfaceOrientationMask { + get { + return UIInterfaceOrientationMask.portrait + } } - func isParentSupportingInterfaceOrientation(toInterfaceOrientation : UIInterfaceOrientation) -> Bool { + func isParentSupportingInterfaceOrientation(_ toInterfaceOrientation : UIInterfaceOrientation) -> Bool { switch(toInterfaceOrientation) { - case UIInterfaceOrientation.Portrait: - return parentViewController!.supportedInterfaceOrientations().contains(UIInterfaceOrientationMask.Portrait) + case UIInterfaceOrientation.portrait: + return parent!.supportedInterfaceOrientations.contains(UIInterfaceOrientationMask.portrait) - case UIInterfaceOrientation.PortraitUpsideDown: - return parentViewController!.supportedInterfaceOrientations().contains(UIInterfaceOrientationMask.PortraitUpsideDown) + case UIInterfaceOrientation.portraitUpsideDown: + return parent!.supportedInterfaceOrientations.contains(UIInterfaceOrientationMask.portraitUpsideDown) - case UIInterfaceOrientation.LandscapeLeft: - return parentViewController!.supportedInterfaceOrientations().contains(UIInterfaceOrientationMask.LandscapeLeft) + case UIInterfaceOrientation.landscapeLeft: + return parent!.supportedInterfaceOrientations.contains(UIInterfaceOrientationMask.landscapeLeft) - case UIInterfaceOrientation.LandscapeRight: - return parentViewController!.supportedInterfaceOrientations().contains(UIInterfaceOrientationMask.LandscapeRight) + case UIInterfaceOrientation.landscapeRight: + return parent!.supportedInterfaceOrientations.contains(UIInterfaceOrientationMask.landscapeRight) - case UIInterfaceOrientation.Unknown: + case UIInterfaceOrientation.unknown: return true } } - override public func beginAppearanceTransition(isAppearing: Bool, animated: Bool) { + override public func beginAppearanceTransition(_ isAppearing: Bool, animated: Bool) { if(!isAppearing) { accessoryView.alpha = 0 playerView?.alpha = 0 @@ -137,60 +141,60 @@ public class AKMediaViewerController : UIViewController, UIScrollViewDelegate { // MARK: - Public - public func updateOrientationAnimated(animated: Bool) { + public func updateOrientationAnimated(_ animated: Bool) { var transform: CGAffineTransform? var frame: CGRect - var duration: NSTimeInterval = kDefaultOrientationAnimationDuration + var duration: TimeInterval = kDefaultOrientationAnimationDuration - if (UIDevice.currentDevice().orientation == previousOrientation) { + if (UIDevice.current.orientation == previousOrientation) { return } - if (UIDeviceOrientationIsLandscape(UIDevice.currentDevice().orientation) && UIDeviceOrientationIsLandscape(previousOrientation)) || - (UIDeviceOrientationIsPortrait(UIDevice.currentDevice().orientation) && UIDeviceOrientationIsPortrait(previousOrientation)) + if (UIDevice.current.orientation.isLandscape && previousOrientation.isLandscape) || + (UIDevice.current.orientation.isPortrait && previousOrientation.isPortrait) { duration *= 2 } - if(UIDevice.currentDevice().orientation == UIDeviceOrientation.Portrait) || isParentSupportingInterfaceOrientation(UIApplication.sharedApplication().statusBarOrientation) { - transform = CGAffineTransformIdentity + if(UIDevice.current.orientation == UIDeviceOrientation.portrait) || isParentSupportingInterfaceOrientation(UIApplication.shared.statusBarOrientation) { + transform = CGAffineTransform.identity } else { - switch (UIDevice.currentDevice().orientation) + switch (UIDevice.current.orientation) { - case UIDeviceOrientation.LandscapeRight: - if(parentViewController!.interfaceOrientation == UIInterfaceOrientation.Portrait) { - transform = CGAffineTransformMakeRotation(CGFloat(-M_PI_2)) + case UIDeviceOrientation.landscapeRight: + if(parent!.interfaceOrientation == UIInterfaceOrientation.portrait) { + transform = CGAffineTransform(rotationAngle: CGFloat(-M_PI_2)) } else { - transform = CGAffineTransformMakeRotation(CGFloat(M_PI_2)) + transform = CGAffineTransform(rotationAngle: CGFloat(M_PI_2)) } break - case UIDeviceOrientation.LandscapeLeft: - if(parentViewController!.interfaceOrientation == UIInterfaceOrientation.Portrait) { - transform = CGAffineTransformMakeRotation(CGFloat(M_PI_2)) + case UIDeviceOrientation.landscapeLeft: + if(parent!.interfaceOrientation == UIInterfaceOrientation.portrait) { + transform = CGAffineTransform(rotationAngle: CGFloat(M_PI_2)) } else { - transform = CGAffineTransformMakeRotation(CGFloat(-M_PI_2)) + transform = CGAffineTransform(rotationAngle: CGFloat(-M_PI_2)) } break - case UIDeviceOrientation.Portrait: - transform = CGAffineTransformIdentity + case UIDeviceOrientation.portrait: + transform = CGAffineTransform.identity break - case UIDeviceOrientation.PortraitUpsideDown: - transform = CGAffineTransformMakeRotation(CGFloat(M_PI)) + case UIDeviceOrientation.portraitUpsideDown: + transform = CGAffineTransform(rotationAngle: CGFloat(M_PI)) break - case UIDeviceOrientation.FaceDown: return - case UIDeviceOrientation.FaceUp: return - case UIDeviceOrientation.Unknown: return + case UIDeviceOrientation.faceDown: return + case UIDeviceOrientation.faceUp: return + case UIDeviceOrientation.unknown: return } } if (animated) { frame = contentView.frame - UIView.animateWithDuration(duration, animations: { () -> Void in + UIView.animate(withDuration: duration, animations: { () -> Void in self.contentView.transform = transform! self.contentView.frame = frame }) @@ -199,41 +203,41 @@ public class AKMediaViewerController : UIViewController, UIScrollViewDelegate { self.contentView.transform = transform! self.contentView.frame = frame } - self.previousOrientation = UIDevice.currentDevice().orientation + self.previousOrientation = UIDevice.current.orientation } - public func showPlayerWithURL(url: NSURL) { + public func showPlayerWithURL(_ url: URL) { playerView = PlayerView.init(frame: mainImageView.bounds) mainImageView.addSubview(self.playerView!) - playerView!.autoresizingMask = [UIViewAutoresizing.FlexibleWidth , UIViewAutoresizing.FlexibleHeight] - playerView!.hidden = true + playerView!.autoresizingMask = [UIView.AutoresizingMask.flexibleWidth , UIView.AutoresizingMask.flexibleHeight] + playerView!.isHidden = true // install loading spinner for remote files - if(!url.fileURL) { - self.activityIndicator = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.WhiteLarge) - self.activityIndicator!.frame = UIScreen.mainScreen().bounds + if(!url.isFileURL) { + self.activityIndicator = UIActivityIndicatorView(style: UIActivityIndicatorView.Style.whiteLarge) + self.activityIndicator!.frame = UIScreen.main.bounds self.activityIndicator!.hidesWhenStopped = true view.addSubview(self.activityIndicator!) self.activityIndicator!.startAnimating() } - dispatch_async(dispatch_get_main_queue(), { () -> Void in - self.player = AVPlayer(URL: url) + DispatchQueue.main.async(execute: { () -> Void in + self.player = AVPlayer(url: url) (self.playerView as! PlayerView).setPlayer(self.player!) - self.player!.currentItem?.addObserver(self, forKeyPath: "presentationSize", options: NSKeyValueObservingOptions.New, context: nil) + self.player!.currentItem?.addObserver(self, forKeyPath: "presentationSize", options: NSKeyValueObservingOptions.new, context: nil) self.layoutControlView() self.activityIndicator?.stopAnimating() }) } - public func focusDidEndWithZoomEnabled(zoomEnabled: Bool) { + public func focusDidEndWithZoomEnabled(_ zoomEnabled: Bool) { if(zoomEnabled && (playerView == nil)) { installZoomView() } view.setNeedsLayout() showAccessoryView(true) - playerView?.hidden = false + playerView?.isHidden = false player?.play() addAccessoryViewTimer() @@ -251,31 +255,31 @@ public class AKMediaViewerController : UIViewController, UIScrollViewDelegate { func addAccessoryViewTimer() { if (player != nil) { - accessoryViewTimer = NSTimer.scheduledTimerWithTimeInterval(1.5, target: self, selector: #selector(AKMediaViewerController.removeAccessoryViewTimer), userInfo: nil, repeats: false) + accessoryViewTimer = Timer.scheduledTimer(timeInterval: 1.5, target: self, selector: #selector(AKMediaViewerController.removeAccessoryViewTimer), userInfo: nil, repeats: false) } } - func removeAccessoryViewTimer() { + @objc func removeAccessoryViewTimer() { accessoryViewTimer?.invalidate() showAccessoryView(false) } func installZoomView() { let scrollView: AKImageScrollView = AKImageScrollView.init(frame: contentView.bounds) - scrollView.autoresizingMask = [UIViewAutoresizing.FlexibleHeight, UIViewAutoresizing.FlexibleWidth] + scrollView.autoresizingMask = [UIView.AutoresizingMask.flexibleHeight, UIView.AutoresizingMask.flexibleWidth] scrollView.delegate = self imageScrollView = scrollView - contentView.insertSubview(scrollView, atIndex: 0) + contentView.insertSubview(scrollView, at: 0) scrollView.displayImage(mainImageView.image!) - self.mainImageView.hidden = true + self.mainImageView.isHidden = true imageScrollView.addGestureRecognizer(doubleTapGesture) } func uninstallZoomView() { - let frame: CGRect = contentView.convertRect(imageScrollView.zoomImageView!.frame, fromView: imageScrollView) - imageScrollView.hidden = true - mainImageView.hidden = false + let frame: CGRect = contentView.convert(imageScrollView.zoomImageView!.frame, from: imageScrollView) + imageScrollView.isHidden = true + mainImageView.isHidden = false mainImageView.frame = frame } @@ -283,8 +287,8 @@ public class AKMediaViewerController : UIViewController, UIScrollViewDelegate { return (accessoryView.superview == view) } - func pinView(view: UIView) { - let frame: CGRect = self.view.convertRect(view.frame, fromView: view.superview) + func pinView(_ view: UIView) { + let frame: CGRect = self.view.convert(view.frame, from: view.superview) view.transform = view.superview!.transform self.view.addSubview(view) view.frame = frame @@ -295,12 +299,12 @@ public class AKMediaViewerController : UIViewController, UIScrollViewDelegate { pinView(accessoryView) } - func showAccessoryView(visible: Bool) { + func showAccessoryView(_ visible: Bool) { if(visible == accessoryViewsVisible()) { return } - UIView.animateWithDuration(0.5, delay: 0, options: [UIViewAnimationOptions.BeginFromCurrentState, UIViewAnimationOptions.AllowUserInteraction], animations: { () -> Void in + UIView.animate(withDuration: 0.5, delay: 0, options: [UIView.AnimationOptions.beginFromCurrentState, UIView.AnimationOptions.allowUserInteraction], animations: { () -> Void in self.accessoryView.alpha = (visible ? 1 : 0) }, completion: nil) } @@ -330,50 +334,50 @@ public class AKMediaViewerController : UIViewController, UIScrollViewDelegate { frame = self.controlView!.frame frame.size.width = self.view.bounds.size.width - self.controlMargin * 2 frame.origin.x = self.controlMargin - titleFrame = self.controlView!.superview!.convertRect(titleLabel.frame, fromView: titleLabel.superview) + titleFrame = self.controlView!.superview!.convert(titleLabel.frame, from: titleLabel.superview) frame.origin.y = titleFrame.origin.y - frame.size.height - self.controlMargin if(videoFrame.size.width > 0) { - frame.origin.y = min(frame.origin.y, CGRectGetMaxY(videoFrame) - frame.size.height - self.controlMargin as CGFloat) + frame.origin.y = min(frame.origin.y, videoFrame.maxY - frame.size.height - self.controlMargin as CGFloat) } self.controlView!.frame = frame } func buildVideoFrame() -> CGRect { - if(CGSizeEqualToSize(self.player!.currentItem!.presentationSize, CGSizeZero)) { - return CGRectZero + if(self.player!.currentItem!.presentationSize.equalTo(CGSize.zero)) { + return CGRect.zero } - var frame: CGRect = AVMakeRectWithAspectRatioInsideRect(self.player!.currentItem!.presentationSize, self.playerView!.bounds) - frame = CGRectIntegral(frame) + var frame: CGRect = AVMakeRect(aspectRatio: self.player!.currentItem!.presentationSize, insideRect: self.playerView!.bounds) + frame = frame.integral return frame } // MARK: - Actions - func handleTap(gesture: UITapGestureRecognizer) { + @objc func handleTap(_ gesture: UITapGestureRecognizer) { if(imageScrollView.zoomScale == imageScrollView.minimumZoomScale) { showAccessoryView(!accessoryViewsVisible()) } } - func handleDoubleTap(gesture: UITapGestureRecognizer) { - var frame: CGRect = CGRectZero + @objc func handleDoubleTap(_ gesture: UITapGestureRecognizer) { + var frame: CGRect = CGRect.zero var location: CGPoint var contentView: UIView var scale: CGFloat if(imageScrollView.zoomScale == imageScrollView.minimumZoomScale) { scale = imageScrollView.maximumZoomScale - contentView = imageScrollView.delegate!.viewForZoomingInScrollView!(imageScrollView)! - location = gesture.locationInView(contentView) - frame = CGRectMake(location.x*imageScrollView.maximumZoomScale - imageScrollView.bounds.size.width/2, location.y*imageScrollView.maximumZoomScale - imageScrollView.bounds.size.height/2, imageScrollView.bounds.size.width, imageScrollView.bounds.size.height) + contentView = imageScrollView.delegate!.viewForZooming!(in: imageScrollView)! + location = gesture.location(in: contentView) + frame = CGRect(x: location.x*imageScrollView.maximumZoomScale - imageScrollView.bounds.size.width/2, y: location.y*imageScrollView.maximumZoomScale - imageScrollView.bounds.size.height/2, width: imageScrollView.bounds.size.width, height: imageScrollView.bounds.size.height) } else { scale = imageScrollView.minimumZoomScale } - UIView.animateWithDuration(0.5, delay: 0, options: UIViewAnimationOptions.BeginFromCurrentState, animations: { () -> Void in + UIView.animate(withDuration: 0.5, delay: 0, options: UIView.AnimationOptions.beginFromCurrentState, animations: { () -> Void in self.imageScrollView.zoomScale = scale self.imageScrollView.layoutIfNeeded() if (scale == self.imageScrollView.maximumZoomScale) { @@ -384,22 +388,22 @@ public class AKMediaViewerController : UIViewController, UIScrollViewDelegate { // MARK: - - public func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView? { + public func viewForZooming(in scrollView: UIScrollView) -> UIView? { return imageScrollView.zoomImageView } - public func scrollViewDidZoom(scrollView: UIScrollView) { + public func scrollViewDidZoom(_ scrollView: UIScrollView) { showAccessoryView(imageScrollView.zoomScale == imageScrollView.minimumZoomScale) } // MARK: - Notifications - func orientationDidChangeNotification(notification: NSNotification) { + @objc func orientationDidChangeNotification(_ notification: Notification) { updateOrientationAnimated(true) } // MARK: - KVO - override public func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer) { + public override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { view.setNeedsLayout() } } diff --git a/AKMediaViewer/AKMediaViewerManager.swift b/AKMediaViewer/AKMediaViewerManager.swift index 5199bca..9c2f026 100644 --- a/AKMediaViewer/AKMediaViewerManager.swift +++ b/AKMediaViewer/AKMediaViewerManager.swift @@ -20,13 +20,13 @@ let kSwipeOffset: CGFloat = 100 @objc public protocol AKMediaViewerDelegate : NSObjectProtocol { // Returns the view controller in which the focus controller is going to be added. This can be any view controller, full screen or not. - func parentViewControllerForMediaFocusManager(manager: AKMediaViewerManager) -> UIViewController + func parentViewControllerForMediaFocusManager(_ manager: AKMediaViewerManager) -> UIViewController // Returns the URL where the media (image or video) is stored. The URL may be local (file://) or distant (http://). - func mediaFocusManager(manager: AKMediaViewerManager, mediaURLForView view: UIView) -> NSURL + func mediaFocusManager(_ manager: AKMediaViewerManager, mediaURLForView view: UIView) -> URL // Returns the title for this media view. Return nil if you don't want any title to appear. - func mediaFocusManager(manager: AKMediaViewerManager, titleForView view: UIView) -> String + func mediaFocusManager(_ manager: AKMediaViewerManager, titleForView view: UIView) -> String // MARK: - Optional @@ -34,33 +34,33 @@ let kSwipeOffset: CGFloat = 100 Returns an image view that represents the media view. This image from this view is used in the focusing animation view. It is usually a small image. If not implemented, default is the initial media view in case it's an UIImageview. */ - optional func mediaFocusManager(manager: AKMediaViewerManager, imageViewForView view: UIView) -> UIImageView + @objc optional func mediaFocusManager(_ manager: AKMediaViewerManager, imageViewForView view: UIView) -> UIImageView // Returns the final focused frame for this media view. This frame is usually a full screen frame. If not implemented, default is the parent view controller's view frame. - optional func mediaFocusManager(manager: AKMediaViewerManager, finalFrameForView view: UIView) -> CGRect + @objc optional func mediaFocusManager(_ manager: AKMediaViewerManager, finalFrameForView view: UIView) -> CGRect // Called when a focus view is about to be shown. For example, you might use this method to hide the status bar. - optional func mediaFocusManagerWillAppear(manager: AKMediaViewerManager) + @objc optional func mediaFocusManagerWillAppear(_ manager: AKMediaViewerManager) // Called when a focus view has been shown. - optional func mediaFocusManagerDidAppear(manager: AKMediaViewerManager) + @objc optional func mediaFocusManagerDidAppear(_ manager: AKMediaViewerManager) // Called when the view is about to be dismissed by the 'done' button or by gesture. For example, you might use this method to show the status bar (if it was hidden before). - optional func mediaFocusManagerWillDisappear(manager: AKMediaViewerManager) + @objc optional func mediaFocusManagerWillDisappear(_ manager: AKMediaViewerManager) // Called when the view has be dismissed by the 'done' button or by gesture. - optional func mediaFocusManagerDidDisappear(manager: AKMediaViewerManager) + @objc optional func mediaFocusManagerDidDisappear(_ manager: AKMediaViewerManager) // Called before mediaURLForView to check if image is already on memory. - optional func mediaFocusManager(manager: AKMediaViewerManager, cachedImageForView view: UIView) -> UIImage + @objc optional func mediaFocusManager(_ manager: AKMediaViewerManager, cachedImageForView view: UIView) -> UIImage } -// MARK: - AKMediaViewerManager +// MARK: - AKMediaViewerManagerqq public class AKMediaViewerManager : NSObject, UIGestureRecognizerDelegate { // The animation duration. Defaults to 0.5. - public var animationDuration: NSTimeInterval + public var animationDuration: TimeInterval // The background color. Defaults to transparent black. public var backgroundColor: UIColor @@ -100,7 +100,8 @@ public class AKMediaViewerManager : NSObject, UIGestureRecognizerDelegate { var isZooming: Bool var videoBehavior: AKVideoBehavior - override init() { + + public override init() { animationDuration = kAnimationDuration backgroundColor = UIColor.init(white: 0.0, alpha: 0.8) @@ -118,34 +119,34 @@ public class AKMediaViewerManager : NSObject, UIGestureRecognizerDelegate { } // Install focusing gesture on the specified array of views. - public func installOnViews(views: NSArray) { + public func installOnViews(_ views: NSArray) { for view in views { installOnView(view as! UIView) } } // Install focusing gesture on the specified view. - public func installOnView(view: UIView) { + public func installOnView(_ view: UIView) { let tapGesture: UITapGestureRecognizer = UITapGestureRecognizer.init(target: self, action: #selector(AKMediaViewerManager.handleFocusGesture(_:))) view.addGestureRecognizer(tapGesture) - view.userInteractionEnabled = true + view.isUserInteractionEnabled = true let pinchRecognizer: UIPinchGestureRecognizer = UIPinchGestureRecognizer.init(target: self, action: #selector(AKMediaViewerManager.handlePinchFocusGesture(_:))) pinchRecognizer.delegate = self view.addGestureRecognizer(pinchRecognizer) - let url: NSURL = delegate!.mediaFocusManager(self, mediaURLForView: view) + let url: URL = delegate!.mediaFocusManager(self, mediaURLForView: view) if(addPlayIconOnVideo && isVideoURL(url)) { videoBehavior.addVideoIconToView(view, image: playImage) } } - func installDefocusActionOnFocusViewController(focusViewController: AKMediaViewerController!) { + func installDefocusActionOnFocusViewController(_ focusViewController: AKMediaViewerController!) { // We need the view to be loaded. if(focusViewController.view != nil) { if(isDefocusingWithTap) { let tapGesture: UITapGestureRecognizer = UITapGestureRecognizer.init(target: self, action: #selector(AKMediaViewerManager.handleDefocusGesture(_:))) - tapGesture.requireGestureRecognizerToFail(focusViewController.doubleTapGesture) + tapGesture.require(toFail: focusViewController.doubleTapGesture) focusViewController.view.addGestureRecognizer(tapGesture) } else { setupAccessoryViewOnFocusViewController(focusViewController) @@ -153,11 +154,11 @@ public class AKMediaViewerManager : NSObject, UIGestureRecognizerDelegate { } } - func setupAccessoryViewOnFocusViewController(focusViewController: AKMediaViewerController!) { + func setupAccessoryViewOnFocusViewController(_ focusViewController: AKMediaViewerController!) { if(topAccessoryController == nil) { let defaultController: AKMediaFocusBasicToolbarController = AKMediaFocusBasicToolbarController(nibName: "AKMediaFocusBasicToolbar", bundle: nil) - defaultController.view.backgroundColor = UIColor.clearColor() - defaultController.doneButton.addTarget(self, action: #selector(AKMediaViewerManager.endFocusing), forControlEvents:UIControlEvents.TouchUpInside) + defaultController.view.backgroundColor = UIColor.clear + defaultController.doneButton.addTarget(self, action: #selector(AKMediaViewerManager.endFocusing), for:UIControl.Event.touchUpInside) topAccessoryController = defaultController } @@ -170,39 +171,39 @@ public class AKMediaViewerManager : NSObject, UIGestureRecognizerDelegate { // MARK: - Utilities // Taken from https://github.com/rs/SDWebImage/blob/master/SDWebImage/SDWebImageDecoder.m - func decodedImageWithImage(image: UIImage) -> UIImage { + func decodedImageWithImage(_ image: UIImage) -> UIImage { // do not decode animated images if (image.images != nil) { return image } - let imageRef: CGImageRef = image.CGImage! + let imageRef: CGImage = image.cgImage! - let alpha: CGImageAlphaInfo = CGImageGetAlphaInfo(imageRef) - let anyAlpha: Bool = (alpha == CGImageAlphaInfo.First || - alpha == CGImageAlphaInfo.Last || - alpha == CGImageAlphaInfo.PremultipliedFirst || - alpha == CGImageAlphaInfo.PremultipliedLast) + let alpha: CGImageAlphaInfo = imageRef.alphaInfo + let anyAlpha: Bool = (alpha == CGImageAlphaInfo.first || + alpha == CGImageAlphaInfo.last || + alpha == CGImageAlphaInfo.premultipliedFirst || + alpha == CGImageAlphaInfo.premultipliedLast) if (anyAlpha) { return image } // current - let imageColorSpaceModel: CGColorSpaceModel = CGColorSpaceGetModel(CGImageGetColorSpace(imageRef)) - var colorspaceRef: CGColorSpaceRef = CGImageGetColorSpace(imageRef)! + let imageColorSpaceModel: CGColorSpaceModel = imageRef.colorSpace!.model + var colorspaceRef: CGColorSpace = imageRef.colorSpace! - let unsupportedColorSpace: Bool = (imageColorSpaceModel == CGColorSpaceModel.Unknown || - imageColorSpaceModel == CGColorSpaceModel.Monochrome || - imageColorSpaceModel == CGColorSpaceModel.CMYK || - imageColorSpaceModel == CGColorSpaceModel.Indexed) + let unsupportedColorSpace: Bool = (imageColorSpaceModel == CGColorSpaceModel.unknown || + imageColorSpaceModel == CGColorSpaceModel.monochrome || + imageColorSpaceModel == CGColorSpaceModel.cmyk || + imageColorSpaceModel == CGColorSpaceModel.indexed) if (unsupportedColorSpace) { - colorspaceRef = CGColorSpaceCreateDeviceRGB()! + colorspaceRef = CGColorSpaceCreateDeviceRGB() } - let width: size_t = CGImageGetWidth(imageRef) - let height: size_t = CGImageGetHeight(imageRef) + let width: size_t = imageRef.width + let height: size_t = imageRef.height let bytesPerPixel: Int = 4 let bytesPerRow: Int = bytesPerPixel * width let bitsPerComponent: Int = 8 @@ -210,36 +211,36 @@ public class AKMediaViewerManager : NSObject, UIGestureRecognizerDelegate { // CGImageAlphaInfo.None is not supported in CGBitmapContextCreate. // Since the original image here has no alpha info, use CGImageAlphaInfo.NoneSkipLast // to create bitmap graphics contexts without alpha info. - let context: CGContextRef = CGBitmapContextCreate(nil, - width, - height, - bitsPerComponent, - bytesPerRow, - colorspaceRef, - CGBitmapInfo.ByteOrderDefault.rawValue | CGImageAlphaInfo.NoneSkipLast.rawValue)! + let context: CGContext = CGContext(data: nil, + width: width, + height: height, + bitsPerComponent: bitsPerComponent, + bytesPerRow: bytesPerRow, + space: colorspaceRef, + bitmapInfo: CGBitmapInfo().rawValue | CGImageAlphaInfo.noneSkipLast.rawValue)! // Draw the image into the context and retrieve the new bitmap image without alpha - CGContextDrawImage(context, CGRectMake(0, 0, CGFloat(width), CGFloat(height)), imageRef) - let imageRefWithoutAlpha: CGImageRef = CGBitmapContextCreateImage(context)! - let imageWithoutAlpha: UIImage = UIImage.init(CGImage: imageRefWithoutAlpha, scale: image.scale, orientation: image.imageOrientation) + context.draw(imageRef, in: CGRect(x: 0, y: 0, width: CGFloat(width), height: CGFloat(height))) + let imageRefWithoutAlpha: CGImage = context.makeImage()! + let imageWithoutAlpha: UIImage = UIImage.init(cgImage: imageRefWithoutAlpha, scale: image.scale, orientation: image.imageOrientation) return imageWithoutAlpha } - func rectInsetsForRect(frame: CGRect, withRatio ratio: CGFloat) -> CGRect { + func rectInsetsForRect(_ frame: CGRect, withRatio ratio: CGFloat) -> CGRect { let dx: CGFloat let dy: CGFloat var resultFrame: CGRect dx = frame.size.width * ratio dy = frame.size.height * ratio - resultFrame = CGRectInset(frame, dx, dy) - resultFrame = CGRectMake(round(resultFrame.origin.x), round(resultFrame.origin.y), round(resultFrame.size.width), round(resultFrame.size.height)) + resultFrame = frame.insetBy(dx: dx, dy: dy) + resultFrame = CGRect(x: round(resultFrame.origin.x), y: round(resultFrame.origin.y), width: round(resultFrame.size.width), height: round(resultFrame.size.height)) return resultFrame } - func sizeThatFitsInSize(boundingSize: CGSize, initialSize size: CGSize) -> CGSize { + func sizeThatFitsInSize(_ boundingSize: CGSize, initialSize size: CGSize) -> CGSize { // Compute the final size that fits in boundingSize in order to keep aspect ratio from initialSize. let fittingSize: CGSize let widthRatio: CGFloat @@ -249,24 +250,24 @@ public class AKMediaViewerManager : NSObject, UIGestureRecognizerDelegate { heightRatio = boundingSize.height / size.height if (widthRatio < heightRatio) { - fittingSize = CGSizeMake(boundingSize.width, floor(size.height * widthRatio)) + fittingSize = CGSize(width: boundingSize.width, height: floor(size.height * widthRatio)) } else { - fittingSize = CGSizeMake(floor(size.width * heightRatio), boundingSize.height) + fittingSize = CGSize(width: floor(size.width * heightRatio), height: boundingSize.height) } return fittingSize } - func focusViewControllerForView(mediaView: UIView) -> AKMediaViewerController? { + func focusViewControllerForView(_ mediaView: UIView) -> AKMediaViewerController? { let viewController: AKMediaViewerController let image: UIImage? var imageView: UIImageView? - let url: NSURL? + let url: URL? imageView = delegate?.mediaFocusManager?(self, imageViewForView: mediaView) - if (imageView == nil && mediaView.isKindOfClass(UIImageView)) { + if (imageView == nil && mediaView is UIImageView) { imageView = mediaView as? UIImageView } @@ -297,24 +298,24 @@ public class AKMediaViewerManager : NSObject, UIGestureRecognizerDelegate { if (isVideoURL(url!)) { viewController.showPlayerWithURL(url!) } else { - dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), { () -> Void in + DispatchQueue.global(qos: .default).async { self.loadImageFromURL(url!, onImageView: viewController.mainImageView) - viewController.mainImageView.hidden = false - }) + viewController.mainImageView.isHidden = false + } } return viewController } - func loadImageFromURL(url: NSURL, onImageView imageView: UIImageView) { - let data: NSData + func loadImageFromURL(_ url: URL, onImageView imageView: UIImageView) { + let data: Data do { - try data = NSData.init(contentsOfURL: url, options: NSDataReadingOptions.DataReadingMappedAlways) + try data = Data.init(contentsOf: url, options:.dataReadingMapped) var image: UIImage = UIImage.init(data: data)! image = decodedImageWithImage(image) - dispatch_async(dispatch_get_main_queue(), { () -> Void in + DispatchQueue.main.async(execute: { () -> Void in imageView.image = image }) } catch { @@ -322,23 +323,23 @@ public class AKMediaViewerManager : NSObject, UIGestureRecognizerDelegate { } } - func isVideoURL(url: NSURL) -> Bool { - let fileExtension: String = url.pathExtension!.lowercaseString + func isVideoURL(_ url: URL) -> Bool { + let fileExtension: String = url.pathExtension.lowercased() return (fileExtension == "mp4" || fileExtension == "mov") } // MARK: - Focus/Defocus // Start the focus animation on the specified view. The focusing gesture must have been installed on this view. - public func startFocusingView(mediaView: UIView) { + public func startFocusingView(_ mediaView: UIView) { let parentViewController: UIViewController let focusViewController: AKMediaViewerController? let center: CGPoint let imageView: UIImageView - let duration: NSTimeInterval + let duration: TimeInterval var finalImageFrame: CGRect? - var untransformedFinalImageFrame: CGRect = CGRectZero + var untransformedFinalImageFrame: CGRect = CGRect.zero focusViewController = focusViewControllerForView(mediaView)! @@ -357,14 +358,14 @@ public class AKMediaViewerManager : NSObject, UIGestureRecognizerDelegate { self.mediaView = mediaView parentViewController = (delegate?.parentViewControllerForMediaFocusManager(self))! - parentViewController.addChildViewController(focusViewController!) + parentViewController.addChild(focusViewController!) parentViewController.view.addSubview(focusViewController!.view) focusViewController!.view.frame = parentViewController.view.bounds - mediaView.hidden = true + mediaView.isHidden = true imageView = focusViewController!.mainImageView - center = (imageView.superview?.convertPoint(mediaView.center, fromView: mediaView.superview))! + center = (imageView.superview?.convert(mediaView.center, from: mediaView.superview))! imageView.center = center imageView.transform = mediaView.transform imageView.bounds = mediaView.bounds @@ -377,21 +378,21 @@ public class AKMediaViewerManager : NSObject, UIGestureRecognizerDelegate { finalImageFrame = parentViewController.view.bounds } - if(imageView.contentMode == UIViewContentMode.ScaleAspectFill) { + if(imageView.contentMode == UIView.ContentMode.scaleAspectFill) { let size: CGSize = sizeThatFitsInSize(finalImageFrame!.size, initialSize: imageView.image!.size) finalImageFrame!.size = size finalImageFrame!.origin.x = (focusViewController!.view.bounds.size.width - size.width) / 2 finalImageFrame!.origin.y = (focusViewController!.view.bounds.size.height - size.height) / 2 } - UIView .animateWithDuration(self.animationDuration) { () -> Void in + UIView .animate(withDuration: self.animationDuration) { () -> Void in focusViewController!.view.backgroundColor = self.backgroundColor focusViewController?.beginAppearanceTransition(true, animated: true) } duration = (elasticAnimation ? animationDuration * (1.0 - kAnimateElasticDurationRatio) : self.animationDuration) - UIView.animateWithDuration(self.animationDuration, + UIView.animate(withDuration: self.animationDuration, animations: { () -> Void in var frame: CGRect let initialFrame: CGRect @@ -406,7 +407,7 @@ public class AKMediaViewerManager : NSObject, UIGestureRecognizerDelegate { // Thus to recreate the right animation, the image frame is set back to its inital frame then to its final frame. // This very last frame operation recreates the right frame animation. initialTransform = imageView.transform - imageView.transform = CGAffineTransformIdentity + imageView.transform = CGAffineTransform.identity initialFrame = imageView.frame imageView.frame = frame focusViewController!.updateOrientationAnimated(false) @@ -417,26 +418,26 @@ public class AKMediaViewerManager : NSObject, UIGestureRecognizerDelegate { imageView.frame = initialFrame imageView.transform = initialTransform imageView.layer .removeAllAnimations() - imageView.transform = CGAffineTransformIdentity + imageView.transform = CGAffineTransform.identity imageView.frame = frame if (mediaView.layer.cornerRadius > 0) { self.animateCornerRadiusOfView(imageView, withDuration: duration, from: Float(mediaView.layer.cornerRadius), to: 0.0) } }, completion: { (finished: Bool) -> Void in - UIView.animateWithDuration(self.elasticAnimation ? self.animationDuration * (kAnimateElasticDurationRatio / 3.0) : 0.0, + UIView.animate(withDuration: self.elasticAnimation ? self.animationDuration * (kAnimateElasticDurationRatio / 3.0) : 0.0, animations: { () -> Void in var frame: CGRect = untransformedFinalImageFrame frame = (self.elasticAnimation ? self.rectInsetsForRect(frame, withRatio:kAnimateElasticSizeRatio * kAnimateElasticSecondMoveSizeRatio) : frame) imageView.frame = frame }, completion: { (finished: Bool) -> Void in - UIView.animateWithDuration(self.elasticAnimation ? self.animationDuration * (kAnimateElasticDurationRatio / 3.0) : 0.0, + UIView.animate(withDuration: self.elasticAnimation ? self.animationDuration * (kAnimateElasticDurationRatio / 3.0) : 0.0, animations: { () -> Void in var frame: CGRect = untransformedFinalImageFrame frame = (self.elasticAnimation ? self.rectInsetsForRect(frame, withRatio: -kAnimateElasticSizeRatio * kAnimateElasticThirdMoveSizeRatio) : frame) imageView.frame = frame }, completion: { (finished: Bool) -> Void in - UIView.animateWithDuration(self.elasticAnimation ? self.animationDuration * (kAnimateElasticDurationRatio / 3.0) : 0.0, + UIView.animate(withDuration: self.elasticAnimation ? self.animationDuration * (kAnimateElasticDurationRatio / 3.0) : 0.0, animations: { () -> Void in imageView.frame = untransformedFinalImageFrame }, completion: { (finished: Bool) -> Void in @@ -449,33 +450,33 @@ public class AKMediaViewerManager : NSObject, UIGestureRecognizerDelegate { }) } - func animateCornerRadiusOfView(view: UIView, withDuration duration: NSTimeInterval, from initialValue: Float, to finalValue: Float) { + func animateCornerRadiusOfView(_ view: UIView, withDuration duration: TimeInterval, from initialValue: Float, to finalValue: Float) { let animation: CABasicAnimation = CABasicAnimation.init(keyPath: "cornerRadius") - animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear) + animation.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.linear) animation.fromValue = initialValue animation.toValue = finalValue animation.duration = duration view.layer.cornerRadius = CGFloat(finalValue) - view.layer.addAnimation(animation, forKey: "cornerRadius") + view.layer.add(animation, forKey: "cornerRadius") } - func updateAnimatedView(view: UIView?, fromFrame initialFrame: CGRect?, toFrame finalFrame: CGRect) { + func updateAnimatedView(_ view: UIView?, fromFrame initialFrame: CGRect?, toFrame finalFrame: CGRect) { // On iOS8 previous animations are not replaced when a new one is defined with the same key. // Instead the new animation is added a number suffix on its key. // To prevent from having additive animations, previous animations are removed. // Note: We don't want to remove all animations as there might be some opacity animation that must remain. - view?.layer.removeAnimationForKey("bounds.size") - view?.layer.removeAnimationForKey("bounds.origin") - view?.layer.removeAnimationForKey("position") + view?.layer.removeAnimation(forKey: "bounds.size") + view?.layer.removeAnimation(forKey: "bounds.origin") + view?.layer.removeAnimation(forKey: "position") view?.frame = initialFrame! - view?.layer.removeAnimationForKey("bounds.size") - view?.layer.removeAnimationForKey("bounds.origin") - view?.layer.removeAnimationForKey("position") + view?.layer.removeAnimation(forKey: "bounds.size") + view?.layer.removeAnimation(forKey: "bounds.origin") + view?.layer.removeAnimation(forKey: "position") view?.frame = finalFrame } - func updateBoundsDuringAnimationWithElasticRatio(ratio: CGFloat) { - var initialFrame: CGRect? = CGRectZero + func updateBoundsDuringAnimationWithElasticRatio(_ ratio: CGFloat) { + var initialFrame: CGRect? = CGRect.zero var frame: CGRect = mediaView.bounds initialFrame = focusViewController!.playerView?.frame @@ -485,8 +486,8 @@ public class AKMediaViewerManager : NSObject, UIGestureRecognizerDelegate { } // Start the close animation on the current focused view. - public func endFocusing() { - let duration: NSTimeInterval + @objc public func endFocusing() { + let duration: TimeInterval let contentView: UIView if(isZooming && gestureDisabledDuringZooming) { @@ -497,11 +498,11 @@ public class AKMediaViewerManager : NSObject, UIGestureRecognizerDelegate { contentView = self.focusViewController!.mainImageView - UIView.animateWithDuration(self.animationDuration) { () -> Void in - self.focusViewController!.view.backgroundColor = UIColor.clearColor() + UIView.animate(withDuration: self.animationDuration) { () -> Void in + self.focusViewController!.view.backgroundColor = UIColor.clear } - UIView.animateWithDuration(self.animationDuration / 2) { () -> Void in + UIView.animate(withDuration: self.animationDuration / 2) { () -> Void in self.focusViewController!.beginAppearanceTransition(false, animated: true) } @@ -511,29 +512,29 @@ public class AKMediaViewerManager : NSObject, UIGestureRecognizerDelegate { animateCornerRadiusOfView(contentView, withDuration: duration, from: 0.0, to: Float(self.mediaView.layer.cornerRadius)) } - UIView.animateWithDuration(duration, + UIView.animate(withDuration: duration, animations: { () -> Void in self.delegate?.mediaFocusManagerWillDisappear?(self) - self.focusViewController!.contentView.transform = CGAffineTransformIdentity - contentView.center = contentView.superview!.convertPoint(self.mediaView.center, fromView: self.mediaView.superview) + self.focusViewController!.contentView.transform = CGAffineTransform.identity + contentView.center = contentView.superview!.convert(self.mediaView.center, from: self.mediaView.superview) contentView.transform = self.mediaView.transform self.updateBoundsDuringAnimationWithElasticRatio(kAnimateElasticSizeRatio) }, completion: { (finished: Bool) -> Void in - UIView.animateWithDuration(self.elasticAnimation ? self.animationDuration * (kAnimateElasticDurationRatio / 3.0) : 0.0, + UIView.animate(withDuration: self.elasticAnimation ? self.animationDuration * (kAnimateElasticDurationRatio / 3.0) : 0.0, animations: { () -> Void in self.updateBoundsDuringAnimationWithElasticRatio(-kAnimateElasticSizeRatio * kAnimateElasticSecondMoveSizeRatio) }, completion: { (finished: Bool) -> Void in - UIView.animateWithDuration(self.elasticAnimation ? self.animationDuration * (kAnimateElasticDurationRatio / 3.0) : 0.0, + UIView.animate(withDuration: self.elasticAnimation ? self.animationDuration * (kAnimateElasticDurationRatio / 3.0) : 0.0, animations: { () -> Void in self.updateBoundsDuringAnimationWithElasticRatio(kAnimateElasticSizeRatio * kAnimateElasticThirdMoveSizeRatio) }, completion: { (finished: Bool) -> Void in - UIView.animateWithDuration(self.elasticAnimation ? self.animationDuration * (kAnimateElasticDurationRatio / 3.0) : 0.0, + UIView.animate(withDuration: self.elasticAnimation ? self.animationDuration * (kAnimateElasticDurationRatio / 3.0) : 0.0, animations: { () -> Void in self.updateBoundsDuringAnimationWithElasticRatio(0.0) }, completion: { (finished: Bool) -> Void in - self.mediaView.hidden = false + self.mediaView.isHidden = false self.focusViewController!.view .removeFromSuperview() - self.focusViewController!.removeFromParentViewController() + self.focusViewController!.removeFromParent() self.focusViewController = nil self.delegate?.mediaFocusManagerDidDisappear?(self) }) @@ -545,22 +546,22 @@ public class AKMediaViewerManager : NSObject, UIGestureRecognizerDelegate { // MARK: - Gestures - func handlePinchFocusGesture(gesture: UIPinchGestureRecognizer) { - if (gesture.state == UIGestureRecognizerState.Began && !isZooming && gesture.scale > 1) { + @objc func handlePinchFocusGesture(_ gesture: UIPinchGestureRecognizer) { + if (gesture.state == UIGestureRecognizer.State.began && !isZooming && gesture.scale > 1) { startFocusingView(gesture.view!) } } - func handleFocusGesture(gesture: UIGestureRecognizer) { + @objc func handleFocusGesture(_ gesture: UIGestureRecognizer) { startFocusingView(gesture.view!) } - func handleDefocusGesture(gesture: UIGestureRecognizer) { + @objc func handleDefocusGesture(_ gesture: UIGestureRecognizer) { endFocusing() } - public func gestureRecognizerShouldBegin(gestureRecognizer: UIGestureRecognizer) -> Bool { - if (gestureRecognizer.isKindOfClass(UIPinchGestureRecognizer)) { + public func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool { + if (gestureRecognizer is UIPinchGestureRecognizer) { return focusOnPinch } return true @@ -570,48 +571,48 @@ public class AKMediaViewerManager : NSObject, UIGestureRecognizerDelegate { func installSwipeGestureOnFocusView() { var swipeGesture: UISwipeGestureRecognizer = UISwipeGestureRecognizer.init(target: self, action: #selector(AKMediaViewerManager.handleDefocusBySwipeGesture(_:))) - swipeGesture.direction = UISwipeGestureRecognizerDirection.Up + swipeGesture.direction = UISwipeGestureRecognizer.Direction.up focusViewController!.view.addGestureRecognizer(swipeGesture) swipeGesture = UISwipeGestureRecognizer.init(target: self, action: #selector(AKMediaViewerManager.handleDefocusBySwipeGesture(_:))) - swipeGesture.direction = UISwipeGestureRecognizerDirection.Down + swipeGesture.direction = UISwipeGestureRecognizer.Direction.down focusViewController!.view.addGestureRecognizer(swipeGesture) - focusViewController!.view.userInteractionEnabled = true + focusViewController!.view.isUserInteractionEnabled = true } - func handleDefocusBySwipeGesture(gesture: UISwipeGestureRecognizer) { + @objc func handleDefocusBySwipeGesture(_ gesture: UISwipeGestureRecognizer) { let contentView: UIView let offset: CGFloat - let duration: NSTimeInterval = self.animationDuration + let duration: TimeInterval = self.animationDuration focusViewController!.defocusWillStart() - offset = (gesture.direction == UISwipeGestureRecognizerDirection.Up ? -kSwipeOffset : kSwipeOffset) + offset = (gesture.direction == UISwipeGestureRecognizer.Direction.up ? -kSwipeOffset : kSwipeOffset) contentView = focusViewController!.mainImageView - UIView.animateWithDuration(duration) { - self.focusViewController!.view.backgroundColor = UIColor.clearColor() + UIView.animate(withDuration: duration) { + self.focusViewController!.view.backgroundColor = UIColor.clear } - UIView.animateWithDuration(duration / 2) { + UIView.animate(withDuration: duration / 2) { self.focusViewController!.beginAppearanceTransition(false, animated: true) } - UIView.animateWithDuration(0.4 * duration, + UIView.animate(withDuration: 0.4 * duration, animations: { self.delegate?.mediaFocusManagerWillDisappear?(self) - self.focusViewController!.contentView.transform = CGAffineTransformIdentity + self.focusViewController!.contentView.transform = CGAffineTransform.identity - contentView.center = CGPointMake(self.focusViewController!.view.center.x, self.focusViewController!.view.center.y + offset) + contentView.center = CGPoint(x: self.focusViewController!.view.center.x, y: self.focusViewController!.view.center.y + offset) }, completion: { (finished: Bool) -> Void in - UIView.animateWithDuration(0.6 * duration, + UIView.animate(withDuration: 0.6 * duration, animations: { - contentView.center = contentView.superview!.convertPoint(self.mediaView.center, fromView: self.mediaView.superview) + contentView.center = contentView.superview!.convert(self.mediaView.center, from: self.mediaView.superview) contentView.transform = self.mediaView.transform self.updateBoundsDuringAnimationWithElasticRatio(0) }, completion: { (finished: Bool) -> Void in - self.mediaView.hidden = false + self.mediaView.isHidden = false self.focusViewController!.view.removeFromSuperview() - self.focusViewController!.removeFromParentViewController() + self.focusViewController!.removeFromParent() self.focusViewController = nil self.delegate?.mediaFocusManagerDidDisappear?(self) }) @@ -621,8 +622,8 @@ public class AKMediaViewerManager : NSObject, UIGestureRecognizerDelegate { // MARK: - Customization // Set minimal customization to default "Done" button. (Text and Color) - public func setDefaultDoneButtonText(text: String, withColor color: UIColor) { - (topAccessoryController as! AKMediaFocusBasicToolbarController).doneButton.setTitle(text, forState: UIControlState.Normal) - (topAccessoryController as! AKMediaFocusBasicToolbarController).doneButton.setTitleColor(color, forState: UIControlState.Normal) + public func setDefaultDoneButtonText(_ text: String, withColor color: UIColor) { + (topAccessoryController as! AKMediaFocusBasicToolbarController).doneButton.setTitle(text, for: UIControl.State()) + (topAccessoryController as! AKMediaFocusBasicToolbarController).doneButton.setTitleColor(color, for: UIControl.State()) } -} \ No newline at end of file +} diff --git a/AKMediaViewer/AKTransparentView.swift b/AKMediaViewer/AKTransparentView.swift index 64438c3..cf1a0d7 100644 --- a/AKMediaViewer/AKTransparentView.swift +++ b/AKMediaViewer/AKTransparentView.swift @@ -11,12 +11,12 @@ import UIKit public class AKTransparentView : UIView { - override public func hitTest(point: CGPoint, withEvent event: UIEvent?) -> UIView? { - var view: UIView? = super.hitTest(point, withEvent: event) + override public func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? { + var view: UIView? = super.hitTest(point, with: event) if(view == self) { view = nil } return view } -} \ No newline at end of file +} diff --git a/AKMediaViewer/AKVideoBehavior.swift b/AKMediaViewer/AKVideoBehavior.swift index 950aff1..6e535b6 100644 --- a/AKMediaViewer/AKVideoBehavior.swift +++ b/AKMediaViewer/AKVideoBehavior.swift @@ -13,18 +13,18 @@ let kPlayIconTag: NSInteger = 50001 public class AKVideoBehavior : NSObject { - public func addVideoIconToView(view: UIView, image: UIImage?) { + public func addVideoIconToView(_ view: UIView, image: UIImage?) { var videoIcon: UIImage? = image var imageView: UIImageView? - if((videoIcon == nil) || CGSizeEqualToSize(image!.size, CGSizeZero)) { + if((videoIcon == nil) || image!.size.equalTo(CGSize.zero)) { videoIcon = UIImage.init(named: "icon_big_play") } imageView = UIImageView.init(image: videoIcon) imageView!.tag = kPlayIconTag - imageView!.contentMode = UIViewContentMode.Center - imageView!.autoresizingMask = [UIViewAutoresizing.FlexibleWidth, UIViewAutoresizing.FlexibleHeight] + imageView!.contentMode = UIView.ContentMode.center + imageView!.autoresizingMask = [UIView.AutoresizingMask.flexibleWidth, UIView.AutoresizingMask.flexibleHeight] imageView!.frame = view.bounds view.addSubview(imageView!) } diff --git a/AKMediaViewer/AKVideoControlView.swift b/AKMediaViewer/AKVideoControlView.swift index 6f28181..f035d38 100644 --- a/AKMediaViewer/AKVideoControlView.swift +++ b/AKMediaViewer/AKVideoControlView.swift @@ -20,7 +20,7 @@ public class AKVideoControlView : UIView { override public func awakeFromNib() { super.awakeFromNib() - scrubbing.addObserver(self, forKeyPath: "player", options: NSKeyValueObservingOptions.New, context: nil) + scrubbing.addObserver(self, forKeyPath: "player", options: NSKeyValueObservingOptions.new, context: nil) } deinit { @@ -29,27 +29,26 @@ public class AKVideoControlView : UIView { } class func videoControlView() -> AKVideoControlView { - let objects: NSArray = NSBundle.mainBundle().loadNibNamed("AKVideoControlView", owner: nil, options: nil) + let objects: NSArray = Bundle.main.loadNibNamed("AKVideoControlView", owner: nil, options: nil)! as NSArray return objects.firstObject as! AKVideoControlView } // MARK: - IBActions - @IBAction func switchTimeLabel(sender: AnyObject) { - self.remainingTimeLabel.hidden = !self.remainingTimeLabel.hidden - self.durationLabel.hidden = !self.remainingTimeLabel.hidden + @IBAction func switchTimeLabel(_ sender: AnyObject) { + self.remainingTimeLabel.isHidden = !self.remainingTimeLabel.isHidden + self.durationLabel.isHidden = !self.remainingTimeLabel.isHidden } // MARK: - KVO - - override public func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer) { + public override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { if (keyPath == "player") { if(scrubbing.player != nil) { - scrubbing.player.addObserver(self, forKeyPath: "rate", options: NSKeyValueObservingOptions.New, context: nil) + scrubbing.player.addObserver(self, forKeyPath: "rate", options: NSKeyValueObservingOptions.new, context: nil) } } else { let player = object as! AVPlayer - playPauseButton.selected = (player.rate != 0) + playPauseButton.isSelected = (player.rate != 0) } } -} \ No newline at end of file +}