networkActivityIndicatorVisible - iphone

Is this code correct to use with the networkActivityIndicatorVisible?
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
UIApplication* app2 = [UIApplication sharedApplication];
app2.networkActivityIndicatorVisible = YES;
[self loadSources]; // Loads data in table view
app2.networkActivityIndicatorVisible = NO;
}
Teo

Since NetworkActivityIndicatorVisible can be set from several points while a connection is still active, you need to track the number of calls that enable/disable it. The following UIApplication category does just that using a static variable:
// file UIApplication+NetworkActivity.h
#interface UIApplication (NetworkActivity)
- (void)showNetworkActivityIndicator;
- (void)hideNetworkActivityIndicator;
#end
// file UIApplication+NetworkActivity.m
#import "UIApplication+NetworkActivity.h"
static NSInteger activityCount = 0;
#implementation UIApplication (NetworkActivity)
- (void)showNetworkActivityIndicator {
if ([[UIApplication sharedApplication] isStatusBarHidden]) return;
#synchronized ([UIApplication sharedApplication]) {
if (activityCount == 0) {
[self setNetworkActivityIndicatorVisible:YES];
}
activityCount++;
}
}
- (void)hideNetworkActivityIndicator {
if ([[UIApplication sharedApplication] isStatusBarHidden]) return;
#synchronized ([UIApplication sharedApplication]) {
activityCount--;
if (activityCount <= 0) {
[self setNetworkActivityIndicatorVisible:NO];
activityCount=0;
}
}
}
#end
Now import UIApplication+NetworkActivity.h in your client code and call
// on connection started:
[[UIApplication sharedApplication] showNetworkActivityIndicator];
// on connection finished:
[[UIApplication sharedApplication] hideNetworkActivityIndicator];
If your concern is that the indicator blinks for only a second, you don't need a background process. Just call [self performSelector:#selector(loadSources) withObject:Nil afterDelay:0.1] so the UI thread has time to start the network indicator animation before you block the main thread.

If you're not using AFNetworking (https://github.com/AFNetworking/AFNetworking) already you can check out their network activity indicator implementation in AFNetworkingActivityIndicatorManager.
If you do choose to use this library for your network access, they handle the network activity indicator for you automatically. All you need to do is make one call in your AppDelegate to set it up, they do the rest of the work for you.
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
[[AFNetworkActivityIndicatorManager sharedManager] setEnabled:YES];
}

An shorter solution for tracking multiple activities - again using a UIApplication category and a static variable:
#interface UIApplication (NetworkActivityIndicator)
- (void)toggleNetworkActivityIndicatorVisible:(BOOL)visible;
#end
#implementation UIApplication (NetworkActivityIndicator)
-(void)toggleNetworkActivityIndicatorVisible:(BOOL)visible {
static int activityCount = 0;
#synchronized (self) {
visible ? activityCount++ : activityCount--;
self.networkActivityIndicatorVisible = activityCount > 0;
}
}
#end

I finally solved it. I used performSelectorInBackground to execute the load data into tableView
-(void)beginLoadSources {
[self loadSources]; // Loads data in table view
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
}
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
[self performSelectorInBackground:#selector(beginLoadSources) withObject:nil];
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
}

Use thins code in your ExempleUIWebView.m
before - (void)viewDidLoad
(void)webViewDidFinishLoad:(UIWebView *)webView {
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
[ProgressHUD dismiss];
}
and use this after - (void)viewDidLoad
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
[ProgressHUD show:#"Loading Privacy Policy" Interaction:NO];

Related

Stop Activity Indicator in Status Bar?

I'm near completing my application, but I'm running into an issue. Obviously, my web view needs an activity indicator for the app to be accepted. I have the following already:
- (void)viewDidLoad
{
[webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:#""]]]; // I removed the website for privacy's sake
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
}
Problem is that it won't stop spinning when I need it to (i.e. even after the page is loaded, it doesn't stop)
Any suggestions? Any help is appreciated!
Implement the UIWebViewDelegate in your class file that holds the UIWebView, and insert the following two methods:
- (void)webViewDidStartLoad:(UIWebView *)webView
- (void)webViewDidFinishLoad:(UIWebView *)webView
In the start method, place your:
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
... and in the finish, place:
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
Hope this helps!
In the web views delegate you can do:
- (void)webViewDidFinishLoad:(UIWebView *)webView {
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
}
you need to call
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
to get it to stop

-[UINavigationController pushViewController:animated:] crashes with no error in console

Update
I swapped out completely different code for pushViewController, and it is still crashing... seems like pushViewController is not the culprit. Here is what I added instead:
NSString *videoURL = [[NSString alloc] initWithFormat:#"http://www.vimeo.com/m/#/%#", videoID];
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:videoURL]];
It opens up the URL in Safari, and then crashes.. wtf?
PushViewController crashes with no error in the console, but I do get an EXC_BAD_ACCESS error in Xcode. The crash doesn't happen until after the view controller has been pushed... but the view its pushing is empty... no code to mess up.
My code is below:
MainViewController.m
PlayVimeo *playTest = [[PlayVimeo alloc] initWithNibName:#"PlayVimeo" bundle:nil];
//playTest.videoID = videoID;
[self.navigationController pushViewController:playTest animated:YES];
[playTest release];
PlayVimeo.m
#import "PlayVimeo.h"
#import "SVProgressHUD.h"
#implementation PlayVimeo
#synthesize videoID, wView;
-(void)viewDidLoad {
[super viewDidLoad];
//Show loading alert
[SVProgressHUD showInView:self.view status:#"Loading Video..."];
}
-(void)viewWillAppear:(BOOL)animated {
NSLog(#"Play View Loaded!");
[self vimeoVideo];
}
-(void)vimeoVideo {
NSLog(#"Video ID: %#", videoID);
NSString *html = [NSString stringWithFormat:#"<html>"
#"<head>"
#"<meta name = \"viewport\" content =\"initial-scale = 1.0, user-scalable = no, width = 460\"/></head>"
#"<frameset border=\"0\">"
#"<frame src=\"http://player.vimeo.com/video/%#?title=0&byline=0&portrait=1&autoplay=1\" width=\"460\" height=\"320\" frameborder=\"0\"></frame>"
#"</frameset>"
#"</html>",
videoID];
NSLog(#"HTML String: %#", html);
[wView loadHTMLString:html baseURL:[NSURL URLWithString:#""]];
//Dismiss loading alert
[SVProgressHUD dismissWithSuccess:#"Playing..."];
}
- (void)viewDidUnload {
[super viewDidUnload];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
return (interfaceOrientation == UIInterfaceOrientationLandscapeLeft || interfaceOrientation == UIInterfaceOrientationLandscapeRight);
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
-(void)dealloc {
[super dealloc];
}
Navigation Controller Code:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
self.window.rootViewController = self.navigationController;
[self.window makeKeyAndVisible];
[Appirater appLaunched];
return YES;
}
Console on crash:
sharedlibrary apply-load-rules all
Current language: auto; currently objective-c
(gdb)
It's likely that the culprit is
[playTest release];
Without seeing the rest of your code, I would still say that you likely need to release this after you're done with the video.
The code can not be fixed, it seems. With the UIWebView class reference, there is an example program TransWeb. Take this as base, it has a window and a navigation controller with a webview in it (in the xib). In MyViewController it reads a html-file and displays it. What you need to do is to change the main view to landscape and replace the html-code with yours. Avoid the frame-stuff.

Intercept URL and opening URL in Safari

I have intercepted URL opening by doing the following:
- (BOOL)openURL:(NSURL *)url{
URLViewController * web = [[URLViewController alloc] init];
web.url = url;
UINavigationController * nav = [[UINavigationController alloc] initWithRootViewController:web];
[nav.navigationBar setTintColor:[UIColor blackColor]];
[nav setModalPresentationStyle:UIModalPresentationFormSheet];
[self.detailViewController presentModalViewController:nav animated:NO];
[web release];
[nav release];
return YES;
}
I have a UITextView in which detects URL and when clicking on the URL it opens up the link in a ModalViewController. Full detail on what's going on can be seen here. Now the issue is, what if I want to open a URL in safari, is it still possible?
You should add an override flag indicating whether you want to exercise control or not.
#interface MyApplication : UIApplication {
}
-(BOOL)openURL:(NSURL *)url withOverride:(BOOL)override;
#end
#implementation MyApplication
-(BOOL)openURL:(NSURL *)url withOverride:(BOOL)override {
if ( !override ) {
return [super openURL:url];
}
if ([self.delegate openURL:url]) {
return YES;
} else {
return [super openURL:url];
}
}
-(BOOL)openURL:(NSURL *)url{
return [self openURL:url withOverride:YES];
}
#end
So now all calls that you want to bypass can be sent like this.
[[MyApplication sharedApplication] openURL:url withOverride:NO];
Original Answer
This is what you should do. Put it before the return YES; statement.
if ( [super canOpenURL:aURL] ) {
return [super openURL:aURL];
}

AVplayer not showing in ScrollView after 2-3 times

I am adding multiple AVPlayer objects in a scrollview. For the first time this is working fine but as i go back to my previous view and come back again i am not able to see AVPlayer objects in scrollView.
I need as matrix of multiple AVPlayer to show thumbnails of my videos.
Please help me asap
Thanks in advance.
I had a similar problem and after a lot of searching discovered that the AVPLayerItem object causes this issue.
Basically when the AVPlayer items go offscreen you need to make sure everything is released properly, and then recreate everything when they come back on screen.
As part of the release process, include the line:
[AVPlayer replaceCurrentItemWithPlayerItem:nil];
That sorted a very similar issue for me.
[AVPlayer replaceCurrentItemWithPlayerItem:nil];
also solves my problem of cannot releasing current player item immediately. (can't manually do that because it's retained by the class..)
Here's how you get 10 AVPlayers to play simultaneously, inside the same scrollView, each and every time you scroll it:
//
// ViewController.m
// VideoWall
//
// Created by James Alan Bush on 6/13/16.
// Copyright © 2016 James Alan Bush. All rights reserved.
//
#import "ViewController.h"
#import "AppDelegate.h"
static NSString *kCellIdentifier = #"Cell Identifier";
#interface ViewController () {
dispatch_queue_t dispatchQueueLocal;
}
#end
#implementation ViewController
- (id)initWithCollectionViewLayout:(UICollectionViewFlowLayout *)layout
{
if (self = [super initWithCollectionViewLayout:layout])
{
[self.collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:kCellIdentifier];
dispatchQueueLocal = dispatch_queue_create( "local session queue", DISPATCH_QUEUE_CONCURRENT );
}
return self;
}
- (void)viewDidLoad {
[super viewDidLoad];
[self.collectionView setDataSource:self];
[self.collectionView setContentSize:CGSizeMake(AppDelegate.sharedAppDelegate.width, AppDelegate.sharedAppDelegate.height)];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
- (void)dealloc {
[super dealloc];
}
#pragma mark <UICollectionViewDataSource>
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
return 1;
}
#pragma mark - UICollectionViewDataSource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
return AppDelegate.sharedAppDelegate.assetsFetchResults.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
UICollectionViewCell *cell = (UICollectionViewCell *)[collectionView dequeueReusableCellWithReuseIdentifier:kCellIdentifier forIndexPath:indexPath];
[CATransaction begin];
[CATransaction setCompletionBlock:^{
cell.contentView.layer.sublayers = nil;
dispatch_release(dispatchQueueLocal);
}];
dispatch_retain(dispatchQueueLocal);
dispatch_async( dispatchQueueLocal, ^{
[self drawPlayerLayerForCell:cell atIndexPath:indexPath];
});
[CATransaction commit];
return cell;
}
- (void)drawPlayerLayerForCell:(UICollectionViewCell *)cell atIndexPath:(NSIndexPath *)indexPath {
void (^drawPlayerLayer)(UICollectionViewCell*, NSIndexPath*) = ^(UICollectionViewCell* cell, NSIndexPath* indexPath) {
[AppDelegate.sharedAppDelegate.imageManager requestPlayerItemForVideo:AppDelegate.sharedAppDelegate.assetsFetchResults[indexPath.item] options:nil resultHandler:^(AVPlayerItem * _Nullable playerItem, NSDictionary * _Nullable info) {
dispatch_async(dispatch_get_main_queue(), ^{
if(![[info objectForKey:PHImageResultIsInCloudKey] boolValue]) {
AVPlayerLayer *playerLayer = [AVPlayerLayer playerLayerWithPlayer:[AVPlayer playerWithPlayerItem:playerItem]];
[playerLayer setVideoGravity:AVLayerVideoGravityResizeAspectFill];
[playerLayer setBorderColor:[UIColor whiteColor].CGColor];
[playerLayer setBorderWidth:1.0f];
[playerLayer setFrame:cell.contentView.bounds];
[cell.contentView.layer addSublayer:playerLayer];
[(AVPlayer *)playerLayer.player play];
} else {
[AppDelegate.sharedAppDelegate.imageManager requestImageForAsset:AppDelegate.sharedAppDelegate.assetsFetchResults[indexPath.item]
targetSize:CGSizeMake(AppDelegate.sharedAppDelegate.flowLayout.itemSize.width, AppDelegate.sharedAppDelegate.flowLayout.itemSize.height)
contentMode:PHImageContentModeAspectFill
options:nil
resultHandler:^(UIImage *result, NSDictionary *info) {
dispatch_async(dispatch_get_main_queue(), ^{
cell.contentView.layer.contents = (__bridge id)result.CGImage;
});
}];
}
});
}];
};
drawPlayerLayer(cell, indexPath);
}
#end
Here's the AppDelegate implementation file:
//
// AppDelegate.m
// VideoWall
//
// Created by James Alan Bush on 6/13/16.
// Copyright © 2016 James Alan Bush. All rights reserved.
//
#import "AppDelegate.h"
#import "ViewController.h"
#implementation AppDelegate
+ (AppDelegate *)sharedAppDelegate
{
return (AppDelegate *)[[UIApplication sharedApplication] delegate];
}
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch
self.width = [[UIScreen mainScreen] bounds].size.width / 2.0;
self.height = [[UIScreen mainScreen] bounds].size.height / 4.0;
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
self.window.rootViewController = [self viewController];
self.window.rootViewController.view = self.viewController.view;
[self.window makeKeyAndVisible];
return YES;
}
- (ViewController *)viewController {
ViewController *c = self->_viewController;
if (!c) {
c = [[ViewController alloc] initWithCollectionViewLayout:[self flowLayout]];
[c.view setFrame:[[UIScreen mainScreen] bounds]];
self->_viewController = c;
}
return c;
}
- (UICollectionViewFlowLayout *)flowLayout {
UICollectionViewFlowLayout *v = self->_flowLayout;
if (!v) {
v = [UICollectionViewFlowLayout new];
[v setItemSize:CGSizeMake(AppDelegate.sharedAppDelegate.width, AppDelegate.sharedAppDelegate.height)];
[v setSectionInset:UIEdgeInsetsMake(0.0, 0.0, 0.0, 0.0)];
[v setMinimumLineSpacing:0.0];
[v setMinimumInteritemSpacing:0.0];
[v setEstimatedItemSize:CGSizeMake(AppDelegate.sharedAppDelegate.width, AppDelegate.sharedAppDelegate.height)];
self->_flowLayout = v;
}
return v;
}
- (PHCachingImageManager *)imageManager {
PHCachingImageManager *i = self->_imageManager;
if (!i) {
i = [[PHCachingImageManager alloc] init];
self->_imageManager = i;
}
return i;
}
- (PHFetchResult *)assetsFetchResults {
PHFetchResult *i = self->_assetsFetchResults;
if (!i) {
PHFetchResult *smartAlbums = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeSmartAlbum subtype:PHAssetCollectionSubtypeSmartAlbumVideos options:nil];
PHAssetCollection *collection = smartAlbums.firstObject;
if (![collection isKindOfClass:[PHAssetCollection class]])
return nil;
PHFetchOptions *allPhotosOptions = [[PHFetchOptions alloc] init];
allPhotosOptions.sortDescriptors = #[[NSSortDescriptor sortDescriptorWithKey:#"creationDate" ascending:NO]];
i = [PHAsset fetchAssetsInAssetCollection:collection options:allPhotosOptions];
self->_assetsFetchResults = i;
}
return i;
}
- (void)applicationWillResignActive:(UIApplication *)application {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
- (void)applicationDidEnterBackground:(UIApplication *)application {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
- (void)applicationWillEnterForeground:(UIApplication *)application {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
- (void)applicationDidBecomeActive:(UIApplication *)application {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
- (void)applicationWillTerminate:(UIApplication *)application {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
#end
These are the only two files you need; no NIB/XIB.

Setting UIActivityIndicatorView while view is prepared

I have a UITabbBarController with a UITableView. Under certain circumstances the TabBarControllers dataset requires updating when a user arrives from another view,
e.g. the initial load when the TabBarController is called the first time, or when the settings are changed.
This dataset update takes about 2 seconds and I want to show an UIActivityIndicatorView.
Trouble is that when I enter from another view I don't know which view to attach it to, since the loading of the tabbarController is carried out in the viewWillAppear method.
Any clues how I can go about this?
I've done this sort of thing in the viewDidAppear method. My code kicks off a background task to load the data from a url. It also hands the background task a selector of a method to call on the controller when it is done. That way the controller is notified that the data has been downloaded and can refresh.
I don't know if this is the best way to do this, but so far it's working fine for me :-)
To give some more details, in addition to the selector of the method to call when the background task has loaded the data, I also and it a selector of a method on the controller which does the loading. That way the background task manages whats going on, but the view controller provides the data specific code.
Here's there viewDidAppear code:
- (void) viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
if (reloadData) {
BackgroundTask *task = [[BackgroundTask alloc] initWithMethod:#selector(loadData) onObject:self];
task.superView = self.view.superview;
task.notifyWhenFinishedMethod = #selector(loadFinished);
[task start];
[task release];
}
}
The background task has an optional superView because it will add a new UIView to it containing an activity indicator.
BackgroundTask.m looks like this:
#implementation BackgroundTask
#synthesize superView;
#synthesize longRunningMethod;
#synthesize notifyWhenFinishedMethod;
#synthesize obj;
- (BackgroundTask *) initWithMethod:(SEL)aLongRunningMethod onObject:(id)aObj {
self = [super init];
if (self != nil) {
self.longRunningMethod = aLongRunningMethod;
self.obj = aObj;
}
return self;
}
- (void) start {
// Fire into the background.
NSThread *thread = [[NSThread alloc] initWithTarget:self selector:#selector(execute:)object:nil];
thread.name = #"BackgroundTask thread";
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(taskFinished:) name:NSThreadWillExitNotification object:thread];
[thread start];
[thread release];
}
- (void) execute:(id)anObject {
// New thread = new pool.
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
if (self.superView != nil) {
busyIndicatorView = [[BusyIndicator alloc] initWithSuperview:self.superView];
[busyIndicatorView performSelectorOnMainThread:#selector(addToSuperView)withObject:nil waitUntilDone:YES];
}
// Do the work on this thread.
[self.obj performSelector:self.longRunningMethod];
if (self.superView != nil) {
[busyIndicatorView performSelectorOnMainThread:#selector(removeFromSuperView)withObject:nil waitUntilDone:YES];
}
[pool release];
}
- (void) taskFinished:(NSNotification *)notification {
[[NSNotificationCenter defaultCenter] removeObserver:self name:NSThreadWillExitNotification object:notification.object];
[self performSelectorOnMainThread:#selector(notifyObject)withObject:nil waitUntilDone:NO];
}
- (void) notifyObject {
// Tell the main thread we are done.
if (self.notifyWhenFinishedMethod != nil) {
[self.obj performSelectorOnMainThread:self.notifyWhenFinishedMethod withObject:nil waitUntilDone:NO];
}
}
- (void) dealloc {
self.notifyWhenFinishedMethod = nil;
self.superView = nil;
self.longRunningMethod = nil;
self.obj = nil;
[super dealloc];
}
#end
Finally as I said I put up a activity indicator. I have a xib which contains a 50% transparent blue background with an activity indicator in the middle. There is a controller for it which has this code:
#implementation BusyIndicator
#synthesize superView;
#synthesize busy;
- (BusyIndicator *) initWithSuperview:(UIView *)aSuperView {
self = [super initWithNibName:#"BusyIndicator" bundle:nil];
if (self != nil) {
self.superView = aSuperView;
}
return self;
}
- (void) addToSuperView {
// Adjust view size to match the superview.
[self.superView addSubview:self.view];
self.view.frame = CGRectMake(0,0, self.superView.frame.size.width, self.superView.frame.size.height);
//Set position of the indicator to the middle of the screen.
int top = (int)(self.view.frame.size.height - self.busy.frame.size.height) / 2;
self.busy.frame = CGRectMake(self.busy.frame.origin.x, top, self.busy.frame.size.width, self.busy.frame.size.height);
[self.busy startAnimating];
}
- (void) removeFromSuperView {
[self.busy stopAnimating];
[self.view removeFromSuperview];
}
- (void) dealloc {
self.superView = nil;
[super dealloc];
}
#end
Hoep this helps.