I need to show a UIActivityIndicatorView when calling of a WebService is take place. However, the activity indicator keeps on showing even after i have received response from web service. It stops only after 5-6 seconds after i receive response. How to make it stop at the moment i am receiving a response?
Here's my code: (configuring UIActivityIndicatorView) and calling my webservice:
loadView = [[UIView alloc] initWithFrame:self.view.bounds];
loadView.backgroundColor = [UIColor colorWithWhite:0.0 alpha:0.5];
//UIActivityIndicatorView *activityView = [[UIActivityIndicatorView alloc] init];
//[second.loadingView addSubview:activityView];
//activityView.center = second.loadingView.center;
//[second.view addSubview:second.loadingView];
activity = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
[loadView addSubview:activity];
activity.center = loadView.center;
[self.view addSubview:loadView];
[self.view bringSubviewToFront:loadView];
activity.hidesWhenStopped = YES;
[activity setHidden:NO];
//[activity performSelectorInBackground: #selector(startAnimating) withObject: nil];
[activity startAnimating];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
[self callRegisterWebService:self.userFname lastName:self.userLName email:self.userEmail];
});
I am stopping the animation in the finally block.
-(void)callRegisterWebService:(NSString *)fname lastName:(NSString *)lName email:(NSString *)email
{
NSString *serviceURL = [NSString stringWithFormat:#"https:abcdefghi..."];
#try {
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:serviceURL]];
NSURLResponse *serviceResponse = nil;
NSError *err = nil;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&serviceResponse error:&err];
NSMutableDictionary *parsedData = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableContainers error:&err];
if(!parsedData)
{
NSLog(#"data not parsed");
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"ERROR" message:#"Problem in Network. Please Try Again!" delegate:self cancelButtonTitle:#"OK" otherButtonTitles: nil];
[alert show];
}
else
{
NSString *status = [parsedData objectForKey:#"Status"];
if([status isEqualToString:#"Success"])
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NULL message:#"Authentication Token Has Been Sent To Your Email-ID!" delegate:self cancelButtonTitle:#"OK" otherButtonTitles: nil];
[alert show];
NSString *uniqueNumber = [parsedData objectForKey:#"UniqueNum"];
[self saveEmailAndUniqueNumberToDatabase:fname lastName:lName Email:email Number:uniqueNumber];
}
else if([status isEqualToString:#"Failed"])
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Not An Authorized User" message:#"Please Contact Admin To Get Access" delegate:self cancelButtonTitle:#"Ok" otherButtonTitles:nil];
[alert show];
}
else
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"ERROR" message:#"Problem in Network. Please Try Again!" delegate:self cancelButtonTitle:#"OK" otherButtonTitles: nil];
[alert show];
}
}
}
#catch (NSException *exception)
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NULL message:#"Problem In Network Connection. Please Try Again!" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
}
#finally {
[activity stopAnimating];
[loadView setHidden:YES];
}
}
There are 2 issues in your code:
You are manipulating UI component from a background thread, never do that. Use main thread for UI manipulations
You wrote the activity indicator functionality in the finally clause, so it'll be hidden only after executing all the statements in try clause
Change your method like:
- (void) hideActivity
{
dispatch_async(dispatch_get_main_queue(), ^{
[activity stopAnimating];
[loadView setHidden:YES];
activity = nil;
loadView = nil;
});
}
-(void)callRegisterWebService:(NSString *)fname lastName:(NSString *)lName email:(NSString *)email
{
NSString *serviceURL = [NSString stringWithFormat:#"https:abcdefghi..."];
NSString *message = #"";
NSString *title = #"";
#try
{
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:serviceURL]];
NSURLResponse *serviceResponse = nil;
NSError *err = nil;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&serviceResponse error:&err];
NSMutableDictionary *parsedData = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableContainers error:&err];
[self hideActivity];
if(!parsedData)
{
message = #"Problem in Network. Please Try Again!";
title = #"ERROR";
}
else
{
NSString *status = [parsedData objectForKey:#"Status"];
if([status isEqualToString:#"Success"])
{
message = #"Authentication Token Has Been Sent To Your Email-ID!";
title = nil;
NSString *uniqueNumber = [parsedData objectForKey:#"UniqueNum"];
[self saveEmailAndUniqueNumberToDatabase:fname lastName:lName Email:email Number:uniqueNumber];
}
else if([status isEqualToString:#"Failed"])
{
message = #"Please Contact Admin To Get Access";
title = #"Not An Authorized User";
}
else
{
message = #"Problem in Network. Please Try Again!";
title = #"ERROR";
}
}
}
#catch (NSException *exception)
{
if (activity != nil && loadView != nil)
{
[self hideActivity];
}
message = #"Problem In Network Connection. Please Try Again!";
title = nil;
}
#finally
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:title message:message delegate:self cancelButtonTitle:#"OK" otherButtonTitles: nil];
[alert show];
}
}
Related
Below is my code and I want to perform segue based on response string, but couldn't, can someone watch out my code and tell me what's wrong.
and when I am entering value in contact no. textfield,app is terminating with the error :
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Can't do regex matching on object <UITextField: 0x7faae2079980; frame = (20 353; 280 45); text = '9876543210'; clipsToBounds = YES; opaque = NO; autoresize = W+TM+BM; gestureRecognizers = <NSArray: 0x7faae2097250>; layer = <CALayer: 0x7faae2083bd0>>.'
Code I have try:
- (IBAction)Register:(id)sender {
if ((uname.text.length==0)&&(uemail.text.length==0)&&(ucontact.text.length==0)&&(upwd.text.length==0)&&(confirmpwd.text.length==0)){
UIAlertView *alert=[[UIAlertView alloc] initWithTitle:#"Can not Register"
message:#"All the Fields are Mandatory"
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:#"Cancel", nil];
[alert show];
}
else{
NSString *emailString = uemail.text;// storing the entered email in a string.
//Regular expression to checl the email format.
NSString *emailReg = #"[A-Z0-9a-z._%+-]+#[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
NSPredicate *emailTest=[NSPredicate predicateWithFormat:#"SELF MATCHES %#", emailReg];
if(([emailTest evaluateWithObject:emailString]!=YES)||[emailString isEqualToString:#""])
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Warning" message:#"Enter your email in abc#example.com format." delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
uemail.text = #"";
return;
}
}
NSString *mobile=ucontact.text;
NSString *numberRegEx = #"([0-9]{10})";
NSPredicate *numberTest = [NSPredicate predicateWithFormat:#"SELF MATCHES %#", numberRegEx];
if ([numberTest evaluateWithObject:ucontact] != YES||[mobile isEqualToString:#""])
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Warning" message:#"Enter a Valid Number." delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
uemail.text = #"";
return;
}
if ((upwd.text)!=(confirmpwd.text)) {
UIAlertView *alert=[[UIAlertView alloc] initWithTitle:#"Password Do Not Match"
message:nil
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:#"Cancel", nil];
[alert show];}
NSURL *url = [NSURL URLWithString:#"http://108.179.246.128/connectme/service/registration.php"];
NSMutableURLRequest *rq = [NSMutableURLRequest requestWithURL:url];
[rq setHTTPMethod:#"POST"];
NSString *params=[NSString stringWithFormat:#"name=%#&email=%#&mobile=%#&passwrd=%#",self->uname.text,self->uemail.text,self->ucontact.text,self->upwd.text];
NSData *postData = [params dataUsingEncoding:NSASCIIStringEncoding];
[rq setHTTPBody:postData];
NSURLResponse *response;
NSError *error;
NSData *urlData = [NSURLConnection sendSynchronousRequest:rq returningResponse:&response error:&error];
NSString *str=[[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding]; NSLog(#"Login response:%#",str); //getting response
// [self performSegueWithIdentifier:#"activity" sender:self];
if([str isEqual: #"Successfully Registered"])
{
[self performSegueWithIdentifier:#"login" sender:self];
}
else if([str isEqual:#"Sorry Email address already taken"])
{
UIAlertView *alertit=[[UIAlertView alloc] initWithTitle:#"Can not Register"
message:#"Email Address already Taken"
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:#"Cancel", nil];
[alertit show];
}
}
For your second question that is crashing, it is because you need to pass the textField.text not the UITextField object. So it should be mobile variable that contain text of textField instead of ucontact textField object.
[numberTest evaluateWithObject:mobile]
I have used URLRequest to fetch a html file from a pc in my wifi network.
My app fetches a html file from my fileserver and the filename is a number which is typed in the app. Also I have given a 20 seconds timeout for the request. How can I detect whether timeout occurred because I have 2 situations,
1. file does not exist
2. connection is slow
In urlrequest, there is a BOOL for error,no description.
Suggest me a method if possible.
My code is below for only urlrequest
-(void)getHtmlContent{
[self.spinner startAnimating];
NSString *str = #"http://192.168.1.250/rec/";
// NSString *str = #"file:///Volumes/xampp/htdocs/";
str = [str stringByAppendingString:numEntered.text];
str = [str stringByAppendingString:#".html"];
NSURL *url=[NSURL URLWithString:str];
//self.htmlContent = nil;
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
//NSURLRequest *request = [NSURLRequest requestWithURL:url];
request.timeoutInterval = 20.0;
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration ephemeralSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration];
NSURLSessionDownloadTask *task = [session downloadTaskWithRequest:request completionHandler:^(NSURL *localfile, NSURLResponse *response, NSError *error) {
if(!error){
if([request.URL isEqual:url]){
NSString *content = [NSString stringWithContentsOfURL:localfile encoding: NSUTF8StringEncoding error:&error];
dispatch_async(dispatch_get_main_queue(), ^{
[numEntered setText:#"0"];
text = #"";
[self.spinner stopAnimating];
self.htmlContent = content;
NSString *myHTMLString = self.htmlContent;
if(myHTMLString != nil) {
if([myHTMLString isEqualToString:#"3"]){
UIAlertView *alrt = [[UIAlertView alloc] initWithTitle:#"LogIn Success" message:#"" delegate:self cancelButtonTitle:#"Continue" otherButtonTitles:nil];
self.view.userInteractionEnabled = YES;
[alrt show];
}
else{
UIAlertView *alrt = [[UIAlertView alloc] initWithTitle:#"LogIn Failed. Try again." message:#"User not authenticated" delegate:self cancelButtonTitle:#"Ok" otherButtonTitles:nil];
self.view.userInteractionEnabled = YES;
[alrt show];
}
}
});
}
}
else {
dispatch_async(dispatch_get_main_queue(), ^{
[self.spinner stopAnimating];
[numEntered setText:#"0"];
text = #"";
UIAlertView *alrt = [[UIAlertView alloc] initWithTitle:#"Requested file does not exist." message:#"Try again." delegate:self cancelButtonTitle:#"Ok" otherButtonTitles:nil];
self.view.userInteractionEnabled = YES;
[alrt show];
});
}
}];
[task resume];
}
Since I can not comment I am writing as an Answer.
You need to check the error object to see the type of error that occured.
so in your else block you need to check error.localizedDescription to see what has happened, it would usually tell you that the file was not found or if the request timed out. you can even use your alert to show it like changing your else block as follows
else {
dispatch_async(dispatch_get_main_queue(), ^{
[self.spinner stopAnimating];
[numEntered setText:#"0"];
text = #"";
UIAlertView *alrt = [[UIAlertView alloc] initWithTitle : #"Error"
message : error.localizedDescription
delegate : self
cancelButtonTitle : #"Ok"
otherButtonTitles : nil];
self.view.userInteractionEnabled = YES;
[alrt show];
});
}
You must use this delegate method to handle timeout:-
-(void) connection:(NSURLConnection * ) connection didFailWithError:(NSError *)error {
if (error.code == NSURLErrorTimedOut)
// handle error as you want
NSLog(#"Request time out");
}
I have complete code for send invitation when i click on button a pop up menu is appear,in the pop up menu say...
ERROR.
Game Requests are available to games.
and my code for invite friends are here:
NSDictionary *parameters = #{#"to":#""};
[FBWebDialogs presentRequestsDialogModallyWithSession:nil
message:#"message aaya kya" title:#"app request"
parameters:parameters
handler:^(FBWebDialogResult result, NSURL *resultURL, NSError *error)
{
if(error)
{
NSLog(#"Some errorr: %#", [error description]);
UIAlertView *alrt = [[UIAlertView alloc] initWithTitle:#"Invitiation Sending Failed" message:#"Unable to send inviation at this Moment, please make sure your are connected with internet" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles: nil];
[alrt show];
// [alrt release];
}
else
{
if (![resultURL query])
{
return;
}
NSDictionary *params = [self parseURLParams:[resultURL query]];
NSMutableArray *recipientIDs = [[NSMutableArray alloc] init];
for (NSString *paramKey in params)
{
if ([paramKey hasPrefix:#"to["])
{
[recipientIDs addObject:[params objectForKey:paramKey]];
}
}
if ([params objectForKey:#"request"])
{
NSLog(#"Request ID: %#", [params objectForKey:#"request"]);
}
if ([recipientIDs count] > 0)
{
//[self showMessage:#"Sent request successfully."];
//NSLog(#"Recipient ID(s): %#", recipientIDs);
UIAlertView *alrt = [[UIAlertView alloc] initWithTitle:#"Success!" message:#"Invitation(s) sent successfuly!" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles: nil];
[alrt show];
//[alrt release];
}
}
}
friendCache:nil];
}
so where I am wrong?
Please help me.
Thanks.
Ok,I understand if you want to send app request to your friends than you should use FBSDKAppInviteContent.
Here is the code:
FBSDKAppInviteContent *content =[[FBSDKAppInviteContent alloc] init];
content.appLinkURL = [NSURL URLWithString:#"Your_App_Id"];
content.previewImageURL = [NSURL URLWithString:#"Your_app_previewimage"];
[FBSDKAppInviteDialog showWithContent:content
delegate:self];
Here for Your_App_Id please refer to this link.
And it's delegate methods:
- (void)appInviteDialog:(FBSDKAppInviteDialog *)appInviteDialog didCompleteWithResults:(NSDictionary *)results{
if (results) {
}
}
- (void)appInviteDialog:(FBSDKAppInviteDialog *)appInviteDialog didFailWithError:(NSError *)error{
if (error) {
NSString *message = error.userInfo[FBSDKErrorLocalizedDescriptionKey] ?:
#"There was a problem sending the invite, please try again later.";
NSString *title = error.userInfo[FBSDKErrorLocalizedTitleKey] ?: #"Oops!";
[[[UIAlertView alloc] initWithTitle:title message:message delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil] show];
}
}
Why don't you try FBSDKGameRequestContent(It will require Facebook SDK 4.0)?
Note: This will work only if your app category is Game in Facebook developer page.
Here is the code:
FBSDKGameRequestContent *gameRequestContent = [[FBSDKGameRequestContent alloc] init];
// Look at FBSDKGameRequestContent for futher optional properties
FBSDKGameRequestDialog *dialog = [[FBSDKGameRequestDialog alloc]init];
dialog.delegate = self;
dialog.content = gameRequestContent;
gameRequestContent.message = #"Become a Ninja!!!";
gameRequestContent.title = #"NinjaPan";
dialog.delegate = self;
dialog.content = gameRequestContent;
[dialog show];
And it's delegate methods:
- (void)gameRequestDialog:(FBSDKGameRequestDialog *)gameRequestDialog didCompleteWithResults:(NSDictionary *)results{
if (results) {
}
}
- (void)gameRequestDialog:(FBSDKGameRequestDialog *)gameRequestDialog didFailWithError:(NSError *)error{
if (error) {
NSLog(#"%#",error.localizedDescription);
}
}
- (void)gameRequestDialogDidCancel:(FBSDKGameRequestDialog *)gameRequestDialog{
NSLog(#"Cancelled by user");
}
I need to show a UIActivityIndicator while i am waiting for response from the web service. Where exactly do i put the code for it?? It does not work this way. the activity indicator does not show up.
Do i need to use asynchronous request in order to show it??
-(void)callWebService
{
[self.customercareSearchbar resignFirstResponder];
[self.SRResultDictionary removeAllObjects];
NSLog(#"web service called");
NSString *srn = _SRNumber;
NSString *serviceURL = [NSString stringWithFormat:#"https://abcdef...];
#try {
UIActivityIndicatorView *activity = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
[self.view addSubview:activity];
activity.center = self.view.center;
[self.view bringSubviewToFront:loadView];
activity.hidesWhenStopped = YES;
[activity setHidden:NO];
[activity startAnimating];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:serviceURL]];
NSURLResponse *serviceResponse = nil;
NSError *err = nil;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&serviceResponse error:&err];
[activity stopAnimating];
NSMutableDictionary *parsedData = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableContainers error:&err];
if(!parsedData)
{
NSLog(#"data not parsed");
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"ERROR" message:#"Problem in Network. Please Try Again!" delegate:self cancelButtonTitle:#"OK" otherButtonTitles: nil];
[alert show];
[self.customerCareTableView setHidden:YES];
}
else
{
NSLog(#"parsed");
NSLog(#"parsed.. the size is %lu", (unsigned long)[parsedData count]);
NSLog(#"%#", parsedData);
NSString *status = [parsedData objectForKey:#"ns:Status"];
NSLog(#"the status is %#", status);
if([status isEqualToString:#"Success"])
{
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
if([[prefs objectForKey:#"SwitchState"] isEqualToString:#"OFF"])
{
//do nothing
}
else
{
[self saveNumberInDatabase:srn];
}
NSMutableDictionary *third = [parsedData objectForKey:#"ListOfXrxLvServiceRequest"];
NSLog(#"internal dict is %#", third);
self.SRResultDictionary = [third objectForKey:#"ServiceRequest"];
[self.customerCareTableView reloadData];
[self.customerCareTableView setHidden:NO];
}
else if([status isEqualToString:#"Record Not Found"])
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Invalid Entry" message:#"Please enter a valid Service Request Number" delegate:self cancelButtonTitle:#"Ok" otherButtonTitles:nil];
[alert show];
[self.customerCareTableView setHidden:YES];
}
else
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"ERROR" message:#"Problem in Network. Please Try Again!" delegate:self cancelButtonTitle:#"OK" otherButtonTitles: nil];
[alert show];
[self.customerCareTableView setHidden:YES];
}
}
}
#catch (NSException *exception)
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NULL message:#"Problem In Network Connection. Please Try Again!" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
[self.customerCareTableView setHidden:YES];
}
#finally {
}
}
Yes, problem is the Synchronous request.
If it is fine to send ASynchronous request then try doing this.
[NSURLConnection sendAsynchronousRequest:request queue:nil completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
// stop activity
// write other code you want to execute
}];
I found MBProgressHUD is best indicator and you can use is simply in your starting of method call like
dispatch_async(dispatch_get_main_queue(), ^{
if(!HUD) HUD = [[MBProgressHUD alloc] initWithView:self.navigationController.view];
[self.view addSubview:HUD];
HUD.delegate = self;
HUD.userInteractionEnabled = NO;
HUD.labelText = #"Saving your Preferences...";
[[UIApplication sharedApplication] beginIgnoringInteractionEvents];
[HUD show:YES];
});
and in your finally block you can hide this like
dispatch_async(dispatch_get_main_queue(), ^{
[HUD hide:YES];
[[UIApplication sharedApplication] endIgnoringInteractionEvents];
});
//.h file
#interface ViewController : UIViewController
{
UIActivityIndicatorView *activityIndicator;
BOOL showingActivityIndicator;
}
#property(nonatomic) BOOL showingActivityIndicator;
#property(nonatomic) UIActivityIndicatorView *activityIndicator;
#end
//.m file
#synthesize showingActivityIndicator,activityIndicator;
///// Call this method in viewDidLoad
-(void)initializeClass
{
self.activityIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
self.activityIndicator.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin|UIViewAutoresizingFlexibleTopMargin|UIViewAutoresizingFlexibleRightMargin|UIViewAutoresizingFlexibleBottomMargin;
self.activityIndicator.hidesWhenStopped = YES;
[self layoutSubviews];
}
-(void)layoutSubviews
{
CGRect activityIndicatorFrame = self.activityIndicator.frame;
activityIndicatorFrame.origin.x = (self.view.frame.size.width - self.activityIndicator.frame.size.width) / 2;
activityIndicatorFrame.origin.y = (self.view.frame.size.height - self.activityIndicator.frame.size.height) / 2;
self.activityIndicator.frame = activityIndicatorFrame;
[self.view addSubview:self.activityIndicator];
}
-(void)setShowingActivityIndicator:(BOOL)showingActivityIndicators
{
if (showingActivityIndicators) {
[self.activityIndicator startAnimating];
} else {
[self.activityIndicator stopAnimating];
}
showingActivityIndicator= showingActivityIndicators;
}
-(void)dummyButtonAction // you button action to call service
{
[self setShowingActivityIndicator:YES];
[self performSelector:#selector(callWebService) withObject:nil afterDelay:0.3];
// [self callWebService];
}
-(void)callWebService
{
[self.view endEditing:YES]; // this statement will make sure keyboard is resigned
//[self.SRResultDictionary removeAllObjects];
NSLog(#"web service called");
NSString *srn = _SRNumber;
NSString *serviceURL = [NSString stringWithFormat:#"https://abcdef...];
#try {
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:serviceURL]];
NSURLResponse *serviceResponse = nil;
NSError *err = nil;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&serviceResponse error:&err];
NSMutableDictionary *parsedData = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableContainers error:&err];
if(!parsedData)
{
NSLog(#"data not parsed");
[self ShowAlertViewWithTitleString:#"ERROR":#"Problem in Network. Please Try Again!"];
[self.customerCareTableView setHidden:YES];
}
else
{
NSLog(#"parsed");
NSLog(#"parsed.. the size is %lu", (unsigned long)[parsedData count]);
NSLog(#"%#", parsedData);
NSString *status = [parsedData objectForKey:#"ns:Status"];
NSLog(#"the status is %#", status);
if([status isEqualToString:#"Success"])
{
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
if([[prefs objectForKey:#"SwitchState"] isEqualToString:#"OFF"])
{
//do nothing
}
else
{
[self saveNumberInDatabase:srn];
}
NSMutableDictionary *third = [parsedData objectForKey:#"ListOfXrxLvServiceRequest"];
NSLog(#"internal dict is %#", third);
self.SRResultDictionary = [third objectForKey:#"ServiceRequest"];
[self.customerCareTableView reloadData];
[self.customerCareTableView setHidden:NO];
}
else if([status isEqualToString:#"Record Not Found"])
{
[self ShowAlertViewWithTitleString:#"Invalid Entry":#"Please enter a valid Service Request Number"];
[self.customerCareTableView setHidden:YES];
}
else
{
[self ShowAlertViewWithTitleString:#"ERROR":#"Problem in Network. Please Try Again!"];
[self.customerCareTableView setHidden:YES];
}
}
}
#catch (NSException *exception)
{
[self ShowAlertViewWithTitleString:#"":#"Problem In Network Connection. Please Try Again!"];
[self.customerCareTableView setHidden:YES];
}
#finally {
}
[self setShowingActivityIndicator:NO];
}
- (void)ShowAlertViewWithTitleString :(NSString *)title :(NSString *)message
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:title message:message delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
}
When the webservice is reachable, the code is working fine, but when it is unreachable, the app crashes. Why isn't the control going to #catch ??
-(void)callRegisterWebService:(NSString *)fname lastName:(NSString *)lName email:(NSString *)email
{
[self.view endEditing:YES];
UIActivityIndicatorView *activity = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
[self.view addSubview:activity];
activity.center = self.view.center;
[self.view bringSubviewToFront:activity];
activity.hidesWhenStopped = YES;
[activity setHidden:NO];
[activity startAnimating];
NSOperationQueue *q = [NSOperationQueue mainQueue];
NSString *serviceURL = [NSString stringWithFormat:#"https://aagaka];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:serviceURL]];
#try
{
[NSURLConnection sendAsynchronousRequest:request queue:q completionHandler:^(NSURLResponse *serviceResponse, NSData *responseData, NSError *err) {
NSMutableDictionary *parsedData = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableContainers error:&err];
[activity stopAnimating];
if(!parsedData)
{
NSLog(#"data not parsed");
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"ERROR" message:#"Problem in Network. Please Try Again!" delegate:self cancelButtonTitle:#"OK" otherButtonTitles: nil];
[alert show];
}
else
{
NSLog(#"parsed");
NSLog(#"parsed.. the size is %lu", (unsigned long)[parsedData count]);
NSLog(#"%#", parsedData);
NSString *status = [parsedData objectForKey:#"Status"];
NSLog(#"the status is %#", status);
if([status isEqualToString:#"Success"])
{
NSString *uniqueNumber = [parsedData objectForKey:#"UniqueNum"];
[self saveEmailAndUniqueNumberToDatabase:fname lastName:lName Email:email Number:uniqueNumber];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NULL message:#"Authentication Token Has Been Sent To Your Email-ID!" delegate:self cancelButtonTitle:#"OK" otherButtonTitles: nil];
[alert show];
[self.verifyView setHidden:NO];
[self.registerView setHidden:YES];
[self.verifyButtonTab setEnabled:YES];
[self.verifyButtonTab setSelected:YES];
[self.registerButtonTab setSelected:NO];
}
else if([status isEqualToString:#"Failed"])
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Not An Authorized User" message:#"Please Contact Admin To Get Access" delegate:self cancelButtonTitle:#"Ok" otherButtonTitles:nil];
[alert show];
[self.verifyView setHidden:YES];
[self.registerView setHidden:NO];
[self.verifyButtonTab setEnabled:NO];
[self.registerButtonTab setSelected:YES];
}
else
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"ERROR" message:#"Problem in Network. Please Try Again!" delegate:self cancelButtonTitle:#"OK" otherButtonTitles: nil];
[alert show];
[self.verifyView setHidden:YES];
[self.registerView setHidden:NO];
[self.verifyButtonTab setEnabled:NO];
[self.registerButtonTab setSelected:YES];
}
}
}];
}
#catch (NSException *exception)
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NULL message:#"Problem In Network Connection. Please Try Again!" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
[self.verifyView setHidden:YES];
[self.registerView setHidden:NO];
[self.verifyButtonTab setEnabled:NO];
[self.registerButtonTab setSelected:YES];
}
#finally {
}
}
If the error occurs with te block the try catch in not going to called since the block is executed in a different context.
Move the try try catch in the block of the completionHandler: and it should work.