Resolved UIActivityIndicatorView Not Showing

Discussion in 'iOS Programming' started by RagingGoat, Oct 21, 2014.

  1. RagingGoat, Oct 21, 2014
    Last edited: Oct 21, 2014

    RagingGoat macrumors 6502

    Joined:
    Jun 21, 2010
    #1
    I have a table view that loads data from JSON. I am trying to get an activity indicator working but it never appears. What am I missing?

    Code:
    #define kBgQueue dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
    #define storeURL [NSURL URLWithString: @"https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&maxResults=25&playlistId=PL9DC706DCCCE00188&key=AIzaSyBS4do208_KPGHAhszfVkHadSvtfSgr7Mo"]
    
    #import "BBYoutubeVideosTableViewController.h"
    #import "Reachability.h"
    #import "TSMessage.h"
    #import "TSMessageView.h"
    #import "YoutubeCell.h"
    #import "KFBYoutubeVideoView.h"
    #import "KFBAppDelegate.h"
    
    @interface BBYoutubeVideosTableViewController ()
    {
        UIActivityIndicatorView *loadingIndicator;
    }
    
    @end
    
    @implementation BBYoutubeVideosTableViewController
    @synthesize title, videoID, thumbURL, descriptionString, url, titleArray, videoIDArray, thumbArray, descriptionArray;
    
    - (id)initWithStyle:(UITableViewStyle)style
    {
        self = [super initWithStyle:style];
        if (self) {
            
        }
        return self;
    }
    
    - (void)viewDidLoad
    {
        [super viewDidLoad];
        
        self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStylePlain target:nil action:nil];
        
        UIImageView *backgroundImage = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"plain_app-background.png"]];
        
        CGFloat width = [[UIScreen mainScreen]bounds].size.width;
        CGFloat height = [[UIScreen mainScreen]bounds].size.height;
        
        if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone)
        {
            loadingIndicator = [[UIActivityIndicatorView alloc]initWithFrame:CGRectMake(width / 2, height / 2, 37, 37)];
            loadingIndicator.center = CGPointMake(width / 2, height / 2 - 37);
        }
        else
        {
            loadingIndicator = [[UIActivityIndicatorView alloc]initWithFrame:CGRectMake(142, 365, 37, 37)];
        }
        
        loadingIndicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyleGray;
        loadingIndicator.hidesWhenStopped = YES;
        
        Reachability *networkReachability = [Reachability reachabilityForInternetConnection];
        NetworkStatus networkStatus = [networkReachability currentReachabilityStatus];
        
        if(networkStatus == NotReachable)
        {
            [TSMessage showNotificationWithTitle:@"Network Error" subtitle:@"No active network connection!" type:TSMessageNotificationTypeError];
        }
        else {
            [self.tableView addSubview:loadingIndicator];
            [loadingIndicator startAnimating];
        }
        
        self.title = @"Bluegrass & Backroads";
        
        self.tableView = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        self.tableView.backgroundView = backgroundImage;
        
        url = [NSURL URLWithString:@"https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&maxResults=25&playlistId=PL9DC706DCCCE00188&key=AIzaSyBS4do208_KPGHAhszfVkHadSvtfSgr7Mo"];
        
        dispatch_async(kBgQueue, ^{
            NSData *data = [NSData dataWithContentsOfURL:url];
            if (data == nil)
            {
                NSLog(@"data is nil");
            }
            else
            {
                [self performSelectorOnMainThread:@selector(fetchedData:) withObject:data waitUntilDone:YES];
            }
        });
    }
    
    - (void)viewDidDisappear:(BOOL)animated
    {
        [loadingIndicator stopAnimating];
    }
    
    - (void)fetchedData:(NSData *)responseData
    {
        NSError *error;
        titleArray = [[NSMutableArray alloc]init];
        videoIDArray = [[NSMutableArray alloc]init];
        thumbArray = [[NSMutableArray alloc]init];
        descriptionArray = [[NSMutableArray alloc]init];
        
        NSDictionary *json = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
        NSArray *items = [json objectForKey:@"items"];
        
        for (NSDictionary *item in items)
        {
            NSDictionary *snippet = [item objectForKey:@"snippet"];
            title = [snippet objectForKey:@"title"];
            videoID = [[snippet objectForKey:@"resourceId"] objectForKey:@"videoId"];
            thumbURL = [[[snippet objectForKey:@"thumbnails"] objectForKey:@"default"] objectForKey:@"url"];
            descriptionString = [snippet objectForKey:@"description"];
            
            [titleArray addObject:title];
            [videoIDArray addObject:videoID];
            UIImage *thumbnailImage = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:thumbURL]]];
            [thumbArray addObject:thumbnailImage];
            [descriptionArray addObject:descriptionString];
        }
        
        [self.tableView reloadData];
        
        [loadingIndicator stopAnimating];
    }
    
    - (IBAction)morePressed:(id)sender
    {
        NSURL *kyfbVideos = [NSURL URLWithString:@"https://www.youtube.com/playlist?list=PL9DC706DCCCE00188"];
        [[UIApplication sharedApplication] openURL:kyfbVideos];
    }
    
    - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
    {
        return 1;
    }
    
    - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
    {
        return [titleArray count];
    }
    
    - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
    {
        return 215;
    }
    
    - (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
    {
        return 60;
    }
    
    - (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
    {
        UIColor *kfbBlue = [UIColor colorWithRed:8.0/255.0f green:77.0/255.0f blue:139.0/255.0f alpha:1];
        
        UIView *footerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, tableView.frame.size.width, tableView.frame.size.height)];
        footerView.backgroundColor = [UIColor clearColor];
        
        CGFloat width = footerView.frame.size.width;
        
        UIButton *moreButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        moreButton.backgroundColor = [UIColor clearColor];
        [moreButton setTitle:@"More" forState:UIControlStateNormal];
        [moreButton setTitleColor:kfbBlue forState:UIControlStateNormal];
        moreButton.titleLabel.textAlignment = NSTextAlignmentCenter;
        moreButton.titleLabel.font = [UIFont fontWithName:@"FranklinGothicStd-ExtraCond" size:25.0];
        moreButton.frame = CGRectMake(width / 2 - 25, 0, 50, 50);
        moreButton.layer.cornerRadius = 25.0;
        moreButton.layer.borderWidth = 2.0f;
        moreButton.layer.borderColor = kfbBlue.CGColor;
        moreButton.clipsToBounds = YES;
        moreButton.backgroundColor = [UIColor clearColor];
        [moreButton addTarget:self action:@selector(morePressed:) forControlEvents:UIControlEventTouchUpInside];
        [footerView addSubview:moreButton];
        return footerView;
    }
    
    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
    {
        UIColor *kfbBlue = [UIColor colorWithRed:8.0/255.0f green:77.0/255.0f blue:139.0/255.0f alpha:1];
        
        YoutubeCell *cell = [tableView dequeueReusableCellWithIdentifier:@"youtubeCell"];
        if (!cell)
        {
            NSArray *nibs =[[NSBundle mainBundle] loadNibNamed:@"YoutubeCell" owner:self options:NULL];
            cell = [nibs firstObject];
        }
        cell.videoTitle.text = [titleArray objectAtIndex:indexPath.row];
        cell.videoDescription.text = [descriptionArray objectAtIndex:indexPath.row];
        cell.videoThumbnail.image = [thumbArray objectAtIndex:indexPath.row];
        
        cell.videoTitle.textColor = kfbBlue;
        cell.videoDescription.textColor = kfbBlue;
        cell.videoTitle.font = [UIFont fontWithName:@"FranklinGothicStd-ExtraCond" size:22.0];
        cell.videoDescription.font = [UIFont fontWithName:@"FranklinGothicStd-ExtraCond" size:16.0];
        cell.backgroundColor = [UIColor clearColor];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        return cell;
    }
    
    - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
    {
        if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone)
        {
            KFBYoutubeVideoView *videoView = [[KFBYoutubeVideoView alloc]init];
            videoView.videoIDString = [videoIDArray objectAtIndex:indexPath.row];
            videoView.videoTitle = [titleArray objectAtIndex:indexPath.row];
            videoView.videoDescription = [descriptionArray objectAtIndex:indexPath.row];
            [self.navigationController pushViewController:videoView animated:YES];
        }
        else
        {
            KFBYoutubeVideoView *videoView = [[KFBYoutubeVideoView alloc]initWithNibName:nil bundle:nil];
            videoView.videoIDString = [videoIDArray objectAtIndex:indexPath.row];
            videoView.videoTitle = [titleArray objectAtIndex:indexPath.row];
            videoView.videoDescription = [descriptionArray objectAtIndex:indexPath.row];
            
            NSMutableArray *details = [self.splitViewController.viewControllers mutableCopy];
            
            UINavigationController *detailNav = [[UINavigationController alloc]initWithRootViewController:videoView];
            
            [details replaceObjectAtIndex:1 withObject:detailNav];
            
            KFBAppDelegate *appDelegate = (KFBAppDelegate *)[[UIApplication sharedApplication]delegate];
            appDelegate.splitViewController.viewControllers = details;
            appDelegate.window.rootViewController = self.splitViewController;
            appDelegate.splitViewController.delegate = videoView;
            [appDelegate.splitViewController viewWillAppear:YES];
        }
        
        [tableView deselectRowAtIndexPath:indexPath animated:YES];
    }
    
    - (void)didReceiveMemoryWarning
    {
        [super didReceiveMemoryWarning];
        // Dispose of any resources that can be recreated.
    }
    
    @end
    
    
     
  2. dejo Moderator

    dejo

    Staff Member

    Joined:
    Sep 2, 2004
    Location:
    The Centennial State
    #2
    What is the value of self.tableView when the following line executes?:
    Code:
    [self.tableView addSubview:loadingIndicator];
    I suggest putting in a breakpoint at this line and using the debugger to examine its value.
     
  3. RagingGoat thread starter macrumors 6502

    Joined:
    Jun 21, 2010
    #3
    This is self.tableView.

    Code:
    self.tableView: <UITableView: 0x7f86ec827200; frame = (0 20; 320 548); clipsToBounds = YES; autoresize = W+H; gestureRecognizers = <NSArray: 0x7f86ec0265c0>; layer = <CALayer: 0x7f86ec03e410>; contentOffset: {0, 0}; contentSize: {0, 0}>
    
     
  4. dejo Moderator

    dejo

    Staff Member

    Joined:
    Sep 2, 2004
    Location:
    The Centennial State
    #4
    And what happens to self.tableView very soon after that line?
     
  5. RagingGoat thread starter macrumors 6502

    Joined:
    Jun 21, 2010
    #5
    Ah! I feel so dumb not noticing it being initialized afterwards.
     

Share This Page