How to show alertview indicator before pulling json data( iOS6 ) - ios

Could any one please help me with this code i'm trying to call alertview indicator before pulling json data in my iOS app but i don't know how to check if the data already loaded and then disappear the alertview indicator, For now it always appears even all data aleady loaded. here is my code:
//
// Firstcine.m
//
//
//
//
#import "Firstcine.h"
#interface Firstcine (){
UIAlertView *loading;
}
#end
#implementation Firstcine
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Loading Show Alert View...
loading = [[UIAlertView alloc] initWithTitle:#"" message:#"Please Wait..."
delegate:nil cancelButtonTitle:nil otherButtonTitles:nil];
UIActivityIndicatorView *progress= [[UIActivityIndicatorView
alloc] initWithFrame:CGRectMake(125, 50, 30, 30)];
progress.activityIndicatorViewStyle = UIActivityIndicatorViewStyleWhiteLarge;
[loading addSubview:progress];
[progress startAnimating];
[loading show];
// dis play all data after first loaded
NSURL *url = [NSURL URLWithString:#"http://localhost/App/first.php"];
NSData *jsonData = [NSData dataWithContentsOfURL:url];
NSArray *json = [NSJSONSerialization JSONObjectWithData:
jsonData options:NSJSONReadingAllowFragments error:nil];
// Do any additional setup after loading the view.
self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:#"bg_tile.png"]];
NSDictionary *dict = [json objectAtIndex:0];
name.text = [dict valueForKey:#"name"];
time.text = [dict valueForKey:#"time"];
date.text = [dict valueForKey:#"date"];
price.text = [dict valueForKey:#"price"];
// then display photo
UIImageView *image = [[UIImageView alloc]initWithFrame:CGRectMake(75, 87, 150,200)];
image.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:
[NSURL URLWithString:[dict valueForKey:#"photo" ]]]];
[self.view addSubview:image];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end

Have you tried something like this
UIAlertView *alertView = [[UIAlertView alloc]
initWithTitle:#"Configuring Preferences\nPlease Wait..."
message:nil
delegate:nil
cancelButtonTitle:nil
otherButtonTitles:nil];
[alertView show];
UIActivityIndicatorView *indicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
indicator.center = CGPointMake(alertView.bounds.size.width / 2, alertView.bounds.size.height - 50);
[indicator startAnimating];
[alertView addSubview:indicator];
dispatch_queue_t downloadQueue = dispatch_queue_create("saver", NULL);
dispatch_async(downloadQueue, ^{
// do some heavy lifting ? like a fetch
dispatch_async(dispatch_get_main_queue(), ^{
// hide the view
[alertView dismissWithClickedButtonIndex:0 animated:YES];
});
});

Related

when Navigate the another page Need to add activity indicator

#import "LoginVC.h"
#import "HOMEVC.h"
#import "DashboardVC.h"
#interface LoginVC ()
#end
#implementation LoginVC
UIActivityIndicatorView *spinner ;
-(IBAction)login:(id)sender{
NSString *userUpdate =[NSString stringWithFormat:#"%#",[Usernamefileld text]];
NSString *userUpdate1 =[NSString stringWithFormat:#"%#",[PasswordField text]];
NSString *baseURL = [NSString stringWithFormat:#"http://192.168.1.200:8094/YazakiService.svc/LOGIN/%#/%#",userUpdate,userUpdate1];
NSURL *url = [NSURL URLWithString:[baseURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
NSURLResponse *response;
NSError *error;
NSData *responseData =[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSMutableArray *serviceResponse=[NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableContainers error:&error];
NSLog(#"got response==%#", serviceResponse);
NSDictionary *template=[serviceResponse objectAtIndex:0];
NSString *test=[template objectForKey:#"ValidState"];
// NSString *test1=[template objectForKey:#"Userid"];
NSString *helloString = #"1";
// //
// NSString *helloString1 =#"LFY430";
if ([test isEqual:helloString]) {
[NSThread detachNewThreadSelector:#selector(threadStartAnimating:) toTarget:self withObject:nil];
[self moveToView];
// UIAlertView *alert=[[UIAlertView alloc]initWithTitle:#"Login Successfully" message:#"Correct Uername/Password" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
}
else{
UIAlertView *alert2=[[UIAlertView alloc]initWithTitle:#"Login Failed" message:#"Incorrect Uername/Password" delegate:self cancelButtonTitle:#"Dismiss" otherButtonTitles:nil];
[alert2 show];
[self alertView1:alert2 didDismissWithButtonIndex:alert2];
}
}
- (void)viewDidLoad {
[super viewDidLoad];
UIActivityIndicatorView *spinner = [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(150, 225, 20, 30)];
[spinner setActivityIndicatorViewStyle:UIActivityIndicatorViewStyleGray];
spinner.color = [UIColor blackColor];
[self.view addSubview:spinner];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
-(void)moveToView{
UIStoryboard *storyboard = [UIStoryboard storyboardWithName:#"Main" bundle:nil];
DashboardVC *initView = (DashboardVC*)[storyboard instantiateViewControllerWithIdentifier:#"Dashboardvc"];
[initView setModalPresentationStyle:UIModalPresentationFullScreen];
[spinner stopAnimating];
[self presentViewController:initView animated:NO completion:nil];
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
[self moveToView];
}
- (void) alertView1:(UIAlertView *)alertView1 didDismissWithButtonIndex:(NSInteger)buttonIndex
{
UIStoryboard *storyboard = [UIStoryboard storyboardWithName:#"Main" bundle:nil];
LoginVC *initView = (LoginVC*)[storyboard instantiateViewControllerWithIdentifier:#"loginvc"];
[initView setModalPresentationStyle:UIModalPresentationFullScreen];
[self presentViewController:initView animated:NO completion:nil];
}
-(void)threadStartAnimating:(id)data
{
[spinner startAnimating];
}
#end
here by i initialse the indicator and start and stop the spinner but its not woking for me...
any one help me to solve the issues how to add the activity indicator when navigation the another view
Thanks in Advance
[self.view addSubview:spinner];
At this line you add the activity indicator to the current ViewController view.
However once you navigate to other view
DashboardVC *initView = (DashboardVC*)[storyboard instantiateViewControllerWithIdentifier:#"Dashboardvc"];
[self presentViewController:initView animated:NO completion:nil];
the current view changes to the new ViewController's view.
The activity indicator isnt present in that view and therefore you wont see your activity indicator there.
To solve, you should again add activity indicator in the second ViewController's viewDidLoad method
In Dashboard VC
- (void)viewDidLoad {
[super viewDidLoad];
UIActivityIndicatorView *spinner = [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(150, 225, 20, 30)];
[spinner setActivityIndicatorViewStyle:UIActivityIndicatorViewStyleGray];
spinner.color = [UIColor blackColor];
[self.view addSubview:spinner];
}
A better solution would be to use third party progress huds which make
the loading indicator part absolutely easy like MBProgressHUD
You should add activityindicator on navigation controller so, it is remains on front when you navigate.
you should use MBProgressHud the great third party library.
Just put class in your project and import .h file in your class when you want to show activity indicator and then add HUD (activity indicator) like,
[MBProgressHUD showHUDAddedTo:self.view animated:YES];
// in your case show hud on `self.navigationController.view`
// use main thread to show if required
and hide like,
dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
// Do something...
dispatch_async(dispatch_get_main_queue(), ^{
[MBProgressHUD hideHUDForView:self.view animated:YES];
});
});
Hope this will help :)
When you stop UIActivityIndicatorView then also hide it.
[spinner setHidesWhenStopped:YES];
EDIT:
If you are not sure about NSThread then just do like this.
if ([test isEqual:helloString]) {
//[NSThread detachNewThreadSelector:#selector(threadStartAnimating:) toTarget:self withObject:nil];
[spinner startAnimating];
[self moveToView];
}
And when you want to stop it ten
[spinner stopAnimating];
[spinner setHidesWhenStopped:YES];
instead of using indicator , use svprogresshud.Check this link https://github.com/SVProgressHUD/SVProgressHUD.
if you want animated progressbar check this link https://github.com/cemolcay/GiFHUD

Unable to show the activity indicator iOS

I can't get to display the activity spinner on UIWebView
Need to show UIActivityIndicatorView while the page is being loaded.
UIActivityIndicatorView is declared but it's never shown on the UIWebView
Please assist.
The code is as follows :
#import <QuartzCore/QuartzCore.h>
#import "MyScreen"
#import "Reachability.h"
#interface MyScreen ()
#end
#implementation MyScreen
{;
UIView *loadingView;
}
#synthesize gotoMainMenu;
- (void)viewDidLoad {
[super viewDidLoad];
loadingView = [[UIView alloc]initWithFrame:CGRectMake(100, 400, 80, 80)];
loadingView.backgroundColor = [UIColor colorWithWhite:0. alpha:0.6];
loadingView.layer.cornerRadius = 5;
UIActivityIndicatorView *activityView=[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
activityView.center = CGPointMake(loadingView.frame.size.width / 2.0, 35);
[activityView startAnimating];
activityView.tag = 100;
[loadingView addSubview:activityView];
UILabel* lblLoading = [[UILabel alloc]initWithFrame:CGRectMake(0, 48, 80, 30)];
lblLoading.text = #"Loading...";
lblLoading.textColor = [UIColor whiteColor];
lblLoading.font = [UIFont fontWithName:lblLoading.font.fontName size:15];
lblLoading.textAlignment = NSTextAlignmentCenter;
[loadingView addSubview:lblLoading];
[self.view addSubview:loadingView];
// Do any additional setup after loading the view.
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:true];
self.navigationController.navigationBar.hidden=false;
Reachability *reach = [Reachability reachabilityForInternetConnection];
NetworkStatus netStatus = [reach currentReachabilityStatus];
if (netStatus != NotReachable)
{
NSLog(#"Network is Available");
}
else
{
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Network Error" message:#"Please check internet connectivity!" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil , nil];
[alertView show];
[self.navigationController popViewControllerAnimated:YES];
}
}
-(id) init
{
if([super init])
{
webView = [[UIWebView alloc] initWithFrame:CGRectMake(0.0, -64.00, self.view.frame.size.width, self.view.frame.size.height+64.0)];
webView.scalesPageToFit = YES;
webView.userInteractionEnabled = YES;
url = [[NSURL alloc] initWithString:#"http://theURL/"];
req = [[NSURLRequest alloc] initWithURL:url];
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReturnCacheDataElseLoad timeoutInterval:5.0];
[webView loadRequest:theRequest];
[webView loadRequest:req];
[self.view addSubview:webView];
}
return self;
}
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
[loadingView setHidden:YES];
}
- (void)webViewDidStartLoad:(UIWebView *)webView
{
[loadingView setHidden:NO];
}
#end
You should not use "self.view" in your init function. When you use it, the view is loaded and viewDidLoad will be invoked before you add webView. So you webView is added after your loading view.
Just try to move this line:
[self.view addSubview:webView];
After:
[self.view addSubview:loadingView];

Saving pictures to parse

My project will save data to parse and while I can pick an image from my library I cannot open the camera. I found a tutorial to do this but it is not compatible with my code. The link to the tutorial is here: Tutorial . I am using .storyboard and the tutorial is .xib, I do not know if this will change anything.
my .m file is here:
#import "NewRecipeViewController.h"
#import <MobileCoreServices/UTCoreTypes.h>
#import <Parse/Parse.h>
#import "MBProgressHUD.h"
#interface NewRecipeViewController ()
- (IBAction)save:(id)sender;
- (IBAction)cancel:(id)sender;
#property (weak, nonatomic) IBOutlet UIImageView *recipeImageView;
#property (weak, nonatomic) IBOutlet UITextField *nameTextField;
#property (weak, nonatomic) IBOutlet UITextField *prepTimeTextField;
#property (weak, nonatomic) IBOutlet UITextField *ingredientsTextField;
#end
#implementation NewRecipeViewController
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
_nameTextField.delegate = self;
_prepTimeTextField.delegate = self;
_ingredientsTextField.delegate = self;
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
if (indexPath.row == 0) {
[self showPhotoLibary];
}
}
- (void)showPhotoLibary
{
if (([UIImagePickerController isSourceTypeAvailable:
UIImagePickerControllerSourceTypeSavedPhotosAlbum] == NO)) {
return;
}
UIImagePickerController *mediaUI = [[UIImagePickerController alloc] init];
mediaUI.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
// Displays saved pictures from the Camera Roll album.
mediaUI.mediaTypes = #[(NSString*)kUTTypeImage];
// Hides the controls for moving & scaling pictures
mediaUI.allowsEditing = NO;
mediaUI.delegate = self;
[self.navigationController presentModalViewController: mediaUI animated: YES];
}
- (IBAction)save:(id)sender {
// Create PFObject with recipe information
PFObject *recipe = [PFObject objectWithClassName:#"Recipe"];
[recipe setObject:_nameTextField.text forKey:#"name"];
[recipe setObject:_prepTimeTextField.text forKey:#"prepTime"];
NSArray *ingredients = [_ingredientsTextField.text componentsSeparatedByString: #","];
[recipe setObject:ingredients forKey:#"ingredients"];
// Recipe image
NSData *imageData = UIImageJPEGRepresentation(_recipeImageView.image, 0.8);
NSString *filename = [NSString stringWithFormat:#"%#.png", _nameTextField.text];
PFFile *imageFile = [PFFile fileWithName:filename data:imageData];
[recipe setObject:imageFile forKey:#"imageFile"];
// Show progress
MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
hud.mode = MBProgressHUDModeIndeterminate;
hud.labelText = #"Uploading";
[hud show:YES];
// Upload recipe to Parse
[recipe saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
[hud hide:YES];
if (!error) {
// Show success message
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Upload Complete" message:#"Successfully saved the recipe" delegate:Nil cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[alert show];
// Notify table view to reload the recipes from Parse cloud
[[NSNotificationCenter defaultCenter] postNotificationName:#"refreshTable" object:self];
// Dismiss the controller
[self dismissViewControllerAnimated:YES completion:nil];
} else {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Upload Failure" message:[error localizedDescription] delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[alert show];
}
}];
}
- (IBAction)cancel:(id)sender {
[self dismissViewControllerAnimated:YES completion:nil];
}
- (void)viewDidUnload {
[self setRecipeImageView:nil];
[self setNameTextField:nil];
[self setPrepTimeTextField:nil];
[self setIngredientsTextField:nil];
[super viewDidUnload];
}
- (void) imagePickerController: (UIImagePickerController *) picker didFinishPickingMediaWithInfo: (NSDictionary *) info {
UIImage *originalImage = (UIImage *) [info objectForKey:UIImagePickerControllerOriginalImage];
self.recipeImageView.image = originalImage;
[picker dismissViewControllerAnimated:YES completion:nil];
}
#pragma mark - Textfield delegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
[textField resignFirstResponder];
return YES;
}
- (IBAction)takephoto:(id)sender {
UIImagePickerController *picker = [[UIImagePickerController alloc] init];
picker.delegate = self;
picker.allowsEditing = YES;
picker.sourceType = UIImagePickerControllerSourceTypeCamera;
[self presentViewController:picker animated:YES completion:NULL];
}
- (IBAction)selectphoto:(id)sender {
UIImagePickerController *picker = [[UIImagePickerController alloc] init];
picker.delegate = self;
picker.allowsEditing = YES;
picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
[self presentViewController:picker animated:YES completion:NULL];
}
#end
Any help is appreciated.
Take a look at Apple's provided sample project (especially APLViewController.m)
https://developer.apple.com/library/ios/samplecode/PhotoPicker/Introduction/Intro.html#//apple_ref/doc/uid/DTS40010196
You'll see them do the following 4 steps. You are only doing the last half of step one, without first verifying if that source type is even available.
From the UIImagePickerController Class Reference:
To use an image picker controller containing its default controls, perform these steps:
Verify that the device is capable of picking content from the desired source. Do this calling the isSourceTypeAvailable: class method, providing a constant from the “UIImagePickerControllerSourceType” enumeration.
Check which media types are available, for the source type you’re using, by calling the availableMediaTypesForSourceType: class method. This lets you distinguish between a camera that can be used for video recording and one that can be used only for still images.
Tell the image picker controller to adjust the UI according to the media types you want to make available—still images, movies, or both—by setting the mediaTypes property.
Present the user interface. On iPhone or iPod touch, do this modally (full-screen) by calling the presentViewController:animated:completion: method of the currently active view controller, passing your configured image picker controller as the new view controller.

NSXMLParser parserDidStartDocument freezes app

I tried to add some operations after call
- (void)parserDidStartDocument:(NSXMLParser *)parser {
//NSLog(#"found file and started parsing");
alertView = [[UIAlertView alloc] initWithTitle:#"Caricamento..."
message:#"\n"
delegate:self
cancelButtonTitle:nil
otherButtonTitles:nil];
UIActivityIndicatorView *spinner = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
spinner.center = CGPointMake(139.5, 75.5); // .5 so it doesn't blur
[alertView addSubview:spinner];
[spinner startAnimating];
[alertView show];
}
But it freeze the app for a while, and then, when finished the XML parse, loads the AlertView, ecc. Same thing with the UIRefreshControl. I slide down the tableView, and the app freeze while parsing, I cant see the spinner rotating.
Any idea?
Edit:
here I call the first time the parser:
- (void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
NSString * path = #"thexmlpath.xml";
if(!caricato)
[NSThread detachNewThreadSelector:#selector(parseXMLFileAtURL:) toTarget:self withObject:path];
//[self parseXMLFileAtURL:path];
caricato = YES;}
Here I call when I use the RefreshControl:
- (void)refreshControlRequest{
NSLog(#"refreshing...");
NSString * path = #"thexmlpath.xml";
[self performSelector:#selector(parseXMLFileAtURL:) withObject:path];}
hope this will help you
- (void)parserDidStartDocument:(NSXMLParser *)parser {
//NSLog(#"found file and started parsing");
dispatch_queue_t queue = dispatch_get_main_queue();
dispatch_async(queue, ^{
alertView = [[UIAlertView alloc] initWithTitle:#"Caricamento..."
message:#"\n"
delegate:self
cancelButtonTitle:nil
otherButtonTitles:nil];
UIActivityIndicatorView *spinner = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
spinner.center = CGPointMake(139.5, 75.5); // .5 so it doesn't blur
[alertView addSubview:spinner];
[spinner startAnimating];
[alertView show];
});
dispatch_release(queue);
}

ipad-NSThread-Error

For Check Valid Login,
I Fetch Data From Webservice And To Show Progress ,
I Display UIIndicatorView Inside UIAlertView
Problem Is :
During Progress When Press Home Button Of IPad Device Then My Application Is Close,, And Second Time When I Try To Start App Then (Black Screen Is Display) Apps Is Not Start.
How I Can Solve this problem?
My Code Is:
-(NSMutableString*) getLoginMessage:(NSString*) UserName : (NSString *) Password : (NSString *) url
{
[NSThread detachNewThreadSelector:#selector(showAlertMethod) toTarget:self withObject:nil];
#try
{
NSArray *Keys =[[NSArray alloc] initWithObjects:#"LoginName",#"PassWord",nil];
NSArray *KeyValue =[[NSArray alloc] initWithObjects:UserName,Password,nil];
operationName=[[NSString alloc] init];
operationName =#"ClientLogin";
NSURL *WebServiceUrl=[WebServiceHelper generateWebServiceHTTPGetURL:url : operationName : Keys: KeyValue];
NSXMLParser *parser = [[NSXMLParser alloc] initWithContentsOfURL:WebServiceUrl];
[parser setShouldReportNamespacePrefixes:NO];
[parser setShouldResolveExternalEntities:NO];
[parser setDelegate:self];
[parser parse];
[Keys release];
[KeyValue release];
[WebServiceUrl release];
[NSThread detachNewThreadSelector:#selector(dismissAlertMethod) toTarget:self withObject:nil];
}
#catch (NSException * e)
{
[NSThread detachNewThreadSelector:#selector(dismissAlertMethod) toTarget:self withObject:nil];
}
return Result;
}
-(void)showAlertMethod
{
NSAutoreleasePool *pool1=[[NSAutoreleasePool alloc]init];
progressAlert = [[UIAlertView alloc] initWithTitle:#"Signing in..." message:#"Please wait..." delegate:nil cancelButtonTitle: nil otherButtonTitles:nil];
CGRect alertFrame = progressAlert.frame;
UIActivityIndicatorView* activityIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
activityIndicator.frame = CGRectMake(135,alertFrame.size.height+75, alertFrame.size.width,30);
activityIndicator.hidden = NO;
activityIndicator.contentMode = UIViewContentModeCenter;
[activityIndicator startAnimating];
[progressAlert addSubview:activityIndicator];
[activityIndicator release];
[progressAlert show];
[pool1 release];
}
-(void)dismissAlertMethod
{
NSAutoreleasePool *pool2=[[NSAutoreleasePool alloc]init];
[progressAlert dismissWithClickedButtonIndex:0 animated:YES];
[pool2 release];
}
A little hard to read your code, but: you cannot do UI from a thread. Your alert must be created and shown from the main thread.

Resources