Showing UIActivityIndicator when calling a webservice - ios

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

Related

Table View is not displaying Data

you can download this project from this link
Execute this Program Clicking on button"Click here to sell your Gold now" enter the
username :hermon_yonaito#bullionscope.com
password :Wau2017?
Issue -1
It will launch you to dashboard. Select "Transaction History" that is not displaying record. Check why record is not displaying?And to display the record in view Controller?
Issue-2
The second issue is on selecting Profile the ProfileViewController.m is executed.On updating the user profile updateButtonTap function is executed.It does not update.It remains buffering.How to perform profile update?
here is ProfileViewController.m
#import "ProfileViewController.h"
#interface ProfileViewController ()
#end
#implementation ProfileViewController
- (void)viewDidLoad
{
[super viewDidLoad];
currentUser = [SingletonClass sharedSingletonClass].settingsDictionary[#"User"];
selectedValues=[NSMutableDictionary dictionary];
[MBProgressHUD showHUDAddedTo:self.view animated:YES];
NSMutableDictionary *paramDict=[NSMutableDictionary dictionary];
[paramDict setObject:#"ios" forKey:#"request"];
[paramDict setObject:[NSString stringWithFormat:#"%#",currentUser.user_id] forKey:#"user_id"];
[GeneralWebservices webserviceMainSplashCall:paramDict webserviceName:Webservice_Profile OnCompletion:^(id returnDict, NSError *error) {
if ([returnDict[#"success"] intValue] ==1)
{
[self setProfileData:returnDict[#"data"]];
provinceList=[NSMutableArray arrayWithArray:returnDict[#"provincedata"]];
questions1Array=[NSMutableArray arrayWithArray:returnDict[#"questiondata"]];
}
else
{
[self get_register_data];
}
[MBProgressHUD hideAllHUDsForView:self.view animated:YES];
}];
}
-(void)setProfileData:(NSMutableDictionary*)dataDict
{
profilePicImageView.imageURL=[NSURL URLWithString:dataDict[#"image_file_thumb"]];
[firstNameLabel setText:dataDict[#"first_name"]];
[lastNameLabel setText:dataDict[#"last_name"]];
[dateOfBirthLabel setText:dataDict[#"user_dob"]];
[postalAddressTextfield setText:dataDict[#"user_address"]];
[mobileTextfield setText:dataDict[#"user_mobile"]];
[question1Textfield setText:dataDict[#"user_answer_1"]];
[question2Textfield setText:dataDict[#"user_answer_2"]];
[LLGButton setTitle:dataDict[#"user_llg"] forState:UIControlStateNormal];
[provinceButton setTitle:dataDict[#"user_province"] forState:UIControlStateNormal];
[districtButton setTitle:dataDict[#"user_district"] forState:UIControlStateNormal];
[villageTextfield setText:dataDict[#"user_village"]];
[question1Button setTitle:dataDict[#"user_question_1"] forState:UIControlStateNormal];
[question2Button setTitle:dataDict[#"user_question_2"] forState:UIControlStateNormal];
[self callforDistrict:#"get_district.php" idForItem:dataDict[#"district_id"]];
[self callforLLG:#"get_llg.php" idForItem:dataDict[#"llg_id"]];
[selectedValues setObject:dataDict[#"user_question_1_id"] forKey:#"user_question_1"];
[selectedValues setObject:dataDict[#"user_question_2_id"] forKey:#"user_question_2"];
[selectedValues setObject:dataDict[#"province_id"] forKey:#"user_province"];
[selectedValues setObject:dataDict[#"district_id"] forKey:#"user_district"];
[selectedValues setObject:dataDict[#"llg_id"] forKey:#"user_llg"];
}
-(void)callforDistrict:(NSString*)serviceName idForItem:(NSString*)idForItem
{
dispatch_async(dispatch_get_main_queue(), ^{
[self getdistdata:idForItem];
});
}
-(void)callforLLG:(NSString*)serviceName idForItem:(NSString*)idForItem
{
dispatch_async(dispatch_get_main_queue(), ^{
[self getIIL:idForItem];
});
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void)viewDidLayoutSubviews
{
[profileScrollView setContentSize:CGSizeMake(self.view.frame.size.width, 700)];
}
- (IBAction)uploadPictureButtonTap:(UIButton *)sender
{
UIActionSheet *popup = [[UIActionSheet alloc] initWithTitle:#"Select option" delegate:self cancelButtonTitle:#"Cancel" destructiveButtonTitle:nil otherButtonTitles:
#"Open Gallery",
#"Take Photo",
nil];
popup.tag = 1;
[popup showInView:[UIApplication sharedApplication].keyWindow];
}
- (IBAction)provinceButtonTap:(UIButton *)sender
{
[self.view endEditing:YES];
NSMutableArray *provinceNames=[NSMutableArray array];
for (NSMutableDictionary*pro in provinceList)
{
[provinceNames addObject:pro[#"province_name"]];
}
LGActionSheet *sheet=[[LGActionSheet alloc] initWithTitle:#"Select Province" buttonTitles:provinceNames cancelButtonTitle:#"Cancel" destructiveButtonTitle:nil];
sheet.tagOfSheet=2;
sheet.heightMax=300;
sheet.delegate=self;
[sheet showAnimated:YES completionHandler:nil];
}
- (IBAction)districtButtonTap:(UIButton *)sender
{
[self.view endEditing:YES];
NSMutableArray *names=[NSMutableArray array];
for (NSMutableDictionary*pro in districList)
{
[names addObject:pro[#"district_name"]];
}
LGActionSheet *sheet=[[LGActionSheet alloc] initWithTitle:#"Select District" buttonTitles:names cancelButtonTitle:#"Cancel" destructiveButtonTitle:nil];
sheet.heightMax=200;
sheet.tagOfSheet=3;
sheet.delegate=self;
[sheet showAnimated:YES completionHandler:nil];
}
- (IBAction)LLGButtonTap:(UIButton *)sender
{
[self.view endEditing:YES];
NSMutableArray *names=[NSMutableArray array];
for (NSMutableDictionary*pro in llgList)
{
[names addObject:pro[#"llg_name"]];
}
LGActionSheet *sheet=[[LGActionSheet alloc] initWithTitle:#"Select LLG" buttonTitles:names cancelButtonTitle:#"Cancel" destructiveButtonTitle:nil];
sheet.heightMax=200;
sheet.tagOfSheet=4;
sheet.delegate=self;
[sheet showAnimated:YES completionHandler:nil];
}
- (IBAction)villageButtonTap:(UIButton *)sender
{
[self.view endEditing:YES];
}
- (IBAction)question1ButtonTap:(UIButton *)sender
{
[self.view endEditing:YES];
NSMutableArray *ques1=[NSMutableArray array];
for (NSMutableDictionary*pro in questions1Array)
{
[ques1 addObject:pro[#"question_name"]];
}
LGActionSheet *sheet=[[LGActionSheet alloc] initWithTitle:#"Select Question 1" buttonTitles:ques1 cancelButtonTitle:#"Cancel" destructiveButtonTitle:nil];
sheet.tagOfSheet=5;
sheet.heightMax=300;
sheet.delegate=self;
[sheet showAnimated:YES completionHandler:nil];
}
- (IBAction)question2ButtonTap:(UIButton *)sender
{
[self.view endEditing:YES];
NSMutableArray *ques2=[NSMutableArray array];
for (NSMutableDictionary*pro in questions1Array)
{
[ques2 addObject:pro[#"question_name"]];
}
LGActionSheet *sheet=[[LGActionSheet alloc] initWithTitle:#"Select Question 2" buttonTitles:ques2 cancelButtonTitle:#"Cancel" destructiveButtonTitle:nil];
sheet.tagOfSheet=6;
sheet.heightMax=300;
sheet.delegate=self;
[sheet showAnimated:YES completionHandler:nil];
}
- (IBAction)updateButtonTap:(UIButton *)sender
{
[self.view endEditing:YES];
[MBProgressHUD showHUDAddedTo:self.view animated:YES];
[selectedValues setObject:#"ios" forKey:#"request"];
[selectedValues setObject:[NSString stringWithFormat:#"%#",currentUser.user_id] forKey:#"user_id"];
[selectedValues setObject:postalAddressTextfield.text forKey:#"address"];
[selectedValues setObject:mobileTextfield.text forKey:#"user_mobile"];
[selectedValues setObject:question1Textfield.text forKey:#"user_answer_1"];
[selectedValues setObject:villageTextfield.text forKey:#"user_village"];
[GeneralWebservices webserviceCallWithData:selectedValues webserviceName:Webservice_ProfileUpdate dataToPost:imageData imageName:imageName OnCompletion:^(id returnDict, NSError *error) {
if ([returnDict[#"success"] intValue] ==1)
{
}
else
{
UIAlertView* alert = [[UIAlertView alloc] init];
[alert setTitle:#"Updated Successfully"];
//[alert setMessage:returnDict[#"message"]];
[alert addButtonWithTitle:#"OK"];
[alert show];
}
[MBProgressHUD hideAllHUDsForView:self.view animated:YES];
}];
}
- (IBAction)saveButtonTap:(UIButton *)sender
{
[self.view endEditing:YES];
}
- (void)actionSheet:(LGActionSheet *)actionSheet buttonPressedWithTitle:(NSString *)title index:(NSUInteger)index
{
dispatch_async(dispatch_get_main_queue(), ^{
if (actionSheet.tagOfSheet==2)
{
[selectedValues setObject:provinceList[index][#"province_id"] forKey:#"user_province"];
[provinceButton setTitle:provinceList[index][#"province_name"] forState:UIControlStateNormal];
[districList removeAllObjects];
[llgList removeAllObjects];
[districtButton setTitle:#"District *" forState:UIControlStateNormal];
[LLGButton setTitle:#"LLG *" forState:UIControlStateNormal];
[selectedValues removeObjectForKey:#"district"];
[selectedValues removeObjectForKey:#"llg"];
[self callforDistrict:#"get_district.php" idForItem:provinceList[index][#"province_id"]];
}
else if(actionSheet.tagOfSheet==3)
{
[selectedValues setObject:districList[index][#"id"] forKey:#"user_district"];
[districtButton setTitle:districList[index][#"district_name"] forState:UIControlStateNormal];
[llgList removeAllObjects];
[LLGButton setTitle:#"LLG *" forState:UIControlStateNormal];
[selectedValues removeObjectForKey:#"llg"];
[self callforLLG:#"get_llg.php" idForItem:districList[index][#"id"]];
}
else if(actionSheet.tagOfSheet==4)
{
[selectedValues setObject:llgList[index][#"id"] forKey:#"user_llg"];
[LLGButton setTitle:llgList[index][#"llg_name"] forState:UIControlStateNormal];
}
else if(actionSheet.tagOfSheet==5)
{
[selectedValues setObject:questions1Array[index][#"question_id"] forKey:#"user_question_1"];
[question1Button setTitle:questions1Array[index][#"question_name"] forState:UIControlStateNormal];
}
else if(actionSheet.tagOfSheet==6)
{
[selectedValues setObject:questions1Array[index][#"question_id"] forKey:#"user_question_2"];
[question2Button setTitle:questions1Array[index][#"question_name"] forState:UIControlStateNormal];
}
});
}
-(IBAction) returnTextField:(id)sender
{
CGRect frame = self.view.frame;
frame.origin.y = 0;
[UIView animateWithDuration:0.3 animations:^{
self.view.frame = frame;
}];
[self.view endEditing:YES];
}
- (BOOL)textFieldShouldEndEditing:(UITextField*)textField
{
return YES;
}
-(BOOL) textFieldShouldReturn:(UITextField *)textField
{
[self animateTextField:textField up:NO];
[textField resignFirstResponder];
return YES;
}
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
[self animateTextField:textField up:YES];
}
- (void)textFieldDidEndEditing:(UITextField *)textField
{
[self animateTextField:textField up:NO];
}
- (void)actionSheet:(UIActionSheet *)popup clickedButtonAtIndex:(NSInteger)buttonIndex
{
switch (popup.tag) {
case 1: {
switch (buttonIndex) {
case 0:
[self openPhotoLibraryButton:self];
break;
case 1:
[self openCameraButton:self];
break;
default:
break;
}
break;
}
default:
break;
}
}
- (IBAction)openCameraButton:(id)sender
{
[self.view endEditing:YES];
if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
UIImagePickerController *picker = [[UIImagePickerController alloc] init];
picker.delegate = self;
[picker setSourceType:UIImagePickerControllerSourceTypeCamera];
picker.allowsEditing = false;
[self presentViewController:picker animated:true completion:nil];
}
else{
UIAlertView *alert=[[UIAlertView alloc]initWithTitle:#"Alert!" message:#"Camera is not connected" delegate:self cancelButtonTitle:#"Ok" otherButtonTitles:nil, nil];
[alert show];
}
}
- (IBAction)openPhotoLibraryButton:(id)sender
{
[self.view endEditing:YES];
if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
UIImagePickerController *picker = [[UIImagePickerController alloc] init];
picker.delegate = self;
[picker setSourceType:UIImagePickerControllerSourceTypePhotoLibrary];
picker.allowsEditing = true;
[self presentViewController:picker animated:true completion:nil];
}
}
-(void) imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
[self dismissViewControllerAnimated:YES completion:nil];
imageData=[[NSData alloc]init];
if ([info[#"UIImagePickerControllerMediaType"] isEqualToString:#"public.image"])
{
UIImage *image = [info objectForKey:#"UIImagePickerControllerEditedImage"];
if (!image)
{
image = [info objectForKey:#"UIImagePickerControllerOriginalImage"];
}
NSURL *imagePath = [info objectForKey:#"UIImagePickerControllerReferenceURL"];
image=[SettingsClass rotateImageAppropriately:image];
NSString *imageNamewithformat = [imagePath lastPathComponent];
imageName=#"assets.jpg";
NSString *Imageformat = [imageNamewithformat substringFromIndex: [imageNamewithformat length] - 3];
if ([Imageformat isEqualToString:#"JPG"]||[Imageformat isEqualToString:#"jpg"]) {
imageData=UIImageJPEGRepresentation(image, 0.33f);
imageName=#"assets.jpg";
}
else if ([Imageformat isEqualToString:#"PNG"]||[Imageformat isEqualToString:#"png"])
{
imageData=UIImagePNGRepresentation(image);
imageName=#"assets.png";
}
else
{
imageData=UIImageJPEGRepresentation(image, 0.33f);
imageName=#"assets.jpg";
}
[profilePicImageView setImage:image];
}
}
- (void) animateTextField: (UITextField*) textField up: (BOOL) up
{
CGPoint temp = [textField.superview convertPoint:textField.frame.origin toView:nil];
UIInterfaceOrientation orientation =
[[UIApplication sharedApplication] statusBarOrientation];
if (orientation == UIInterfaceOrientationPortrait){
if(up) {
int moveUpValue = temp.y+textField.frame.size.height;
animatedDis = 264-(self.view.frame.size.height-moveUpValue-35);
}
}
else if(orientation == UIInterfaceOrientationPortraitUpsideDown) {
if(up) {
int moveUpValue = self.view.frame.size.height-temp.y+textField.frame.size.height;
animatedDis = 264-(self.view.frame.size.height-moveUpValue-35);
}
}
else if(orientation == UIInterfaceOrientationLandscapeLeft || orientation == UIInterfaceOrientationLandscapeRight) {
if(up) {
int moveUpValue = temp.y+textField.frame.size.height;
animatedDis = 352-(self.view.frame.size.height-moveUpValue-100);
}
}
else
{
if(up) {
int moveUpValue = temp.y+textField.frame.size.height;
animatedDis = 352-(768-moveUpValue-100);
}
}
if(animatedDis>0)
{
const int movementDistance = animatedDis;
const float movementDuration = 0.3f;
int movement = (up ? -movementDistance : movementDistance);
[UIView beginAnimations: nil context: nil];
[UIView setAnimationBeginsFromCurrentState: YES];
[UIView setAnimationDuration: movementDuration];
if (orientation == UIInterfaceOrientationPortrait){
self.view.frame = CGRectOffset( self.view.frame, 0, movement);
}
else if(orientation == UIInterfaceOrientationPortraitUpsideDown) {
self.view.frame = CGRectOffset( self.view.frame, 0, movement);
}
else if(orientation == UIInterfaceOrientationLandscapeLeft) {
self.view.frame = CGRectOffset( self.view.frame, 0, movement);
}
else {
self.view.frame = CGRectOffset( self.view.frame, 0, movement);
}
[UIView commitAnimations];
}
}
- (IBAction)backtohomeview :(id)sender {
[self dismissViewControllerAnimated:YES completion:nil];
}
-(void)getdistdata:(NSString*)idForItem
{
self.view.userInteractionEnabled = NO;
NSString *strURL;
strURL = [NSString stringWithFormat:#"http://bullionscope.com/Gold_Phase3/webservices/get_district.php?request=ios&province_id=%#",idForItem];
NSDictionary *headers = #{ #"cache-control": #"no-cache",
#"postman-token": #"900e1577-4876-cd9a-d24c-cb0631b4a1fb" };
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:strURL]
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:10.0];
[request setHTTPMethod:#"POST"];
[request setAllHTTPHeaderFields:headers];
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request
completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if (error) {
// [self AlertController:#"Alert!" :#"Request time out"];
}
else
{
NSDictionary *jsonDic = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSString *success = [[jsonDic objectForKey:#"success"]stringValue];
if (
[success isEqualToString:
#"1"])
{
districList=[NSMutableArray arrayWithArray:[jsonDic objectForKey:#"data"]];
dispatch_async(dispatch_get_main_queue(), ^{
self.view.userInteractionEnabled = YES;
});
}
else
{
// [self AlertController:#"Alert!" :#"No record found"];
dispatch_async(dispatch_get_main_queue(), ^{
self.view.userInteractionEnabled = YES;
});
}
}
}];
[dataTask resume];
}
-(void)get_register_data
{
self.view.userInteractionEnabled = NO;
NSString *strURL;
http://bullionscope.com/Gold_Phase3/webservices/get_all_province.php?request=ios
strURL = [NSString stringWithFormat:#"http://bullionscope.com/Gold_Phase3/webservices/get_all_province.php?request=ios"];
NSDictionary *headers = #{ #"cache-control": #"no-cache",
#"postman-token": #"900e1577-4876-cd9a-d24c-cb0631b4a1fb" };
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:strURL]
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:10.0];
[request setHTTPMethod:#"POST"];
[request setAllHTTPHeaderFields:headers];
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request
completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if (error) {
// [self AlertController:#"Alert!" :#"Request time out"];
}
else
{
NSDictionary *jsonDic = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSString *success = [[jsonDic objectForKey:#"success"]stringValue];
if (
[success isEqualToString:
#"1"])
{
provinceList=[NSMutableArray arrayWithArray:[jsonDic objectForKey:#"data"]];
dispatch_async(dispatch_get_main_queue(), ^{
self.view.userInteractionEnabled = YES;
});
}
else
{
// [self AlertController:#"Alert!" :#"No record found"];
dispatch_async(dispatch_get_main_queue(), ^{
self.view.userInteractionEnabled = YES;
});
}
}
}];
[dataTask resume];
}
#end
Your api is returning nil data .
here is the error description -
Error Description: Error Domain=com.alamofire.error.serialization.response Code=-1016 "Request failed: unacceptable content-type: text/html"
Problem is with your api handling .
This replace method in your GeneralWebservices class with this
+(void) webserviceMainSplashCall:(NSMutableDictionary *)parameters webserviceName:(NSString*)webserviceName OnCompletion:(void(^)(id returnDict, NSError* error))callbackBlock{
/*
// parameter keys & values, values will be dynamic.
"forward_date" = "26-05-2016";
"gold_weight" = 345;
request = ios;
"user_id" = 1;
*/
NSString *url = [NSString stringWithFormat:#"%#%#",App_BaseUrl,webserviceName];
NSLog(#"url is this = %#", [NSString stringWithFormat:#"%#%#",App_BaseUrl,webserviceName]);
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.requestSerializer = [AFHTTPRequestSerializer serializer];
AFJSONResponseSerializer *jsonReponseSerializer = [AFJSONResponseSerializer serializer];
// This will make the AFJSONResponseSerializer accept any content type
jsonReponseSerializer.acceptableContentTypes = nil;
manager.responseSerializer = jsonReponseSerializer;
// manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:#"application/json", #"text/html",#"text/json", #"text/javascript", nil];
// manager.responseSerializer = [AFJSONResponseSerializer serializer];
[manager POST:[NSString stringWithFormat:#"%#%#",App_BaseUrl,webserviceName] parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {
}
progress:^(NSProgress * _Nonnull uploadProgress)
{
}
success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject)
{
callbackBlock( responseObject, nil );
}
failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error)
{
// check error here.
NSLog(#"Error Description: %#",error);
callbackBlock( nil, nil );
}];
}
final screen shot of output -

How to check a timeout occurred in ios url connection?

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

how to display loading indicator in AVAudioPlayer if user clicks the play button

I am working in AVAudioplayer in iOS. I am displaying an activity indicator for loading time if a user clicks the play button. My problem is that when I click the play button the loading time activity indicator is not displayed.
-(void)loadData
{
url=[NSURL URLWithString:#"http://www.urls.com"];
NSMutableURLRequest *request=[[NSMutableURLRequest alloc]initWithURL:url];
[[NSURLConnection alloc]initWithRequest:request delegate:self];
[UIApplication sharedApplication].networkActivityIndicatorVisible=YES;
[self.view addSubview:loadingView];
[activityView startAnimating];
loadingConnection=[[NSURLConnection alloc]initWithRequest:request delegate:self startImmediately:YES];
}
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
responseData=[[NSMutableData alloc]init];
[responseData setLength:0];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
if(connection==loadingConnection)
{
[responseData appendData:data];
}
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
[UIApplication sharedApplication].networkActivityIndicatorVisible=NO;
[activityView stopAnimating];
[loadingView removeFromSuperview];
if(connection==loadingConnection)
{
NSError *jsonError = nil;
id jsonObject = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&jsonError];
if ([jsonObject isKindOfClass:[NSArray class]])
{
//NSArray *jsonArray = (NSArray *)jsonObject;
}
else if ([jsonObject isKindOfClass:[NSDictionary class]])
{
NSDictionary *jsonDictionary = (NSDictionary *)jsonObject;
NSArray *array=[[NSArray alloc]init];
array=[jsonDictionary objectForKey:#"audio-urls"];
dataDictionary=[array objectAtIndex:0];
NSLog(#"%#",dataDictionary);
}
[urlsArray addObject:[dataDictionary objectForKey:#“Audio1”]];
[urlsArray addObject:[dataDictionary objectForKey:#“Audio2”]];
[urlsArray addObject:[dataDictionary objectForKey:#“Audio3”]];
[urlsArray addObject:[dataDictionary objectForKey:#“Audio4”]];
[urlsArray addObject:[dataDictionary objectForKey:#“Audio5”]];
[urlsArray addObject:[dataDictionary objectForKey:#“Audio6”]];
NSLog(#"%#",urlsArray);
}
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
[UIApplication sharedApplication].networkActivityIndicatorVisible=NO;
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"No Internet Connection" message:#"Please ensure you have internet connection" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
[activityView stopAnimating];
[loadingView removeFromSuperview];
}
- (void)viewDidLoad
{
playing=NO;
[self loadData];
// [self temp];
[self performSelector:#selector(loadData) withObject:nil afterDelay:3.0f];
urlsArray=[[NSMutableArray alloc]init];
[super viewDidLoad];
}
-(void)temp
{
// loading View
loadingView=[[UILabel alloc]initWithFrame:CGRectMake(135, 200, 40, 40)];
loadingView.backgroundColor=[UIColor clearColor];
loadingView.clipsToBounds=YES;
loadingView.layer.cornerRadius=10.0;
activityView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite];
activityView.frame = CGRectMake(10, 11, activityView.bounds.size.width, activityView.bounds.size.height);
[loadingView addSubview:activityView];
}
-(void)playOrPauseButtonPressed:(id)sender
{
if(playing==NO)
{
[self temp];
// [self.view addSubview:loadingView];
// [loadingView addSubview:activityView];
// [UIApplication sharedApplication].networkActivityIndicatorVisible=YES;
[playButton setBackgroundImage:[UIImage imageNamed:#"Pause.png"] forState:UIControlStateNormal];
// Here Pause.png is a image showing Pause Button.
NSError *err=nil;
AVAudioSession *audioSession=[AVAudioSession sharedInstance];
[audioSession setCategory:AVAudioSessionCategoryPlayback error:nil];
NSLog(#"%# %d",urlsArray,selectedIndex);
NSString *sourcePath=[urlsArray objectAtIndex:selectedIndex];
NSData *objectData=[NSData dataWithContentsOfURL:[NSURL URLWithString:sourcePath]];
NSLog(#"%#",objectData);
audioPlayer = [[AVAudioPlayer alloc] initWithData:objectData error:&err];
if(err)
{
NSLog(#"Error %ld,%#",(long)err.code,err.localizedDescription);
}
NSTimeInterval bufferDuration=0.005;
[audioSession setPreferredIOBufferDuration:bufferDuration error:&err];
if(err)
{
NSLog(#"Error %ld, %#", (long)err.code, err.localizedDescription);
}
double sampleRate = 44100.0;
[audioSession setPreferredSampleRate:sampleRate error:&err];
if(err)
{
NSLog(#"Error %ld, %#",(long)err.code,err.localizedDescription);
}
[audioSession setActive:YES error:&err];
if(err)
{
NSLog(#"Error %ld,%#", (long)err.code, err.localizedDescription);
}
sampRate=audioSession.sampleRate;
bufferDuration=audioSession.IOBufferDuration;
NSLog(#"SampeRate:%0.0fHZI/OBufferDuration:%f",sampleRate,bufferDuration);
audioPlayer.numberOfLoops = 0;
[audioPlayer prepareToPlay];
[audioPlayer play];
audioPlayer.delegate=self;
if(!audioPlayer.playing)
{
[audioPlayer play];
}
playing=YES;
}
else if (playing==YES)
{
[playButton setBackgroundImage:[UIImage imageNamed:#"play.png"] forState:UIControlStateNormal];
[audioPlayer pause];
playing=NO;
timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:#selector(updateViewForPlayerState) userInfo:nil repeats:YES];
}
if (self.audioPlayer)
{
[self updateViewForPlayerInfo];
[self updateViewForPlayerState];
[self.audioPlayer setDelegate:self];
}
}
//Create and add the Activity Indicator to view
UIActivityIndicatorView *activityIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite];
activityIndicator.alpha = 1.0;
activityIndicator.center = CGPointMake(160, 360);
activityIndicator.hidesWhenStopped = NO;
[self.view addSubview:activityIndicator];
[activityIndicator startAnimating];`
Have a nice day!
no need to NSURLConnection delegate method
direct pass url in AVAudioPlayer
UIActivityIndicatorView *spinner = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
[spinner setCenter:CGPointMake(230, 330)]; // I do this because I'm in landscape mode
[yourview addSubview:spinner];
[spinner setColor:[UIColor whiteColor]];
[spinner startAnimating];
[self performSelector:#selector(download) withObject:nil afterDelay:0.50f];
-(void)download
{
NSData *audioData = [NSData dataWithContentsOfURL:[NSURL URLWithString:#"http://www.dailywav.com/0813/bicycles.wav"]];
NSString *docDirPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *filePath = [NSString stringWithFormat:#"%#/bicycles.wav", docDirPath ];
[audioData writeToFile:filePath atomically:YES];
NSError *error;
NSURL *fileURL = [NSURL fileURLWithPath:filePath];
AVAudioPlayer *player = [[AVAudioPlayer alloc] initWithContentsOfURL:fileURL error:&error];
if (player == nil) {
NSLog(#"AudioPlayer did not load properly: %#", [error description]);
} else {
[spinner stopAnimating
];
[player play];
}
}

UIActivityIndicatorView Not Stopping When I want

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

App crashing. Control not moving to catch statement

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.

Resources