MWPhotoBrowser.m 51 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433
  1. //
  2. // MWPhotoBrowser.m
  3. // MWPhotoBrowser
  4. //
  5. // Created by Michael Waterfall on 14/10/2010.
  6. // Copyright 2010 d3i. All rights reserved.
  7. //
  8. #import <QuartzCore/QuartzCore.h>
  9. #import "MWCommon.h"
  10. #import "MWPhotoBrowser.h"
  11. #import "MWPhotoBrowserPrivate.h"
  12. #import "UIImage+MWPhotoBrowser.h"
  13. #import "NCBridgeSwift.h"
  14. #define PADDING 10
  15. static void * MWVideoPlayerObservation = &MWVideoPlayerObservation;
  16. @implementation MWPhotoBrowser
  17. #pragma mark - Init
  18. - (id)init {
  19. if ((self = [super init])) {
  20. [self _initialisation];
  21. }
  22. return self;
  23. }
  24. - (id)initWithDelegate:(id <MWPhotoBrowserDelegate>)delegate {
  25. if ((self = [self init])) {
  26. _delegate = delegate;
  27. }
  28. return self;
  29. }
  30. - (id)initWithPhotos:(NSArray *)photosArray {
  31. if ((self = [self init])) {
  32. _fixedPhotosArray = photosArray;
  33. }
  34. return self;
  35. }
  36. - (id)initWithCoder:(NSCoder *)decoder {
  37. if ((self = [super initWithCoder:decoder])) {
  38. [self _initialisation];
  39. }
  40. return self;
  41. }
  42. - (void)_initialisation {
  43. // Defaults
  44. NSNumber *isVCBasedStatusBarAppearanceNum = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"UIViewControllerBasedStatusBarAppearance"];
  45. if (isVCBasedStatusBarAppearanceNum) {
  46. _isVCBasedStatusBarAppearance = isVCBasedStatusBarAppearanceNum.boolValue;
  47. } else {
  48. _isVCBasedStatusBarAppearance = YES; // default
  49. }
  50. self.hidesBottomBarWhenPushed = YES;
  51. _hasBelongedToViewController = NO;
  52. _photoCount = NSNotFound;
  53. _previousLayoutBounds = CGRectZero;
  54. _currentPageIndex = 0;
  55. _previousPageIndex = NSUIntegerMax;
  56. _displayActionButton = YES;
  57. _displayShareButton = YES;
  58. _displayDeleteButton = YES;
  59. _displayNavArrows = NO;
  60. _zoomPhotosToFill = YES;
  61. _performingLayout = NO; // Reset on view did appear
  62. _rotating = NO;
  63. _viewIsActive = NO;
  64. _enableSwipeToDismiss = YES;
  65. _delayToHideElements = 5;
  66. _visiblePages = [[NSMutableSet alloc] init];
  67. _recycledPages = [[NSMutableSet alloc] init];
  68. _photos = [[NSMutableArray alloc] init];
  69. _thumbPhotos = [[NSMutableArray alloc] init];
  70. _didSavePreviousStateOfNavBar = NO;
  71. self.automaticallyAdjustsScrollViewInsets = NO;
  72. // Listen for MWPhoto notifications
  73. [[NSNotificationCenter defaultCenter] addObserver:self
  74. selector:@selector(handleMWPhotoLoadingDidEndNotification:)
  75. name:MWPHOTO_LOADING_DID_END_NOTIFICATION
  76. object:nil];
  77. }
  78. - (void)dealloc {
  79. [self clearCurrentVideo];
  80. _pagingScrollView.delegate = nil;
  81. [[NSNotificationCenter defaultCenter] removeObserver:self];
  82. [self releaseAllUnderlyingPhotos:NO];
  83. }
  84. - (void)releaseAllUnderlyingPhotos:(BOOL)preserveCurrent {
  85. // Create a copy in case this array is modified while we are looping through
  86. // Release photos
  87. NSArray *copy = [_photos copy];
  88. for (id p in copy) {
  89. if (p != [NSNull null]) {
  90. if (preserveCurrent && p == [self photoAtIndex:self.currentIndex]) {
  91. continue; // skip current
  92. }
  93. [p unloadUnderlyingImage];
  94. }
  95. }
  96. // Release thumbs
  97. copy = [_thumbPhotos copy];
  98. for (id p in copy) {
  99. if (p != [NSNull null]) {
  100. [p unloadUnderlyingImage];
  101. }
  102. }
  103. }
  104. - (void)didReceiveMemoryWarning {
  105. // Release any cached data, images, etc that aren't in use.
  106. [self releaseAllUnderlyingPhotos:YES];
  107. [_recycledPages removeAllObjects];
  108. // Releases the view if it doesn't have a superview.
  109. [super didReceiveMemoryWarning];
  110. }
  111. #pragma mark - View Loading
  112. // Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
  113. - (void)viewDidLoad {
  114. // View
  115. self.view.backgroundColor = [UIColor whiteColor];
  116. self.view.clipsToBounds = YES;
  117. // Setup paging scrolling view
  118. CGRect pagingScrollViewFrame = [self frameForPagingScrollView];
  119. _pagingScrollView = [[UIScrollView alloc] initWithFrame:pagingScrollViewFrame];
  120. _pagingScrollView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
  121. _pagingScrollView.pagingEnabled = YES;
  122. _pagingScrollView.delegate = self;
  123. _pagingScrollView.showsHorizontalScrollIndicator = NO;
  124. _pagingScrollView.showsVerticalScrollIndicator = NO;
  125. _pagingScrollView.backgroundColor = [UIColor whiteColor];
  126. _pagingScrollView.contentSize = [self contentSizeForPagingScrollView];
  127. [self.view addSubview:_pagingScrollView];
  128. // Toolbar
  129. _toolbar = [[UIToolbar alloc] initWithFrame:[self frameForToolbarAtOrientation:[[UIApplication sharedApplication] statusBarOrientation]]];
  130. _toolbar.tintColor = [NCBrandColor sharedInstance].brandElement;
  131. _toolbar.barTintColor = [NCBrandColor sharedInstance].tabBar;
  132. [_toolbar setBackgroundImage:nil forToolbarPosition:UIToolbarPositionAny barMetrics:UIBarMetricsDefault];
  133. [_toolbar setBackgroundImage:nil forToolbarPosition:UIToolbarPositionAny barMetrics:UIBarMetricsCompact];
  134. _toolbar.barStyle = UIBarStyleDefault; //TWS
  135. _toolbar.autoresizingMask = UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleWidth;
  136. [_toolbar setTranslucent:NO];
  137. // Toolbar Items
  138. if (self.displayNavArrows) {
  139. NSString *arrowPathFormat = @"UIBarButtonItemArrow%@";
  140. UIImage *previousButtonImage = [UIImage imageForResourcePath:[NSString stringWithFormat:arrowPathFormat, @"Left"] ofType:@"png" inBundle:[NSBundle bundleForClass:[self class]]];
  141. UIImage *nextButtonImage = [UIImage imageForResourcePath:[NSString stringWithFormat:arrowPathFormat, @"Right"] ofType:@"png" inBundle:[NSBundle bundleForClass:[self class]]];
  142. _previousButton = [[UIBarButtonItem alloc] initWithImage:previousButtonImage style:UIBarButtonItemStylePlain target:self action:@selector(gotoPreviousPage)];
  143. _nextButton = [[UIBarButtonItem alloc] initWithImage:nextButtonImage style:UIBarButtonItemStylePlain target:self action:@selector(gotoNextPage)];
  144. }
  145. //TWS
  146. if (self.displayDeleteButton) {
  147. _deleteButton = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"deletePhotoBrowser"] style:UIBarButtonItemStylePlain target:self action:@selector(deleteButtonPressed:)];
  148. }
  149. if (self.displayActionButton) {
  150. _actionButton = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"openFile"] style:UIBarButtonItemStylePlain target:self action:@selector(actionButtonPressed:)];
  151. }
  152. if (self.displayShareButton) {
  153. _shareButton = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"sharePhotoBrowser"] style:UIBarButtonItemStylePlain target:self action:@selector(shareButtonPressed:)];
  154. }
  155. // Update
  156. [self reloadData];
  157. // Swipe to dismiss
  158. if (_enableSwipeToDismiss) {
  159. UISwipeGestureRecognizer *swipeGesture = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(doneButtonPressed:)];
  160. swipeGesture.direction = UISwipeGestureRecognizerDirectionDown | UISwipeGestureRecognizerDirectionUp;
  161. [self.view addGestureRecognizer:swipeGesture];
  162. }
  163. // Super
  164. [super viewDidLoad];
  165. }
  166. - (void)performLayout {
  167. // Setup
  168. _performingLayout = YES;
  169. NSUInteger numberOfPhotos = [self numberOfPhotos];
  170. // Setup pages
  171. [_visiblePages removeAllObjects];
  172. [_recycledPages removeAllObjects];
  173. // Navigation buttons
  174. if ([self.navigationController.viewControllers objectAtIndex:0] == self) {
  175. // We're first on stack so show done button
  176. _doneButton = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"Done", nil) style:UIBarButtonItemStylePlain target:self action:@selector(doneButtonPressed:)];
  177. // Set appearance
  178. [_doneButton setBackgroundImage:nil forState:UIControlStateNormal barMetrics:UIBarMetricsDefault];
  179. [_doneButton setBackgroundImage:nil forState:UIControlStateNormal barMetrics:UIBarMetricsCompact];
  180. [_doneButton setBackgroundImage:nil forState:UIControlStateHighlighted barMetrics:UIBarMetricsDefault];
  181. [_doneButton setBackgroundImage:nil forState:UIControlStateHighlighted barMetrics:UIBarMetricsCompact];
  182. [_doneButton setTitleTextAttributes:[NSDictionary dictionary] forState:UIControlStateNormal];
  183. [_doneButton setTitleTextAttributes:[NSDictionary dictionary] forState:UIControlStateHighlighted];
  184. self.navigationItem.rightBarButtonItem = _doneButton;
  185. }
  186. // color
  187. self.navigationController.navigationBar.barTintColor = [NCBrandColor sharedInstance].brand;
  188. self.navigationController.navigationBar.tintColor = [NCBrandColor sharedInstance].brandText;
  189. [self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName : [NCBrandColor sharedInstance].brandText}];
  190. self.navigationController.navigationBar.translucent = false;
  191. [self setExtendedLayoutIncludesOpaqueBars:YES];
  192. // Toolbar items
  193. BOOL hasItems = NO;
  194. UIBarButtonItem *fixedSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:self action:nil];
  195. fixedSpace.width = 32; // To balance action button
  196. UIBarButtonItem *fixedSpaceMini = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:self action:nil];
  197. fixedSpaceMini.width = 25; // To balance action button
  198. UIBarButtonItem *flexSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil];
  199. NSMutableArray *items = [[NSMutableArray alloc] init];
  200. // Middle - Nav
  201. if (_previousButton && _nextButton && numberOfPhotos > 1) {
  202. hasItems = YES;
  203. [items addObject:_previousButton];
  204. [items addObject:fixedSpace];
  205. [items addObject:fixedSpace];
  206. [items addObject:_nextButton];
  207. [items addObject:flexSpace];
  208. } else {
  209. [items addObject:flexSpace];
  210. }
  211. if (_deleteButton) {
  212. [items addObject:_deleteButton];
  213. [items addObject:fixedSpaceMini];
  214. }
  215. if (_shareButton) {
  216. [items addObject:_shareButton];
  217. [items addObject:fixedSpaceMini];
  218. }
  219. if (_actionButton) {
  220. [items addObject:_actionButton];
  221. }
  222. // Toolbar visibility
  223. [_toolbar setItems:items];
  224. BOOL hideToolbar = YES;
  225. for (UIBarButtonItem* item in _toolbar.items) {
  226. if (item != fixedSpace && item != flexSpace) {
  227. hideToolbar = NO;
  228. break;
  229. }
  230. }
  231. if (hideToolbar) {
  232. [_toolbar removeFromSuperview];
  233. } else {
  234. [self.view addSubview:_toolbar];
  235. }
  236. // Update nav
  237. [self updateNavigation];
  238. // Content offset
  239. _pagingScrollView.contentOffset = [self contentOffsetForPageAtIndex:_currentPageIndex];
  240. [self tilePages];
  241. _performingLayout = NO;
  242. }
  243. // Release any retained subviews of the main view.
  244. - (void)viewDidUnload {
  245. _currentPageIndex = 0;
  246. _pagingScrollView = nil;
  247. _visiblePages = nil;
  248. _recycledPages = nil;
  249. _toolbar = nil;
  250. _previousButton = nil;
  251. _nextButton = nil;
  252. _progressHUD = nil;
  253. [super viewDidUnload];
  254. }
  255. - (BOOL)presentingViewControllerPrefersStatusBarHidden {
  256. UIViewController *presenting = self.presentingViewController;
  257. if (presenting) {
  258. if ([presenting isKindOfClass:[UINavigationController class]]) {
  259. presenting = [(UINavigationController *)presenting topViewController];
  260. }
  261. } else {
  262. // We're in a navigation controller so get previous one!
  263. if (self.navigationController && self.navigationController.viewControllers.count > 1) {
  264. presenting = [self.navigationController.viewControllers objectAtIndex:self.navigationController.viewControllers.count-2];
  265. }
  266. }
  267. if (presenting) {
  268. return [presenting prefersStatusBarHidden];
  269. } else {
  270. return NO;
  271. }
  272. }
  273. #pragma mark - Appearance
  274. - (void)viewWillAppear:(BOOL)animated {
  275. // Super
  276. [super viewWillAppear:animated];
  277. // Nav Bar Appearance iPAD
  278. if (self.traitCollection.horizontalSizeClass != UIUserInterfaceSizeClassCompact) {
  279. // ----- TWS ----- //
  280. self.navigationItem.hidesBackButton = YES;
  281. self.navigationController.topViewController.navigationItem.leftBarButtonItem = self.splitViewController.displayModeButtonItem;
  282. }
  283. // Update UI
  284. [self hideControlsAfterDelay];
  285. // If rotation occured while we're presenting a modal
  286. // and the index changed, make sure we show the right one now
  287. if (_currentPageIndex != _pageIndexBeforeRotation) {
  288. [self jumpToPageAtIndex:_pageIndexBeforeRotation animated:NO];
  289. }
  290. // Layaout
  291. [self.view setNeedsLayout];
  292. }
  293. - (void)viewDidAppear:(BOOL)animated {
  294. [super viewDidAppear:animated];
  295. _viewIsActive = YES;
  296. // Autoplay if first is video
  297. if (!_viewHasAppearedInitially) {
  298. if (_autoPlayOnAppear) {
  299. MWPhoto *photo = [self photoAtIndex:_currentPageIndex];
  300. if ([photo respondsToSelector:@selector(isVideo)] && photo.isVideo) {
  301. [self playVideoAtIndex:_currentPageIndex];
  302. }
  303. }
  304. }
  305. _viewHasAppearedInitially = YES;
  306. }
  307. - (void)viewWillDisappear:(BOOL)animated {
  308. // Detect if rotation occurs while we're presenting a modal
  309. _pageIndexBeforeRotation = _currentPageIndex;
  310. // Check that we're being popped for good
  311. if ([self.navigationController.viewControllers objectAtIndex:0] != self &&
  312. ![self.navigationController.viewControllers containsObject:self]) {
  313. // State
  314. _viewIsActive = NO;
  315. [self clearCurrentVideo]; // Clear current playing video
  316. }
  317. // Controls
  318. [self.navigationController.navigationBar.layer removeAllAnimations]; // Stop all animations on nav bar
  319. [NSObject cancelPreviousPerformRequestsWithTarget:self]; // Cancel any pending toggles from taps
  320. [self setControlsHidden:NO animated:NO permanent:YES];
  321. // Super
  322. [super viewWillDisappear:animated];
  323. }
  324. - (void)willMoveToParentViewController:(UIViewController *)parent {
  325. if (parent && _hasBelongedToViewController) {
  326. [NSException raise:@"MWPhotoBrowser Instance Reuse" format:@"MWPhotoBrowser instances cannot be reused."];
  327. }
  328. }
  329. - (void)didMoveToParentViewController:(UIViewController *)parent {
  330. if (!parent) _hasBelongedToViewController = YES;
  331. }
  332. #pragma mark - Layout
  333. - (void)viewWillLayoutSubviews {
  334. [super viewWillLayoutSubviews];
  335. [self layoutVisiblePages];
  336. }
  337. - (void)layoutVisiblePages {
  338. // Flag
  339. _performingLayout = YES;
  340. // Toolbar
  341. _toolbar.frame = [self frameForToolbarAtOrientation:[[UIApplication sharedApplication] statusBarOrientation]];
  342. // Remember index
  343. NSUInteger indexPriorToLayout = _currentPageIndex;
  344. // Get paging scroll view frame to determine if anything needs changing
  345. CGRect pagingScrollViewFrame = [self frameForPagingScrollView];
  346. // Frame needs changing
  347. if (!_skipNextPagingScrollViewPositioning) {
  348. _pagingScrollView.frame = pagingScrollViewFrame;
  349. }
  350. _skipNextPagingScrollViewPositioning = NO;
  351. // Recalculate contentSize based on current orientation
  352. _pagingScrollView.contentSize = [self contentSizeForPagingScrollView];
  353. // Adjust frames and configuration of each visible page
  354. for (MWZoomingScrollView *page in _visiblePages) {
  355. NSUInteger index = page.index;
  356. page.frame = [self frameForPageAtIndex:index];
  357. if (page.captionView) {
  358. page.captionView.frame = [self frameForCaptionView:page.captionView atIndex:index];
  359. }
  360. if (page.selectedButton) {
  361. page.selectedButton.frame = [self frameForSelectedButton:page.selectedButton atIndex:index];
  362. }
  363. if (page.playButton) {
  364. page.playButton.frame = [self frameForPlayButton:page.playButton atIndex:index];
  365. }
  366. // Adjust scales if bounds has changed since last time
  367. if (!CGRectEqualToRect(_previousLayoutBounds, self.view.bounds)) {
  368. // Update zooms for new bounds
  369. [page setMaxMinZoomScalesForCurrentBounds];
  370. _previousLayoutBounds = self.view.bounds;
  371. }
  372. }
  373. // Adjust video loading indicator if it's visible
  374. [self positionVideoLoadingIndicator];
  375. // Adjust contentOffset to preserve page location based on values collected prior to location
  376. _pagingScrollView.contentOffset = [self contentOffsetForPageAtIndex:indexPriorToLayout];
  377. [self didStartViewingPageAtIndex:_currentPageIndex]; // initial
  378. // Reset
  379. _currentPageIndex = indexPriorToLayout;
  380. _performingLayout = NO;
  381. }
  382. #pragma mark - Rotation
  383. - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation {
  384. return YES;
  385. }
  386. #if __IPHONE_OS_VERSION_MAX_ALLOWED < 90000
  387. - (NSUInteger)supportedInterfaceOrientations
  388. #else
  389. - (UIInterfaceOrientationMask)supportedInterfaceOrientations
  390. #endif
  391. {
  392. return UIInterfaceOrientationMaskPortrait;
  393. }
  394. - (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration {
  395. // Remember page index before rotation
  396. _pageIndexBeforeRotation = _currentPageIndex;
  397. _rotating = YES;
  398. // In iOS 7 the nav bar gets shown after rotation, but might as well do this for everything!
  399. if ([self areControlsHidden]) {
  400. // Force hidden
  401. self.navigationController.navigationBarHidden = YES;
  402. }
  403. }
  404. - (void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration {
  405. // Perform layout
  406. _currentPageIndex = _pageIndexBeforeRotation;
  407. // Delay control holding
  408. [self hideControlsAfterDelay];
  409. // Layout
  410. [self layoutVisiblePages];
  411. }
  412. - (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
  413. _rotating = NO;
  414. // Ensure nav bar isn't re-displayed
  415. if ([self areControlsHidden]) {
  416. self.navigationController.navigationBarHidden = NO;
  417. self.navigationController.navigationBar.alpha = 0;
  418. }
  419. }
  420. #pragma mark - Data
  421. - (NSUInteger)currentIndex {
  422. return _currentPageIndex;
  423. }
  424. - (void)reloadData {
  425. // Reset
  426. _photoCount = NSNotFound;
  427. // Get data
  428. NSUInteger numberOfPhotos = [self numberOfPhotos];
  429. [self releaseAllUnderlyingPhotos:YES];
  430. [_photos removeAllObjects];
  431. [_thumbPhotos removeAllObjects];
  432. for (int i = 0; i < numberOfPhotos; i++) {
  433. [_photos addObject:[NSNull null]];
  434. [_thumbPhotos addObject:[NSNull null]];
  435. }
  436. // Update current page index
  437. if (numberOfPhotos > 0) {
  438. _currentPageIndex = MAX(0, MIN(_currentPageIndex, numberOfPhotos - 1));
  439. } else {
  440. _currentPageIndex = 0;
  441. }
  442. // Update layout
  443. if ([self isViewLoaded]) {
  444. while (_pagingScrollView.subviews.count) {
  445. [[_pagingScrollView.subviews lastObject] removeFromSuperview];
  446. }
  447. [self performLayout];
  448. [self.view setNeedsLayout];
  449. }
  450. }
  451. - (NSUInteger)numberOfPhotos {
  452. if (_photoCount == NSNotFound) {
  453. if ([_delegate respondsToSelector:@selector(numberOfPhotosInPhotoBrowser:)]) {
  454. _photoCount = [_delegate numberOfPhotosInPhotoBrowser:self];
  455. } else if (_fixedPhotosArray) {
  456. _photoCount = _fixedPhotosArray.count;
  457. }
  458. }
  459. if (_photoCount == NSNotFound) _photoCount = 0;
  460. return _photoCount;
  461. }
  462. - (id<MWPhoto>)photoAtIndex:(NSUInteger)index {
  463. id <MWPhoto> photo = nil;
  464. if (index < _photos.count) {
  465. if ([_photos objectAtIndex:index] == [NSNull null]) {
  466. if ([_delegate respondsToSelector:@selector(photoBrowser:photoAtIndex:)]) {
  467. photo = [_delegate photoBrowser:self photoAtIndex:index];
  468. } else if (_fixedPhotosArray && index < _fixedPhotosArray.count) {
  469. photo = [_fixedPhotosArray objectAtIndex:index];
  470. }
  471. if (photo) [_photos replaceObjectAtIndex:index withObject:photo];
  472. } else {
  473. photo = [_photos objectAtIndex:index];
  474. }
  475. }
  476. return photo;
  477. }
  478. - (MWCaptionView *)captionViewForPhotoAtIndex:(NSUInteger)index {
  479. MWCaptionView *captionView = nil;
  480. if ([_delegate respondsToSelector:@selector(photoBrowser:captionViewForPhotoAtIndex:)]) {
  481. captionView = [_delegate photoBrowser:self captionViewForPhotoAtIndex:index];
  482. } else {
  483. id <MWPhoto> photo = [self photoAtIndex:index];
  484. if ([photo respondsToSelector:@selector(caption)]) {
  485. if ([photo caption]) captionView = [[MWCaptionView alloc] initWithPhoto:photo];
  486. }
  487. }
  488. captionView.alpha = [self areControlsHidden] ? 0 : 1; // Initial alpha
  489. return captionView;
  490. }
  491. - (BOOL)photoIsSelectedAtIndex:(NSUInteger)index {
  492. BOOL value = NO;
  493. if (_displaySelectionButtons) {
  494. if ([self.delegate respondsToSelector:@selector(photoBrowser:isPhotoSelectedAtIndex:)]) {
  495. value = [self.delegate photoBrowser:self isPhotoSelectedAtIndex:index];
  496. }
  497. }
  498. return value;
  499. }
  500. - (void)setPhotoSelected:(BOOL)selected atIndex:(NSUInteger)index {
  501. if (_displaySelectionButtons) {
  502. if ([self.delegate respondsToSelector:@selector(photoBrowser:photoAtIndex:selectedChanged:)]) {
  503. [self.delegate photoBrowser:self photoAtIndex:index selectedChanged:selected];
  504. }
  505. }
  506. }
  507. - (UIImage *)imageForPhoto:(id<MWPhoto>)photo {
  508. if (photo) {
  509. // Get image or obtain in background
  510. if ([photo underlyingImage]) {
  511. return [photo underlyingImage];
  512. } else {
  513. [photo loadUnderlyingImageAndNotify];
  514. }
  515. }
  516. return nil;
  517. }
  518. - (void)loadAdjacentPhotosIfNecessary:(id<MWPhoto>)photo
  519. {
  520. MWZoomingScrollView *page = [self pageDisplayingPhoto:photo];
  521. if (page) {
  522. // If page is current page then initiate loading of previous and next pages
  523. NSUInteger pageIndex = page.index;
  524. if (_currentPageIndex == pageIndex) {
  525. if (pageIndex > 0) {
  526. // Preload index - 1
  527. id <MWPhoto> photo = [self photoAtIndex:pageIndex-1];
  528. if (![photo underlyingImage]) {
  529. [photo loadUnderlyingImageAndNotify];
  530. MWLog(@"Pre-loading image at index %lu", (unsigned long)pageIndex-1);
  531. }
  532. }
  533. if (pageIndex < [self numberOfPhotos] - 1) {
  534. // Preload index + 1
  535. id <MWPhoto> photo = [self photoAtIndex:pageIndex+1];
  536. if (![photo underlyingImage]) {
  537. [photo loadUnderlyingImageAndNotify];
  538. MWLog(@"Pre-loading image at index %lu", (unsigned long)pageIndex+1);
  539. }
  540. }
  541. }
  542. }
  543. }
  544. #pragma mark - MWPhoto Loading Notification
  545. - (void)handleMWPhotoLoadingDidEndNotification:(NSNotification *)notification {
  546. id <MWPhoto> photo = [notification object];
  547. MWZoomingScrollView *page = [self pageDisplayingPhoto:photo];
  548. if (page) {
  549. if ([photo underlyingImage]) {
  550. // Successful load
  551. [page displayImage];
  552. [self loadAdjacentPhotosIfNecessary:photo];
  553. } else {
  554. // Failed to load
  555. [page displayImageFailure];
  556. }
  557. // Update nav
  558. [self updateNavigation];
  559. }
  560. }
  561. #pragma mark - Paging
  562. - (void)tilePages {
  563. // Calculate which pages should be visible
  564. // Ignore padding as paging bounces encroach on that
  565. // and lead to false page loads
  566. CGRect visibleBounds = _pagingScrollView.bounds;
  567. NSInteger iFirstIndex = (NSInteger)floorf((CGRectGetMinX(visibleBounds)+PADDING*2) / CGRectGetWidth(visibleBounds));
  568. NSInteger iLastIndex = (NSInteger)floorf((CGRectGetMaxX(visibleBounds)-PADDING*2-1) / CGRectGetWidth(visibleBounds));
  569. if (iFirstIndex < 0) iFirstIndex = 0;
  570. if (iFirstIndex > [self numberOfPhotos] - 1) iFirstIndex = [self numberOfPhotos] - 1;
  571. if (iLastIndex < 0) iLastIndex = 0;
  572. if (iLastIndex > [self numberOfPhotos] - 1) iLastIndex = [self numberOfPhotos] - 1;
  573. // Recycle no longer needed pages
  574. NSInteger pageIndex;
  575. for (MWZoomingScrollView *page in _visiblePages) {
  576. pageIndex = page.index;
  577. if (pageIndex < (NSUInteger)iFirstIndex || pageIndex > (NSUInteger)iLastIndex) {
  578. [_recycledPages addObject:page];
  579. [page.captionView removeFromSuperview];
  580. [page.selectedButton removeFromSuperview];
  581. [page.playButton removeFromSuperview];
  582. [page prepareForReuse];
  583. [page removeFromSuperview];
  584. MWLog(@"Removed page at index %lu", (unsigned long)pageIndex);
  585. }
  586. }
  587. [_visiblePages minusSet:_recycledPages];
  588. while (_recycledPages.count > 2) // Only keep 2 recycled pages
  589. [_recycledPages removeObject:[_recycledPages anyObject]];
  590. // Add missing pages
  591. for (NSUInteger index = (NSUInteger)iFirstIndex; index <= (NSUInteger)iLastIndex; index++) {
  592. if (![self isDisplayingPageForIndex:index]) {
  593. // Add new page
  594. MWZoomingScrollView *page = [self dequeueRecycledPage];
  595. if (!page) {
  596. page = [[MWZoomingScrollView alloc] initWithPhotoBrowser:self];
  597. }
  598. [_visiblePages addObject:page];
  599. [self configurePage:page forIndex:index];
  600. [_pagingScrollView addSubview:page];
  601. MWLog(@"Added page at index %lu", (unsigned long)index);
  602. // Add caption
  603. MWCaptionView *captionView = [self captionViewForPhotoAtIndex:index];
  604. if (captionView) {
  605. captionView.frame = [self frameForCaptionView:captionView atIndex:index];
  606. [_pagingScrollView addSubview:captionView];
  607. page.captionView = captionView;
  608. }
  609. // Add play button if needed
  610. if (page.displayingVideo) {
  611. UIButton *playButton = [UIButton buttonWithType:UIButtonTypeCustom];
  612. [playButton setImage:[UIImage imageForResourcePath:@"PlayButtonOverlayLarge" ofType:@"png" inBundle:[NSBundle bundleForClass:[self class]]] forState:UIControlStateNormal];
  613. [playButton setImage:[UIImage imageForResourcePath:@"PlayButtonOverlayLargeTap" ofType:@"png" inBundle:[NSBundle bundleForClass:[self class]]] forState:UIControlStateHighlighted];
  614. [playButton addTarget:self action:@selector(playButtonTapped:) forControlEvents:UIControlEventTouchUpInside];
  615. [playButton sizeToFit];
  616. playButton.frame = [self frameForPlayButton:playButton atIndex:index];
  617. [_pagingScrollView addSubview:playButton];
  618. page.playButton = playButton;
  619. }
  620. // Add selected button
  621. if (self.displaySelectionButtons) {
  622. UIButton *selectedButton = [UIButton buttonWithType:UIButtonTypeCustom];
  623. [selectedButton setImage:[UIImage imageForResourcePath:@"ImageSelectedOff" ofType:@"png" inBundle:[NSBundle bundleForClass:[self class]]] forState:UIControlStateNormal];
  624. UIImage *selectedOnImage;
  625. if (self.customImageSelectedIconName) {
  626. selectedOnImage = [UIImage imageNamed:self.customImageSelectedIconName];
  627. } else {
  628. selectedOnImage = [UIImage imageForResourcePath:@"ImageSelectedOn" ofType:@"png" inBundle:[NSBundle bundleForClass:[self class]]];
  629. }
  630. [selectedButton setImage:selectedOnImage forState:UIControlStateSelected];
  631. [selectedButton sizeToFit];
  632. selectedButton.adjustsImageWhenHighlighted = NO;
  633. [selectedButton addTarget:self action:@selector(selectedButtonTapped:) forControlEvents:UIControlEventTouchUpInside];
  634. selectedButton.frame = [self frameForSelectedButton:selectedButton atIndex:index];
  635. [_pagingScrollView addSubview:selectedButton];
  636. page.selectedButton = selectedButton;
  637. selectedButton.selected = [self photoIsSelectedAtIndex:index];
  638. }
  639. }
  640. }
  641. }
  642. - (void)updateVisiblePageStates {
  643. NSSet *copy = [_visiblePages copy];
  644. for (MWZoomingScrollView *page in copy) {
  645. // Update selection
  646. page.selectedButton.selected = [self photoIsSelectedAtIndex:page.index];
  647. }
  648. }
  649. - (BOOL)isDisplayingPageForIndex:(NSUInteger)index {
  650. for (MWZoomingScrollView *page in _visiblePages)
  651. if (page.index == index) return YES;
  652. return NO;
  653. }
  654. - (MWZoomingScrollView *)pageDisplayedAtIndex:(NSUInteger)index {
  655. MWZoomingScrollView *thePage = nil;
  656. for (MWZoomingScrollView *page in _visiblePages) {
  657. if (page.index == index) {
  658. thePage = page; break;
  659. }
  660. }
  661. return thePage;
  662. }
  663. - (MWZoomingScrollView *)pageDisplayingPhoto:(id<MWPhoto>)photo {
  664. MWZoomingScrollView *thePage = nil;
  665. for (MWZoomingScrollView *page in _visiblePages) {
  666. if (page.photo == photo) {
  667. thePage = page; break;
  668. }
  669. }
  670. return thePage;
  671. }
  672. - (void)configurePage:(MWZoomingScrollView *)page forIndex:(NSUInteger)index {
  673. page.frame = [self frameForPageAtIndex:index];
  674. page.index = index;
  675. page.photo = [self photoAtIndex:index];
  676. }
  677. - (MWZoomingScrollView *)dequeueRecycledPage {
  678. MWZoomingScrollView *page = [_recycledPages anyObject];
  679. if (page) {
  680. [_recycledPages removeObject:page];
  681. }
  682. return page;
  683. }
  684. // Handle page changes
  685. - (void)didStartViewingPageAtIndex:(NSUInteger)index {
  686. // Handle 0 photos
  687. if (![self numberOfPhotos]) {
  688. // Show controls
  689. [self setControlsHidden:NO animated:YES permanent:YES];
  690. return;
  691. }
  692. // Handle video on page change
  693. if (!_rotating || index != _currentVideoIndex) {
  694. [self clearCurrentVideo];
  695. }
  696. // Release images further away than +/-1
  697. NSUInteger i;
  698. if (index > 0) {
  699. // Release anything < index - 1
  700. for (i = 0; i < index-1; i++) {
  701. id photo = [_photos objectAtIndex:i];
  702. if (photo != [NSNull null]) {
  703. [photo unloadUnderlyingImage];
  704. [_photos replaceObjectAtIndex:i withObject:[NSNull null]];
  705. MWLog(@"Released underlying image at index %lu", (unsigned long)i);
  706. }
  707. }
  708. }
  709. if (index < [self numberOfPhotos] - 1) {
  710. // Release anything > index + 1
  711. for (i = index + 2; i < _photos.count; i++) {
  712. id photo = [_photos objectAtIndex:i];
  713. if (photo != [NSNull null]) {
  714. [photo unloadUnderlyingImage];
  715. [_photos replaceObjectAtIndex:i withObject:[NSNull null]];
  716. MWLog(@"Released underlying image at index %lu", (unsigned long)i);
  717. }
  718. }
  719. }
  720. // Load adjacent images if needed and the photo is already
  721. // loaded. Also called after photo has been loaded in background
  722. id <MWPhoto> currentPhoto = [self photoAtIndex:index];
  723. if ([currentPhoto underlyingImage]) {
  724. // photo loaded so load ajacent now
  725. [self loadAdjacentPhotosIfNecessary:currentPhoto];
  726. }
  727. // Notify delegate
  728. if (index != _previousPageIndex) {
  729. if ([_delegate respondsToSelector:@selector(photoBrowser:didDisplayPhotoAtIndex:)])
  730. [_delegate photoBrowser:self didDisplayPhotoAtIndex:index];
  731. _previousPageIndex = index;
  732. } else {
  733. if ([_delegate respondsToSelector:@selector(photoBrowser:didDisplayPhotoAtIndex:)])
  734. [_delegate photoBrowser:self didDisplayPhotoAtIndex:index];
  735. }
  736. // Update nav
  737. [self updateNavigation];
  738. }
  739. #pragma mark - Frame Calculations
  740. - (CGRect)frameForPagingScrollView {
  741. CGRect frame = self.view.bounds;// [[UIScreen mainScreen] bounds];
  742. frame.origin.x -= PADDING;
  743. frame.size.width += (2 * PADDING);
  744. return CGRectIntegral(frame);
  745. }
  746. - (CGRect)frameForPageAtIndex:(NSUInteger)index {
  747. // We have to use our paging scroll view's bounds, not frame, to calculate the page placement. When the device is in
  748. // landscape orientation, the frame will still be in portrait because the pagingScrollView is the root view controller's
  749. // view, so its frame is in window coordinate space, which is never rotated. Its bounds, however, will be in landscape
  750. // because it has a rotation transform applied.
  751. CGRect bounds = _pagingScrollView.bounds;
  752. CGRect pageFrame = bounds;
  753. pageFrame.size.width -= (2 * PADDING);
  754. pageFrame.origin.x = (bounds.size.width * index) + PADDING;
  755. return CGRectIntegral(pageFrame);
  756. }
  757. - (CGSize)contentSizeForPagingScrollView {
  758. // We have to use the paging scroll view's bounds to calculate the contentSize, for the same reason outlined above.
  759. CGRect bounds = _pagingScrollView.bounds;
  760. return CGSizeMake(bounds.size.width * [self numberOfPhotos], bounds.size.height);
  761. }
  762. - (CGPoint)contentOffsetForPageAtIndex:(NSUInteger)index {
  763. CGFloat pageWidth = _pagingScrollView.bounds.size.width;
  764. CGFloat newOffset = index * pageWidth;
  765. return CGPointMake(newOffset, 0);
  766. }
  767. - (CGRect)frameForToolbarAtOrientation:(UIInterfaceOrientation)orientation {
  768. CGFloat safeAreaBottom = 0;
  769. CGFloat height = 49;
  770. // iOS 11 safeArea
  771. if (@available(iOS 11, *)) {
  772. safeAreaBottom = [UIApplication sharedApplication].delegate.window.safeAreaInsets.bottom;
  773. }
  774. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone && UIInterfaceOrientationIsLandscape(orientation))
  775. height = 39;
  776. return CGRectIntegral(CGRectMake(0, self.view.bounds.size.height - height - safeAreaBottom, self.view.bounds.size.width, height ));
  777. }
  778. - (CGRect)frameForCaptionView:(MWCaptionView *)captionView atIndex:(NSUInteger)index {
  779. // iOS 11 safeArea
  780. CGFloat safeAreaBottom = 0;
  781. if (@available(iOS 11, *)) {
  782. safeAreaBottom = [UIApplication sharedApplication].delegate.window.safeAreaInsets.bottom;
  783. }
  784. CGRect pageFrame = [self frameForPageAtIndex:index];
  785. CGSize captionSize = [captionView sizeThatFits:CGSizeMake(pageFrame.size.width, 0)];
  786. CGRect captionFrame = CGRectMake(pageFrame.origin.x,
  787. pageFrame.size.height - captionSize.height - (_toolbar.superview?_toolbar.frame.size.height:0) - safeAreaBottom,
  788. pageFrame.size.width,
  789. captionSize.height);
  790. return CGRectIntegral(captionFrame);
  791. }
  792. - (CGRect)frameForSelectedButton:(UIButton *)selectedButton atIndex:(NSUInteger)index {
  793. CGRect pageFrame = [self frameForPageAtIndex:index];
  794. CGFloat padding = 20;
  795. CGFloat yOffset = 0;
  796. if (![self areControlsHidden]) {
  797. UINavigationBar *navBar = self.navigationController.navigationBar;
  798. yOffset = navBar.frame.origin.y + navBar.frame.size.height;
  799. }
  800. CGRect selectedButtonFrame = CGRectMake(pageFrame.origin.x + pageFrame.size.width - selectedButton.frame.size.width - padding,
  801. padding + yOffset,
  802. selectedButton.frame.size.width,
  803. selectedButton.frame.size.height);
  804. return CGRectIntegral(selectedButtonFrame);
  805. }
  806. - (CGRect)frameForPlayButton:(UIButton *)playButton atIndex:(NSUInteger)index {
  807. CGRect pageFrame = [self frameForPageAtIndex:index];
  808. return CGRectMake(floorf(CGRectGetMidX(pageFrame) - playButton.frame.size.width / 2),
  809. floorf(CGRectGetMidY(pageFrame) - playButton.frame.size.height / 2),
  810. playButton.frame.size.width,
  811. playButton.frame.size.height);
  812. }
  813. #pragma mark - UIScrollView Delegate
  814. - (void)scrollViewDidScroll:(UIScrollView *)scrollView {
  815. // Checks
  816. if (!_viewIsActive || _performingLayout || _rotating) return;
  817. // Tile pages
  818. [self tilePages];
  819. // Calculate current page
  820. CGRect visibleBounds = _pagingScrollView.bounds;
  821. NSInteger index = (NSInteger)(floorf(CGRectGetMidX(visibleBounds) / CGRectGetWidth(visibleBounds)));
  822. if (index < 0) index = 0;
  823. if (index > [self numberOfPhotos] - 1) index = [self numberOfPhotos] - 1;
  824. NSUInteger previousCurrentPage = _currentPageIndex;
  825. _currentPageIndex = index;
  826. if (_currentPageIndex != previousCurrentPage) {
  827. [self didStartViewingPageAtIndex:index];
  828. }
  829. }
  830. - (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
  831. // Hide controls when dragging begins
  832. [self setControlsHidden:YES animated:YES permanent:NO];
  833. }
  834. - (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
  835. // Update nav when page changes
  836. [self updateNavigation];
  837. }
  838. #pragma mark - Navigation
  839. - (void)updateNavigation {
  840. // Title
  841. NSUInteger numberOfPhotos = [self numberOfPhotos];
  842. if (numberOfPhotos > 1) {
  843. if ([_delegate respondsToSelector:@selector(photoBrowser:titleForPhotoAtIndex:)]) {
  844. self.title = [_delegate photoBrowser:self titleForPhotoAtIndex:_currentPageIndex];
  845. } else {
  846. self.title = [NSString stringWithFormat:@"%lu %@ %lu", (unsigned long)(_currentPageIndex+1), NSLocalizedString(@"of", @"Used in the context: 'Showing 1 of 3 items'"), (unsigned long)numberOfPhotos];
  847. }
  848. } else {
  849. self.title = nil;
  850. }
  851. // Buttons
  852. _previousButton.enabled = (_currentPageIndex > 0);
  853. _nextButton.enabled = (_currentPageIndex < numberOfPhotos - 1);
  854. //TWS Disable action button if there is no image or it's a video
  855. /*
  856. MWPhoto *photo = [self photoAtIndex:_currentPageIndex];
  857. if ([photo underlyingImage] == nil || ([photo respondsToSelector:@selector(isVideo)] && photo.isVideo)) {
  858. _actionButton.enabled = NO;
  859. _actionButton.tintColor = [UIColor clearColor]; // Tint to hide button
  860. } else {
  861. _actionButton.enabled = YES;
  862. _actionButton.tintColor = nil;
  863. }
  864. */
  865. }
  866. - (void)jumpToPageAtIndex:(NSUInteger)index animated:(BOOL)animated {
  867. // Change page
  868. if (index < [self numberOfPhotos]) {
  869. CGRect pageFrame = [self frameForPageAtIndex:index];
  870. [_pagingScrollView setContentOffset:CGPointMake(pageFrame.origin.x - PADDING, 0) animated:animated];
  871. [self updateNavigation];
  872. }
  873. // Update timer to give more time
  874. [self hideControlsAfterDelay];
  875. }
  876. - (void)gotoPreviousPage {
  877. [self showPreviousPhotoAnimated:NO];
  878. }
  879. - (void)gotoNextPage {
  880. [self showNextPhotoAnimated:NO];
  881. }
  882. - (void)showPreviousPhotoAnimated:(BOOL)animated {
  883. [self jumpToPageAtIndex:_currentPageIndex-1 animated:animated];
  884. }
  885. - (void)showNextPhotoAnimated:(BOOL)animated {
  886. [self jumpToPageAtIndex:_currentPageIndex+1 animated:animated];
  887. }
  888. #pragma mark - Interactions
  889. - (void)selectedButtonTapped:(id)sender {
  890. UIButton *selectedButton = (UIButton *)sender;
  891. selectedButton.selected = !selectedButton.selected;
  892. NSUInteger index = NSUIntegerMax;
  893. for (MWZoomingScrollView *page in _visiblePages) {
  894. if (page.selectedButton == selectedButton) {
  895. index = page.index;
  896. break;
  897. }
  898. }
  899. if (index != NSUIntegerMax) {
  900. [self setPhotoSelected:selectedButton.selected atIndex:index];
  901. }
  902. }
  903. - (void)playButtonTapped:(id)sender {
  904. // Ignore if we're already playing a video
  905. if (_currentVideoIndex != NSUIntegerMax) {
  906. return;
  907. }
  908. NSUInteger index = [self indexForPlayButton:sender];
  909. if (index != NSUIntegerMax) {
  910. if (!_currentVideoPlayerViewController) {
  911. [self playVideoAtIndex:index];
  912. }
  913. }
  914. }
  915. - (NSUInteger)indexForPlayButton:(UIView *)playButton {
  916. NSUInteger index = NSUIntegerMax;
  917. for (MWZoomingScrollView *page in _visiblePages) {
  918. if (page.playButton == playButton) {
  919. index = page.index;
  920. break;
  921. }
  922. }
  923. return index;
  924. }
  925. #pragma mark - Video
  926. - (void)playVideoAtIndex:(NSUInteger)index {
  927. id photo = [self photoAtIndex:index];
  928. if ([photo respondsToSelector:@selector(getVideoURL:)]) {
  929. // Valid for playing
  930. [self clearCurrentVideo];
  931. _currentVideoIndex = index;
  932. [self setVideoLoadingIndicatorVisible:YES atPageIndex:index];
  933. // Get video and play
  934. __typeof(self) __weak weakSelf = self;
  935. [photo getVideoURL:^(NSURL *url) {
  936. dispatch_async(dispatch_get_main_queue(), ^{
  937. // If the video is not playing anymore then bail
  938. __typeof(self) strongSelf = weakSelf;
  939. if (!strongSelf) return;
  940. if (strongSelf->_currentVideoIndex != index || !strongSelf->_viewIsActive) {
  941. return;
  942. }
  943. if (url) {
  944. [weakSelf _playVideo:url atPhotoIndex:index];
  945. } else {
  946. [weakSelf setVideoLoadingIndicatorVisible:NO atPageIndex:index];
  947. }
  948. });
  949. }];
  950. }
  951. }
  952. - (void)_playVideo:(NSURL *)videoURL atPhotoIndex:(NSUInteger)index {
  953. // Setup player
  954. _currentVideoPlayerViewController = [[AVPlayerViewController alloc] init];
  955. _currentVideoPlayerViewController.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
  956. _currentVideoPlayerItem = [[AVPlayerItem alloc] initWithURL:videoURL];
  957. _currentVideoPlayerViewController.player = [[AVPlayer alloc] initWithPlayerItem:_currentVideoPlayerItem];
  958. _currentVideoPlayer = _currentVideoPlayerViewController.player;
  959. // Remove the movie player view controller from the "playback did finish" notification observers
  960. // Observe ourselves so we can get it to use the crossfade transition
  961. [[NSNotificationCenter defaultCenter] removeObserver:self
  962. name:AVPlayerItemDidPlayToEndTimeNotification
  963. object:_currentVideoPlayerItem];
  964. [[NSNotificationCenter defaultCenter] addObserver:self
  965. selector:@selector(videoFinishedCallback:)
  966. name:AVPlayerItemDidPlayToEndTimeNotification
  967. object:_currentVideoPlayerItem];
  968. // Show
  969. [self presentViewController:_currentVideoPlayerViewController animated:YES completion:^{
  970. [_currentVideoPlayer play];
  971. }];
  972. }
  973. - (void)videoFinishedCallback:(NSNotification*)notification {
  974. // Remove observer
  975. [[NSNotificationCenter defaultCenter] removeObserver:self
  976. name:AVPlayerItemDidPlayToEndTimeNotification
  977. object:_currentVideoPlayerItem];
  978. // Clear up
  979. [self clearCurrentVideo];
  980. [self dismissViewControllerAnimated:YES completion:nil];
  981. }
  982. - (void)clearCurrentVideo {
  983. [_currentVideoPlayerViewController.player pause];
  984. [_currentVideoLoadingIndicator removeFromSuperview];
  985. _currentVideoPlayerViewController = nil;
  986. _currentVideoLoadingIndicator = nil;
  987. _currentVideoPlayerItem = nil;
  988. [[self pageDisplayedAtIndex:_currentVideoIndex] playButton].hidden = NO;
  989. _currentVideoIndex = NSUIntegerMax;
  990. }
  991. - (void)setVideoLoadingIndicatorVisible:(BOOL)visible atPageIndex:(NSUInteger)pageIndex {
  992. if (_currentVideoLoadingIndicator && !visible) {
  993. [_currentVideoLoadingIndicator removeFromSuperview];
  994. _currentVideoLoadingIndicator = nil;
  995. [[self pageDisplayedAtIndex:pageIndex] playButton].hidden = NO;
  996. } else if (!_currentVideoLoadingIndicator && visible) {
  997. _currentVideoLoadingIndicator = [[UIActivityIndicatorView alloc] initWithFrame:CGRectZero];
  998. [_currentVideoLoadingIndicator sizeToFit];
  999. [_currentVideoLoadingIndicator startAnimating];
  1000. [_pagingScrollView addSubview:_currentVideoLoadingIndicator];
  1001. [self positionVideoLoadingIndicator];
  1002. [[self pageDisplayedAtIndex:pageIndex] playButton].hidden = YES;
  1003. }
  1004. }
  1005. - (void)positionVideoLoadingIndicator {
  1006. if (_currentVideoLoadingIndicator && _currentVideoIndex != NSUIntegerMax) {
  1007. CGRect frame = [self frameForPageAtIndex:_currentVideoIndex];
  1008. _currentVideoLoadingIndicator.center = CGPointMake(CGRectGetMidX(frame), CGRectGetMidY(frame));
  1009. }
  1010. }
  1011. #pragma mark - Control Hiding / Showing
  1012. // If permanent then we don't set timers to hide again
  1013. // Fades all controls on iOS 5 & 6, and iOS 7 controls slide and fade
  1014. - (void)setControlsHidden:(BOOL)hidden animated:(BOOL)animated permanent:(BOOL)permanent {
  1015. // Force visible
  1016. if (![self numberOfPhotos] || _alwaysShowControls)
  1017. hidden = NO;
  1018. // Cancel any timers
  1019. [self cancelControlHiding];
  1020. // Animations & positions
  1021. CGFloat animatonOffset = 20;
  1022. CGFloat animationDuration = (animated ? 0.35 : 0);
  1023. // Toolbar, nav bar and captions
  1024. // Pre-appear animation positions for sliding
  1025. if ([self areControlsHidden] && !hidden && animated) {
  1026. // Toolbar
  1027. _toolbar.frame = CGRectOffset([self frameForToolbarAtOrientation:[[UIApplication sharedApplication] statusBarOrientation]], 0, animatonOffset);
  1028. // Captions
  1029. for (MWZoomingScrollView *page in _visiblePages) {
  1030. if (page.captionView) {
  1031. MWCaptionView *v = page.captionView;
  1032. //TWS
  1033. id <MWPhoto> photo = [self photoAtIndex:self.currentIndex];
  1034. if (photo.caption) {
  1035. if ([photo caption]) v.label.text = photo.caption;
  1036. }
  1037. // Pass any index, all we're interested in is the Y
  1038. CGRect captionFrame = [self frameForCaptionView:v atIndex:0];
  1039. captionFrame.origin.x = v.frame.origin.x; // Reset X
  1040. v.frame = CGRectOffset(captionFrame, 0, animatonOffset);
  1041. }
  1042. }
  1043. }
  1044. if ([_delegate respondsToSelector:@selector(setControlsHidden:animated:permanent:)]) {
  1045. [_delegate setControlsHidden:hidden animated:animated permanent:permanent];
  1046. }
  1047. [UIView animateWithDuration:animationDuration animations:^(void) {
  1048. CGFloat alpha = hidden ? 0 : 1;
  1049. // Nav bar slides up on it's own on iOS 7+
  1050. [self.navigationController.navigationBar setAlpha:alpha];
  1051. // Toolbar
  1052. _toolbar.frame = [self frameForToolbarAtOrientation:[[UIApplication sharedApplication] statusBarOrientation]];
  1053. if (hidden) _toolbar.frame = CGRectOffset(_toolbar.frame, 0, animatonOffset);
  1054. _toolbar.alpha = alpha;
  1055. // Captions
  1056. for (MWZoomingScrollView *page in _visiblePages) {
  1057. if (page.captionView) {
  1058. MWCaptionView *v = page.captionView;
  1059. // Pass any index, all we're interested in is the Y
  1060. CGRect captionFrame = [self frameForCaptionView:v atIndex:0];
  1061. captionFrame.origin.x = v.frame.origin.x; // Reset X
  1062. if (hidden) captionFrame = CGRectOffset(captionFrame, 0, animatonOffset);
  1063. v.frame = captionFrame;
  1064. v.alpha = alpha;
  1065. }
  1066. }
  1067. // Selected buttons
  1068. for (MWZoomingScrollView *page in _visiblePages) {
  1069. if (page.selectedButton) {
  1070. UIButton *v = page.selectedButton;
  1071. CGRect newFrame = [self frameForSelectedButton:v atIndex:0];
  1072. newFrame.origin.x = v.frame.origin.x;
  1073. v.frame = newFrame;
  1074. }
  1075. }
  1076. } completion:^(BOOL finished) {}];
  1077. // Control hiding timer
  1078. // Will cancel existing timer but only begin hiding if
  1079. // they are visible
  1080. if (!permanent) [self hideControlsAfterDelay];
  1081. }
  1082. - (UIStatusBarStyle)preferredStatusBarStyle {
  1083. return UIStatusBarStyleLightContent;
  1084. }
  1085. - (UIStatusBarAnimation)preferredStatusBarUpdateAnimation {
  1086. return UIStatusBarAnimationSlide;
  1087. }
  1088. - (void)cancelControlHiding {
  1089. // If a timer exists then cancel and release
  1090. if (_controlVisibilityTimer) {
  1091. [_controlVisibilityTimer invalidate];
  1092. _controlVisibilityTimer = nil;
  1093. }
  1094. }
  1095. // Enable/disable control visiblity timer
  1096. - (void)hideControlsAfterDelay {
  1097. if (![self areControlsHidden]) {
  1098. [self cancelControlHiding];
  1099. _controlVisibilityTimer = [NSTimer scheduledTimerWithTimeInterval:self.delayToHideElements target:self selector:@selector(hideControls) userInfo:nil repeats:NO];
  1100. }
  1101. }
  1102. - (BOOL)areControlsHidden {
  1103. return (_toolbar.alpha == 0);
  1104. }
  1105. - (void)hideControls { [self setControlsHidden:YES animated:YES permanent:NO]; }
  1106. - (void)showControls { [self setControlsHidden:NO animated:YES permanent:NO]; }
  1107. - (void)toggleControls { [self setControlsHidden:![self areControlsHidden] animated:YES permanent:NO]; }
  1108. #pragma mark - Properties
  1109. - (void)setCurrentPhotoIndex:(NSUInteger)index {
  1110. // Validate
  1111. NSUInteger photoCount = [self numberOfPhotos];
  1112. if (photoCount == 0) {
  1113. index = 0;
  1114. } else {
  1115. if (index >= photoCount)
  1116. index = [self numberOfPhotos]-1;
  1117. }
  1118. _currentPageIndex = index;
  1119. if ([self isViewLoaded]) {
  1120. [self jumpToPageAtIndex:index animated:NO];
  1121. if (!_viewIsActive)
  1122. [self tilePages]; // Force tiling if view is not visible
  1123. }
  1124. }
  1125. #pragma mark - Misc
  1126. - (void)doneButtonPressed:(id)sender {
  1127. // Dismiss view controller
  1128. if ([_delegate respondsToSelector:@selector(photoBrowserDidFinishPresentation:)]) {
  1129. // Call delegate method and let them dismiss us
  1130. [_delegate photoBrowserDidFinishPresentation:self];
  1131. }
  1132. }
  1133. #pragma mark - Delete
  1134. - (void)deleteButtonPressed:(id)sender {
  1135. if ([self.delegate respondsToSelector:@selector(photoBrowser:deleteButtonPressedForPhotoAtIndex:deleteButton:)])
  1136. [self.delegate photoBrowser:self deleteButtonPressedForPhotoAtIndex:_currentPageIndex deleteButton:self.deleteButton];
  1137. }
  1138. #pragma mark - Share
  1139. - (void)shareButtonPressed:(id)sender {
  1140. if ([self.delegate respondsToSelector:@selector(photoBrowser:shareButtonPressedForPhotoAtIndex:)])
  1141. [self.delegate photoBrowser:self shareButtonPressedForPhotoAtIndex:_currentPageIndex];
  1142. }
  1143. #pragma mark - Actions
  1144. - (void)actionButtonPressed:(id)sender {
  1145. // Only react when image has loaded
  1146. id <MWPhoto> photo = [self photoAtIndex:_currentPageIndex];
  1147. if ([self numberOfPhotos] > 0 && [photo underlyingImage]) {
  1148. // If they have defined a delegate method then just message them
  1149. if ([self.delegate respondsToSelector:@selector(photoBrowser:actionButtonPressedForPhotoAtIndex:)]) {
  1150. // Let delegate handle things
  1151. [self.delegate photoBrowser:self actionButtonPressedForPhotoAtIndex:_currentPageIndex];
  1152. } else {
  1153. // Show activity view controller
  1154. NSMutableArray *items = [NSMutableArray arrayWithObject:[photo underlyingImage]];
  1155. if (photo.caption) {
  1156. [items addObject:photo.caption];
  1157. }
  1158. self.activityViewController = [[UIActivityViewController alloc] initWithActivityItems:items applicationActivities:nil];
  1159. // Show
  1160. typeof(self) __weak weakSelf = self;
  1161. [self.activityViewController setCompletionWithItemsHandler:^(NSString *activityType, BOOL completed, NSArray *returnedItems, NSError *activityError) {
  1162. weakSelf.activityViewController = nil;
  1163. [weakSelf hideControlsAfterDelay];
  1164. }];
  1165. // iOS 8 - Set the Anchor Point for the popover
  1166. if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"8")) {
  1167. self.activityViewController.popoverPresentationController.barButtonItem = _actionButton;
  1168. }
  1169. [self presentViewController:self.activityViewController animated:YES completion:nil];
  1170. }
  1171. // Keep controls hidden
  1172. [self setControlsHidden:NO animated:YES permanent:YES];
  1173. }
  1174. }
  1175. @end