Advertisement
Guest User

Untitled

a guest
Jan 18th, 2016
99
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Swift 29.92 KB | None | 0 0
  1. //
  2. //  UIDashboardViewController.swift
  3. //  Twingled
  4. //
  5. //  Created by Tom Swindell on 12/05/2015.
  6. //  Copyright (c) 2015 The App Developers. All rights reserved.
  7. //
  8.  
  9. import Foundation
  10. import UIKit
  11. import CoreData
  12.  
  13. func ==(lhs: CarouselButton, rhs: CarouselButton) -> Bool {
  14.     return lhs.hashValue == rhs.hashValue
  15. }
  16.  
  17. class CarouselButton: Hashable {
  18.     var index = 0
  19.     var avatarButton = UIButton()
  20.     var unreadIndicator = UIView()
  21.    
  22.    
  23.     var hashValue: Int {
  24.         get {
  25.             return "\(index)".hashValue
  26.         }
  27.     }
  28.    
  29.    
  30.     func setUnreadMessageIndicator(visible: Bool) {
  31.        
  32.         if (visible) {
  33.            
  34.             if (unreadIndicator.superview == nil) {
  35.                
  36.                 //draw circle
  37.                 let rect : CGRect = CGRectMake(0,0,48,48)
  38.                 unreadIndicator = UIView(frame: rect)
  39.                 avatarButton.addSubview(unreadIndicator)
  40.                
  41.                 let circlePath = UIBezierPath(arcCenter: CGPoint(x: rect.width-8, y: 8), radius: CGFloat(4), startAngle: CGFloat(0), endAngle:CGFloat(M_PI * 2), clockwise: true)
  42.                
  43.                 let shapeLayer = CAShapeLayer()
  44.                 shapeLayer.path = circlePath.CGPath
  45.                
  46.                 //change the fill color
  47.                 let profileColor = UIColor.getProfileColorFromString(UserManager.SharedInstance.user!.profileColor)
  48.                 shapeLayer.fillColor = profileColor.CGColor
  49.                 //you can change the stroke color
  50.                 shapeLayer.strokeColor = UIColor.clearColor().CGColor
  51.                
  52.                 unreadIndicator.layer.addSublayer(shapeLayer)
  53.             }
  54.         }
  55.         else {
  56.             unreadIndicator.removeFromSuperview()
  57.         }
  58.        
  59.     }
  60.  
  61.    
  62.    
  63.    
  64. }
  65.  
  66. class UIDashboardViewController: UIViewController {
  67.    
  68.    
  69.    
  70.     //MARK: Variables
  71.     var pageViewController: UIPageViewController!
  72.     var apiRequest = WebRequest()
  73. //    var avatarButtons = [CarouselButton]()
  74.     var avatarSet = Set<CarouselButton>()
  75.     var currentPageIndex = 0
  76.     var profileContentPages = [ProfileContentViewController]()
  77.    
  78.     var fetchResultsController: NSFetchedResultsController!
  79.     var isChatOpen = false
  80.     var hasOpenedProfile = false
  81.    
  82.     var pageVCinAnimation = false
  83.    
  84.     lazy var webStoryboard: UIStoryboard = {
  85.         return UIStoryboard(name: "WebRequest", bundle: nil)
  86.         }()
  87.    
  88.     lazy private var activityIndicator : CustomActivityIndicatorView = {
  89.         let image : UIImage = UIImage(named: "spinner")!
  90.         return CustomActivityIndicatorView(image: image)
  91.     }()
  92.    
  93.    
  94.     //top avatar buttons for easy access
  95.     var avatarButtons: [CarouselButton] {
  96.        
  97.         get {
  98.             var buttons = Array(self.avatarSet)
  99.             buttons.sortInPlace({($0.index < $1.index) })
  100.             return buttons
  101.         }
  102.     }
  103.    
  104.    
  105.     //MARK: Outlets
  106.     @IBOutlet weak var mainViewOutlet: UIView!
  107.     @IBOutlet weak var twingledTitleOutlet: UIImageView!
  108.     @IBOutlet weak var plusButtonOutlet: UIButton!
  109.     @IBOutlet weak var editProfileButtonOutlet: UIButton!
  110.     @IBOutlet weak var addTwingleButton: UIButton!
  111.     @IBOutlet weak var avatarScrollView: UIScrollView!
  112.     @IBOutlet weak var carousel: iCarousel!
  113.     @IBOutlet weak var tutorialView: UIView!
  114.     @IBOutlet weak var noConnectionsView: UIView!
  115.     @IBOutlet weak var noConnectionsCopyLabel: UILabel!
  116.     @IBOutlet weak var buySomeTwinglesCopyLabel: UILabel!
  117.     @IBOutlet weak var largeTwingleGraphicTopConstraint: NSLayoutConstraint!
  118.     @IBOutlet weak var largeTwingleGraphicHeightConstraint: NSLayoutConstraint!
  119.  
  120.    
  121.     @IBAction func didTapAddTwingle(sender: AnyObject) {
  122.         hasOpenedProfile = true
  123.         let addTwingleStoryboard = UIStoryboard(name: "AddTwingle", bundle: nil)
  124.         if let vc = addTwingleStoryboard.instantiateViewControllerWithIdentifier("addTwingle") as? AddTwingleViewController {
  125.            
  126.             vc.mode = .Recieve
  127.             self.showDetailViewController(vc, sender: self)
  128.         }
  129.     }
  130.    
  131.     @IBAction func didTapBuyCodes(sender: AnyObject) {
  132.         let vc = self.webStoryboard.instantiateInitialViewController() as! WebRequestViewController
  133.         WebViewManager.SharedInstance.urlType = .BuyTwingles
  134.         self.presentViewController(vc, animated: true, completion: nil)
  135.     }
  136.    
  137.     @IBAction func didTapProfileButton(sender: AnyObject) {
  138.         activityIndicator.startAnimating()
  139.         UIApplication.sharedApplication().beginIgnoringInteractionEvents()
  140.     }
  141.    
  142.     //MARK: Functions
  143.     private func slideToPage(index: Int, completion: (() -> Void)?) {
  144.         let count = ConnectionsManager.SharedInstance.connections.count
  145.         if index < count {
  146.             if index > currentPageIndex {
  147.                 if let vc = viewControllerAtIndex(index) {
  148.                     self.pageViewController.setViewControllers([vc], direction: UIPageViewControllerNavigationDirection.Forward, animated: true, completion: { (complete) -> Void in
  149.                         self.currentPageIndex = index
  150.                         completion?()
  151.                     })
  152.                 }
  153.             } else if index < currentPageIndex {
  154.                 if let vc = viewControllerAtIndex(index) {
  155.                     self.pageViewController.setViewControllers([vc], direction: UIPageViewControllerNavigationDirection.Reverse, animated: true, completion: { (complete) -> Void in
  156.                         self.currentPageIndex = index
  157.                         completion?()
  158.                     })
  159.                 }
  160.             }
  161.         }
  162.     }
  163.    
  164.     func reset() {
  165.         if pageVCinAnimation{
  166.             self.performSelector("reset", withObject: nil, afterDelay: 0.2)
  167.             return
  168.         }
  169.        
  170.        
  171.         dispatch_async(dispatch_get_main_queue(), { () -> Void in
  172.             for a in self.avatarSet {
  173.                 a.avatarButton.removeFromSuperview()
  174.             }
  175.         })
  176.         if let vcs = pageViewController.viewControllers {
  177.             for vc in vcs {
  178.                 vc.view.removeFromSuperview()
  179.                 vc.removeFromParentViewController()
  180.                 vc.dismissViewControllerAnimated(false, completion: nil)
  181.             }
  182.         }
  183.         self.profileContentPages = [ProfileContentViewController]()
  184.         self.pageViewController.dataSource = self
  185.         self.pageViewController.delegate = self
  186.         self.pageViewController.automaticallyAdjustsScrollViewInsets = false
  187.         var index = 0
  188.        
  189.         for _ in ConnectionsManager.SharedInstance.connections {
  190.             let vc = viewControllerAtIndex(index)
  191.             vc?.view //forces view did load to be called
  192.             ++index
  193.         }
  194.         let profileContentViewController = self.viewControllerAtIndex(0)
  195.         if profileContentViewController != nil {
  196.             self.pageViewController.setViewControllers([profileContentViewController!], direction: UIPageViewControllerNavigationDirection.Forward, animated: false, completion: nil)
  197.             self.view.layoutIfNeeded()
  198.             self.pageViewController.view.frame = CGRectMake(0, 0, self.view.frame.width, self.view.frame.height)
  199.             self.addChildViewController(pageViewController)
  200.             self.mainViewOutlet.addSubview(pageViewController.view)
  201.             self.pageViewController.view.center = self.mainViewOutlet.center
  202.             self.pageViewController.didMoveToParentViewController(self)
  203.             self.view.layoutIfNeeded()
  204.             dispatch_async(dispatch_get_main_queue(), { () -> Void in
  205.                
  206.                 for var i = 0; i < self.carousel.numberOfItems; i++ {
  207.                     self.carousel.itemViewAtIndex(i).removeFromSuperview()
  208.                     self.carousel.removeItemAtIndex(i, animated: false)
  209.                 }
  210.                 for a in self.avatarSet {
  211.                     a.avatarButton.removeFromSuperview()
  212.                 }
  213.                 self.avatarSet = Set<CarouselButton>()
  214.                 self.carousel.reloadData()
  215.             })
  216.            
  217.         }
  218.         if currentPageIndex > 0 && currentPageIndex < ConnectionsManager.SharedInstance.connections.count {
  219.             slideToPage(currentPageIndex, completion: nil)
  220.             selectAvatarButton(currentPageIndex)
  221.             ChatManager.SharedInstance.delegate = self.profileContentPages[currentPageIndex].chatVC
  222.         } else {
  223.             slideToPage(0, completion: nil)
  224.             self.selectAvatarButton(0)
  225.             if self.profileContentPages.count > 0 {
  226.                 ChatManager.SharedInstance.delegate = self.profileContentPages[0].chatVC
  227.             }
  228.         }
  229.     }
  230.    
  231.     func selectAvatarButton(index: Int) {
  232.        
  233. //        var avatarButtons: [CarouselButton] = Array(self.avatarSet)
  234. //        avatarButtons.sortInPlace({($0.index < $1.index) })
  235.         if avatarButtons.count > index && index >= 0 && ConnectionsManager.SharedInstance.connections.count > index {
  236.             if ConnectionsManager.SharedInstance.connections.count > 0 {
  237.                 for a in avatarButtons {
  238.                     if a.index == index {
  239.                         let path = ConnectionsManager.SharedInstance.connections[index].avatar.imagePath
  240.                         if path != nil {
  241.                             let image = FileManager.SharedInstance.getImageFromDisk(path!)
  242.                        
  243.                             a.avatarButton.setImage(image!.mask(UIImage(named: "dashboardAvatarMask")!), forState: .Normal)
  244.                             a.avatarButton.setBackgroundImage(UIImage.createImageWithColor(UIColor.whiteColor(), size: CGSize(width: 41, height: 41)).mask(UIImage(named: "dashboardSelectedAvatarMask")!)!, forState: .Normal)
  245.                         }
  246.                     } else {
  247.                         a.avatarButton.setBackgroundImage(UIImage(), forState: .Normal)
  248.                     }
  249.                 }
  250.                 self.view.layoutIfNeeded()
  251.             }
  252.         }
  253.     }
  254.    
  255.     func navigationToChat(senderId: String) {
  256.  
  257.         dispatch_async(dispatch_get_main_queue()) { () -> Void in
  258.        
  259.             let profileContentView = self.profileContentPages[self.currentPageIndex]
  260.             profileContentView.chatVC.closeChatAction(self)
  261.  
  262. //            NSTimer.scheduledTimerWithTimeInterval(0.5, target: self, selector: "scrollToPage:", userInfo: senderId, repeats: false)
  263.            
  264.         }
  265.            
  266.     }
  267.    
  268.     func scrollToPage(timer: NSTimer) {
  269.         let senderId = timer.userInfo as! String
  270.         dispatch_async(dispatch_get_main_queue()) { () -> Void in
  271.  
  272.             for var i = 0; i < self.profileContentPages.count; i++ {
  273.                 let p = self.profileContentPages[i]
  274.                 if p.connection.account_id == senderId {
  275.                     self.carousel.scrollToItemAtIndex(i, animated: true)
  276.                     self.slideToPage(i, completion: { () -> Void in
  277.                         dispatch_async(dispatch_get_main_queue()) { () -> Void in
  278.                             self.changeTopBarAlpha(0.0, time: 0.3, animate: false, completion: { () -> () in
  279.                                 UIView.animateWithDuration(0.2, delay: 1.2, options: UIViewAnimationOptions.CurveEaseIn, animations: { () -> Void in
  280.                                    
  281.                                     }, completion: { (complete) -> Void in
  282.                                         dispatch_async(dispatch_get_main_queue(), { () -> Void in
  283.                                             p.openChatView()
  284.                                         })
  285.                                 })
  286.                             })
  287.                         }
  288.                     })
  289.                 }
  290.             }
  291.         }
  292.        
  293.     }
  294.    
  295.    
  296.    
  297.     func viewControllerAtIndex(index : Int) -> UIViewController? {
  298.         if((ConnectionsManager.SharedInstance.connections.count == 0) || (index >= ConnectionsManager.SharedInstance.connections.count)) {
  299.                 return nil
  300.         }
  301.         var profileContentViewController: ProfileContentViewController?
  302.        
  303.         for p in self.profileContentPages {
  304.                 if p.connection.account_id == ConnectionsManager.SharedInstance.connections[index].account_id {
  305.                     profileContentViewController = p
  306.             }
  307.         }
  308.         if profileContentViewController == nil {
  309.             profileContentViewController = self.storyboard?.instantiateViewControllerWithIdentifier("ProfileContentViewController") as? ProfileContentViewController
  310.             profileContentViewController!.connection = ConnectionsManager.SharedInstance.connections[index]
  311.             var profiles = (profileContentViewController!.connection.profileImages.allObjects as! [ProfileImage]).sort({$0.modified.compare($1.modified) == NSComparisonResult.OrderedAscending})
  312.            
  313.             if profiles.count > 0 {
  314.                 let image = profiles[0].imagePath
  315.                 profileContentViewController!.imagePath = image
  316.  
  317.             }
  318.            
  319.             profileContentViewController!.pageIndex = index
  320.             self.profileContentPages.append(profileContentViewController!)
  321.         }
  322.        
  323.         self.changeTopBarAlpha(1.0, time: 0.33, animate: true, completion: nil)
  324.        
  325.         return profileContentViewController
  326.     }
  327.    
  328.  
  329.  
  330.    
  331.     func changeTopBarAlpha(alpha: CGFloat, time: NSTimeInterval, animate: Bool, completion: (() -> ())?) {
  332.         if animate {
  333.             UIView.animateWithDuration(time, animations: { () -> Void in
  334.                 self.twingledTitleOutlet.alpha = alpha
  335.                 self.plusButtonOutlet.alpha = alpha
  336.                 self.editProfileButtonOutlet.alpha = alpha
  337.                 self.addTwingleButton.alpha = alpha
  338.                 self.carousel.alpha = alpha
  339.                 }) { (complete) -> Void in
  340.                     if completion != nil {
  341.                         completion!()
  342.                     }
  343.             }
  344.         } else {
  345.             self.twingledTitleOutlet.alpha = alpha
  346.             self.plusButtonOutlet.alpha = alpha
  347.             self.editProfileButtonOutlet.alpha = alpha
  348.             self.addTwingleButton.alpha = alpha
  349.             self.carousel.alpha = alpha
  350.             if completion != nil {
  351.                 completion!()
  352.             }
  353.         }
  354.     }
  355.    
  356.     func animateAlpha(notif: NSNotification) {
  357.         if let alpha = notif.object as? CGFloat
  358.         {
  359.             self.changeTopBarAlpha(alpha, time: 0.33, animate: true, completion: nil)
  360.         }
  361.     }
  362.    
  363.     func changeAlpha(notif: NSNotification) {
  364.         if let alpha = notif.object as? CGFloat
  365.         {
  366.             self.changeTopBarAlpha(alpha, time: 0.33, animate: false, completion: nil)
  367.         }
  368.     }
  369.    
  370.    
  371.     typealias DeviceTokenCompletion = ((deviceToken: String?) -> Void)
  372.     var deviceTokenCompletion: DeviceTokenCompletion?
  373.    
  374.     func registerForPush( completion: (deviceToken: String?) -> () ) {
  375.        
  376.         deviceTokenCompletion = completion
  377.        
  378.         let application = UIApplication.sharedApplication()
  379.         if(application.respondsToSelector("isRegisteredForRemoteNotifications")) {
  380.             application.registerUserNotificationSettings(UIUserNotificationSettings(forTypes: ([.Badge, .Sound, .Alert]), categories: nil));
  381.         } else {
  382.             application.registerForRemoteNotificationTypes([.Badge, .Sound, .Alert])
  383.         }
  384.     }
  385.    
  386.     func gotToken(notification: NSNotification) {
  387.         var t: String?
  388.         if let token = notification.object as? String {
  389.             t = token
  390.         }
  391.         if deviceTokenCompletion != nil {
  392.             deviceTokenCompletion!(deviceToken: t)
  393.         }
  394.     }
  395.    
  396.     //MARK: Class lifecycle
  397.     override func viewDidLoad() {
  398.         activityIndicator.center = view.center
  399.         view.addSubview(activityIndicator)
  400.         addObserversToViewController()
  401.        
  402.         let style = NSMutableParagraphStyle()
  403.         style.lineSpacing = 5
  404.         style.alignment = NSTextAlignment.Center
  405.         let attributes = [NSParagraphStyleAttributeName : style]
  406.         noConnectionsCopyLabel.attributedText = NSAttributedString(string: noConnectionsCopyLabel.text!, attributes:attributes)
  407.         buySomeTwinglesCopyLabel.attributedText = NSAttributedString(string: buySomeTwinglesCopyLabel.text!, attributes:attributes)
  408.        
  409.         if DeviceType.IS_IPHONE_6 {
  410.             largeTwingleGraphicTopConstraint.constant = 110
  411.         } else if DeviceType.IS_IPHONE_6P {
  412.             largeTwingleGraphicTopConstraint.constant = 130
  413.         } else if DeviceType.IS_IPHONE_4_OR_LESS {
  414.             largeTwingleGraphicHeightConstraint.constant = 130
  415.         }
  416.         view.layoutIfNeeded()
  417.        
  418.         UserManager.SharedInstance.dashboardNav = self.navigationController as? TwingledNavigationController
  419.         if !NSUserDefaults.standardUserDefaults().boolForKey("hasSeenTutorial") {
  420.             UIView.animateWithDuration(0.33, animations: { () -> Void in
  421.                 self.tutorialView.alpha = 1.0
  422.             })
  423.         }
  424.        
  425.         self.automaticallyAdjustsScrollViewInsets = false
  426.         self.profileContentPages = [ProfileContentViewController]()
  427. //        self.avatarButtons = [CarouselButton]()
  428.         avatarSet = Set<CarouselButton>()
  429.         self.carousel.type = .Linear
  430.         self.carousel.scrollEnabled = false
  431.         carousel.bounces = false
  432.         carousel.ignorePerpendicularSwipes = true
  433.        
  434.         if let navController = self.navigationController as? TwingledNavigationController {
  435.             navController.hideNavigationBar()
  436.         }
  437.         super.viewDidLoad()
  438.         self.pageViewController = self.storyboard!.instantiateViewControllerWithIdentifier("PageViewController") as! UIPageViewController
  439.         for v in self.pageViewController!.view.subviews {
  440.             if let sub = v as? UIScrollView {
  441.                 sub.delegate = self
  442.             }
  443.         }
  444.         registerForPush()
  445.        
  446.        
  447.     }
  448.    
  449.     func registerForPush() {
  450.         self.registerForPush { (deviceToken) -> () in
  451.             if deviceToken != nil {
  452.                 self.loginToChat()
  453.                 UserManager.SharedInstance.uploadDeviceToken(UserManager.SharedInstance.Token!, deviceToken: deviceToken!, completion: {
  454.                     (success) -> () in
  455.                     if success {
  456.                         print("token uploaded")
  457.                     } else {
  458.                         print("token not uploaded")
  459.                     }
  460.                 })
  461.             }
  462.         }
  463.     }
  464.    
  465.     func loginToChat() {
  466.        
  467.         FirebaseManager.sharedInstance.login(UserManager.SharedInstance.user!.email, password: UserManager.SharedInstance.user!.account_id) { (success, authData) -> () in
  468.             if success {
  469.             }
  470.         }
  471.     }
  472.    
  473.     func addObserversToViewController() {
  474.         NSNotificationCenter.defaultCenter().addObserver(self, selector: "gotNewConnections", name: "gotNewConnections", object: nil)
  475.         NSNotificationCenter.defaultCenter().addObserver(self, selector: "openingProfile", name: "openingProfile", object: nil)
  476.         NSNotificationCenter.defaultCenter().addObserver(self, selector: "applicationBecameActive", name: "applicationBecameActive", object: nil)
  477.         NSNotificationCenter.defaultCenter().addObserver(self, selector: "updatedConnection", name: "updatedConnection", object: nil)
  478.         NSNotificationCenter.defaultCenter().addObserver(self, selector: "chatOpen", name: "chatOpen", object: nil)
  479.         NSNotificationCenter.defaultCenter().addObserver(self, selector: "chatClosed", name: "chatClosed", object: nil)
  480.         NSNotificationCenter.defaultCenter().addObserver(self, selector: "changeBackgroundColor:", name: "changeBackgroundColor", object: nil)
  481.         NSNotificationCenter.defaultCenter().addObserver(self, selector: "pageContentShown:", name: "pageContentShown", object: nil)
  482.         NSNotificationCenter.defaultCenter().addObserver(self, selector: "animateAlpha:", name: "animateAlpha", object: nil)
  483.         NSNotificationCenter.defaultCenter().addObserver(self, selector: "changeAlpha:", name: "changeAlpha", object: nil)
  484.         NSNotificationCenter.defaultCenter().addObserver(self, selector: "gotToken:", name: "GotDeviceID", object: nil)
  485.         NSNotificationCenter.defaultCenter().addObserver(self, selector: "didTapLogout", name: "didTapLogout", object: nil)
  486.         NSNotificationCenter.defaultCenter().addObserver(self, selector: "updatedConnectionProfile:", name: "updatedConnectionProfile", object: nil)
  487.     }
  488.    
  489.     func gotNewConnections() {
  490.         print("Got New Connections")
  491.         dispatch_async(dispatch_get_main_queue()) { () -> Void in
  492.             if ConnectionsManager.SharedInstance.connections.count == 0 {
  493.                 self.noConnectionsView.alpha = 1.0
  494.             } else {
  495.                 self.noConnectionsView.alpha = 0.0
  496.             }
  497.        
  498.             self.reset()
  499.         }
  500.        
  501.     }
  502.    
  503.     func applicationBecameActive() {
  504.     }
  505.    
  506.     override func viewWillDisappear(animated: Bool) {
  507.         activityIndicator.stopAnimating()
  508.         UIApplication.sharedApplication().endIgnoringInteractionEvents()
  509.         super.viewWillDisappear(animated)
  510.     }
  511.    
  512.    
  513.     override func viewWillAppear(animated: Bool) {
  514.         if(UserManager.SharedInstance.user == nil) {
  515.             return
  516.         }
  517.        
  518.         if !hasOpenedProfile {
  519.             let connections = ConnectionsManager.SharedInstance.connections
  520.             if connections.count == 0 {
  521.                 self.noConnectionsView.alpha = 1.0
  522.                
  523.             } else {
  524.                 dispatch_async(dispatch_get_main_queue(), { () -> Void in
  525.                     self.reset()
  526.                     self.carousel.scrollToItemAtIndex(0, animated: true)
  527.                 })
  528.             }
  529.             if ConnectionsManager.SharedInstance.connections.count == 0 {
  530.                 self.noConnectionsView.alpha = 1.0
  531.             } else {
  532.                 self.noConnectionsView.alpha = 0.0
  533.             }
  534.         }
  535.        
  536.        
  537.         super.viewWillAppear(animated)
  538.        
  539.     }
  540.    
  541.     override func viewDidAppear(animated: Bool) {
  542.         super.viewDidAppear(animated)
  543.         if(UserManager.SharedInstance.user == nil) {
  544.             return
  545.         }
  546.         if !hasOpenedProfile {
  547.             self.carousel.scrollToItemAtIndex(currentPageIndex, animated: true)
  548.             selectAvatarButton(currentPageIndex)
  549.         } else {
  550.             hasOpenedProfile = false
  551.         }
  552.     }
  553.    
  554.     func changeBackgroundColor(notification: NSNotification) {
  555.         self.mainViewOutlet.backgroundColor = notification.object as? UIColor
  556.     }
  557.  
  558.     func didTapLogout() {
  559.         hasOpenedProfile = false
  560.     }
  561.    
  562.     func updatedConnection() {
  563.         dispatch_async(dispatch_get_main_queue()) { () -> Void in
  564.             self.reset()
  565.         }
  566.         self.carousel.scrollToItemAtIndex(currentPageIndex, animated: true)
  567.         selectAvatarButton(currentPageIndex)
  568.     }
  569.    
  570.     func pageContentShown(notification: NSNotification) {
  571.        
  572.         let index = notification.object as! Int
  573.         self.currentPageIndex = index
  574.         self.carousel.scrollToItemAtIndex(index, animated: true)
  575.     }
  576.    
  577.     func chatOpen() {
  578.         self.isChatOpen = true
  579.         for v in self.pageViewController!.view.subviews {
  580.             if let sub = v as? UIScrollView {
  581.                 sub.scrollEnabled = false
  582.             }
  583.         }
  584.     }
  585.    
  586.     func chatClosed() {
  587.         self.isChatOpen = false
  588.         for v in self.pageViewController!.view.subviews {
  589.             if let sub = v as? UIScrollView {
  590.                 sub.scrollEnabled = true
  591.             }
  592.         }
  593.     }
  594.    
  595.     func openingProfile() {
  596.         hasOpenedProfile = true
  597.     }
  598.    
  599.     func updatedConnectionProfile(notification: NSNotification) {
  600.         carousel.reloadData()
  601.     }
  602.    
  603. }
  604.  
  605. extension UIDashboardViewController: UIPageViewControllerDelegate, UIPageViewControllerDataSource {
  606.    
  607.     func pageViewController(pageViewController: UIPageViewController, viewControllerAfterViewController viewController: UIViewController) -> UIViewController? {
  608.  
  609.         var index = currentPageIndex
  610.         index++
  611.         if(index >= ConnectionsManager.SharedInstance.connections.count){
  612.             return nil
  613.         }
  614.         return self.viewControllerAtIndex(index)
  615.     }
  616.    
  617.     func pageViewController(pageViewController: UIPageViewController, viewControllerBeforeViewController viewController: UIViewController) -> UIViewController? {
  618.  
  619.         var index = currentPageIndex
  620.         if(index <= 0){
  621.             return nil
  622.         }
  623.        
  624.         index--
  625.        
  626.         return self.viewControllerAtIndex(index)
  627.     }
  628.    
  629.     func pageViewController(pageViewController: UIPageViewController, willTransitionToViewControllers pendingViewControllers: [UIViewController]) {
  630.         pageVCinAnimation = true
  631.     }
  632.    
  633.     func pageViewController(pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool) {
  634.         pageVCinAnimation = false
  635.     }
  636.    
  637. }
  638.  
  639. extension UIDashboardViewController: UIScrollViewDelegate {
  640.    
  641.     func scrollViewDidScroll(scrollView: UIScrollView) {
  642.        
  643.         if 0 == currentPageIndex && scrollView.contentOffset.x < scrollView.bounds.size.width {
  644.             scrollView.contentOffset = CGPointMake(scrollView.bounds.size.width, 0)
  645.         }
  646.         if currentPageIndex == (ConnectionsManager.SharedInstance.connections.count - 1) && scrollView.contentOffset.x > scrollView.bounds.size.width {
  647.             scrollView.contentOffset = CGPointMake(scrollView.bounds.size.width, 0)
  648.         }
  649.     }
  650.    
  651.     func scrollViewWillEndDragging(scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
  652.         if 0 == currentPageIndex && scrollView.contentOffset.x <= scrollView.bounds.size.width {
  653.             scrollView.contentOffset = CGPointMake(scrollView.bounds.size.width, 0)
  654.         }
  655.         if currentPageIndex == (ConnectionsManager.SharedInstance.connections.count - 1) && scrollView.contentOffset.x >= scrollView.bounds.size.width {
  656.             scrollView.contentOffset = CGPointMake(scrollView.bounds.size.width, 0)
  657.         }
  658.     }
  659.    
  660. }
  661.  
  662. extension UIDashboardViewController: iCarouselDelegate, iCarouselDataSource {
  663.  
  664.     func numberOfItemsInCarousel(carousel: iCarousel!) -> Int {
  665.         print("Number of items in the carousel: \(ConnectionsManager.SharedInstance.connections.count)")
  666.         return ConnectionsManager.SharedInstance.connections.count
  667.     }
  668.    
  669.     func carousel(carousel: iCarousel!, didSelectItemAtIndex index: Int) {
  670.         self.selectAvatarButton(index)
  671.         self.slideToPage(index, completion: nil)
  672.  
  673.        
  674.     }
  675.    
  676.  
  677.     func carouselDidEndDragging(carousel: iCarousel!, willDecelerate decelerate: Bool) {
  678.        
  679.         let index = carousel.currentItemIndex
  680.         self.selectAvatarButton(index)
  681.         self.slideToPage(index, completion: nil)
  682.     }
  683.    
  684.    
  685.    
  686.     func carouselCurrentItemIndexDidChange(carousel: iCarousel!) {
  687.         let index = carousel.currentItemIndex
  688.         self.selectAvatarButton(index)
  689.        
  690.        
  691.         //is new connection have unread message, if so disable indicator
  692.         avatarButtons[index].setUnreadMessageIndicator(false)
  693.         self.setCurrentConnectionTimestamp()
  694.        
  695.     }
  696.    
  697.    
  698.     func setCurrentConnectionTimestamp() {
  699.         //set timestamp
  700.         let connection = ConnectionsManager.SharedInstance.connections[carousel!.currentItemIndex]
  701.         ChatManager.SharedInstance.setMyTimestamp(connection.connection_id)
  702.        
  703.     }
  704.    
  705.    
  706.    
  707.     func carouselDidEndDecelerating(carousel: iCarousel!) {
  708.        
  709.     }
  710.    
  711.     func carousel(carousel: iCarousel!, viewForItemAtIndex index: Int, reusingView view: UIView!) -> UIView! {
  712.         if UserManager.SharedInstance.user == nil {
  713.             return UIView()
  714.         }
  715.        
  716.         var b = view
  717.         if let v = view as? UIButton {
  718.             b = v
  719. //            for sub in view.subviews {
  720. //                sub.removeFromSuperview()
  721. //            }
  722. //            view.removeFromSuperview()
  723.         } else {
  724.             print("view is nil")
  725.         }
  726.         if index < ConnectionsManager.SharedInstance.connections.count {
  727. //            var avatarButtons: [CarouselButton] = Array(self.avatarSet)
  728. //            avatarButtons.sortInPlace({($0.index < $1.index) })
  729.            
  730.            
  731.            
  732.             let profile = ConnectionsManager.SharedInstance.connections[index]
  733.             let avatar = profile.avatar
  734.             b = UIButton(frame: CGRectMake(0, 0, 44, 44))
  735.             for a in avatarButtons {
  736.                 if a.index == index {
  737.                     b = a.avatarButton
  738.                 }
  739.             }
  740.             let avatarButton = b as! UIButton
  741.             let avatarImage = FileManager.SharedInstance.getImageFromDisk(avatar.imagePath!)
  742.             if avatarImage != nil {
  743.                 avatarButton.setImage(avatarImage!.mask(UIImage(named: "dashboardAvatarMask")!), forState: .Normal)
  744.             }
  745.             b = avatarButton
  746.             let carouselButton = CarouselButton()
  747.             carouselButton.index = index
  748.             carouselButton.avatarButton = b as! UIButton
  749.             self.avatarSet.insert(carouselButton)
  750.            
  751.             self.view.layoutIfNeeded()
  752.             avatarButtons[index].setUnreadMessageIndicator(true)
  753.            
  754.         }
  755.         return b
  756.  
  757.     }
  758.    
  759.  
  760.    
  761.     func carousel(carousel: iCarousel!, valueForOption option: iCarouselOption, withDefault value: CGFloat) -> CGFloat {
  762.         if (option == .Spacing) {
  763.             return value * 1.1
  764.         }
  765.         return value
  766.     }
  767.    
  768. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement