ipad-NSThread-Error - ipad

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.

Related

iOS - MFMailComposerViewController cannot cancel if addAttachmentData:

My MFMailComposer code:
MFMailComposeViewController *mailViewController = [[MFMailComposeViewController alloc] init];
[mailViewController setDelegate:self];
[mailViewController setSubject:#"subject"];
[mailViewController setToRecipients:[NSArray arrayWithObject:#"email#email.com"]];
[mailViewController setMessageBody:#"body" isHTML:NO];
for (int i = 0; i < self.imagesData.count; i++)
{
NSDateFormatter *dateFormatter=[[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy-MM-dd-HH-mm-ss-SSSS"];
[mailViewController addAttachmentData:[self.imagesData objectAtIndex:i] mimeType:[self contentTypeForImageData:[self.imagesData objectAtIndex:i]] fileName:[NSString stringWithFormat:#"portfolio_%#_%d", [dateFormatter stringFromDate:[NSDate date]], i]];
}
[self presentViewController:mailViewController animated:YES completion:nil];
With this code I'd press cancel and delete draft and nothing happens, the MFMailComposerViewController doesn't close.
I added the delegates already:
- (void)mailComposeController:(MFMailComposeViewController*)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError*)error{
if(error) NSLog(#"ERROR - mailComposeController: %#", [error localizedDescription]);
if (result == MFMailComposeResultSent)
{
NSLog(#"It's away!");
}
[[UINavigationBar appearance] setTintColor:[UIColor whiteColor]];
[self dismissViewControllerAnimated:YES completion:nil];}
What am I missing?
OK I found an answer. I was stupid.
I used setDelegate instead of setMailComposeDelegate

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

Convert NSArray to NSMutable to remove string dynamically

I have a code that I modified to pull data from an external JSON file. There are two NSArrays. One for the image and one for color. Then, when a particular array is pressed it opens a webviewcontroller. I got it to work perfectly. Here is the problem. I want to be able to modify the JSON anytime I want externally and have the app update the information but since the NSArray information is hardcoded I don't know how to remove an array if I remove an objectforkey from the JSON. Any help would be appreciated.
The code to call the images and colors is:
- (IBAction)onclick:(id)sender {
NSArray *images = #[
[UIImage imageNamed:[NSString stringWithFormat: #"%#",[dataDictionary objectForKey:#"PhoneUrl"]]],
[UIImage imageNamed:[NSString stringWithFormat: #"%#",[dataDictionary objectForKey:#"TextUrl"]]],
[UIImage imageNamed:[NSString stringWithFormat: #"%#",[dataDictionary objectForKey:#"MailUrl"]]]
];
NSArray *colors = #[
[UIColor [NSString stringWithFormat: #"%#",[dataDictionary objectForKey:#"PhoneColor"]],
[UIColor [NSString stringWithFormat: #"%#",[dataDictionary objectForKey:#"TextColor"]]],
[UIColor [NSString stringWithFormat: #"%#",[dataDictionary objectForKey:#"MailColor"]]],
];
Sidebar *callout = [[Sidebar alloc] initWithImages:images borderColors:colors];
callout.delegate = self;
[callout show];
}
Then when pressed it calls the following:
- (void)sidebar:(Sidebar *)sidebar didTapItemAtIndex:(NSUInteger)index {
self.webViewController = [[PBWebViewController alloc] init];
PBSafariActivity *activity = [[PBSafariActivity alloc] init];
self.webViewController.applicationActivities = #[activity];
self.webViewController.excludedActivityTypes = #[UIActivityTypeMail, UIActivityTypeMessage];
NSLog(#"Tapped item at index %lu",(unsigned long)index);
if (index == 0) {
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:[dataDictionary objectForKey:#"PhoneWeb"]]];
[sidebar dismissAnimated:YES completion:nil];
}
if (index == 1) {
if(![MFMessageComposeViewController canSendText]) {
UIAlertView *warningAlert = [[UIAlertView alloc] initWithTitle:#"Error" message:#"Your device doesn't support SMS!" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[warningAlert show];
return;
}
NSArray *recipents = #[[dataDictionary objectForKey:#"TextWeb"]];
MFMessageComposeViewController *messageController = [[MFMessageComposeViewController alloc] init];
messageController.messageComposeDelegate = self;
[messageController setRecipients:recipents];
[[messageController navigationBar] setTintColor:[UIColor whiteColor]];
[self presentViewController:messageController animated:YES completion:nil];
[sidebar dismissAnimated:YES completion:nil];
}
if (index == 2) {
if ([MFMailComposeViewController canSendMail])
{
MFMailComposeViewController *mailer = [[MFMailComposeViewController alloc] init];
[[mailer navigationBar] setTintColor:[UIColor whiteColor]];
mailer.mailComposeDelegate = self;
NSArray *toRecipients = [NSArray arrayWithObjects:[dataDictionary objectForKey:#"MailWeb"], nil];
[mailer setToRecipients:toRecipients];
[self presentViewController:mailer animated:YES completion:nil];
}
else
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Failure"
message:#"Your device doesn't support the composer sheet"
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles: nil];
[alert show];
}
[sidebar dismissAnimated:YES completion:nil];
}

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

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];
});
});

IOS flicker in SDK6.1 but not in 5.X or earlier

I updated my app which was created one year later for SDK 5.X, but now, I get a terrible problem.In the app, using MBProgressHUD to download files from the server, and show an UIAlerView when it finished. but, thus, the view flicker, Someone saied that the UIAlertView should disappeared on the main thread, my code is like this :
NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
MBProgressHUD *hud = [[MBProgressHUD alloc] initWithWindow:[[WNMAppDelegate appDelegate] window]];
hud.labelText = #"Please wait...";
[[[WNMAppDelegate appDelegate] window] addSubview:hud];
[hud showAnimated:YES whileExecutingBlock:^{
[self progressHudMethodForCheckIn:dic];
} completionBlock:^{
[hud removeFromSuperview];
[hud release];
if ([[dic allKeys] count])
{
NSString *key = [[dic allKeys] objectAtIndex:0];
[self alertMessage:[dic objectForKey:key] withTitle:key];
}
else
{
[self alertMessage:#"Succeed sign in" withTitle:#"Nice"];
}
}];
[dic release];
- (void)alertMessage:(NSString *)message withTitle:(NSString *)title{
UIAlertView *alert = [[UIAlertView alloc]
initWithTitle:title
message:(NSString *)message
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
[alert release];
}
can someone help me? Thank you.

Resources