Parse 122 error upload - ios

If I save text without having any text in the field I get this error message in Parse.com: Update Failure - The operation couldn't be completed(Parse error 122.) If I press OK and then try to dismiss the view with Cancel(a button item) the app crashes. I think a valid file name at Parse.com has to contain at least 1 character. Maybe I can do do something to stop the user from saving when not enter text? Any ideas?
This my code:
- (IBAction)save:(id)sender {
// Create PFObject with profile information
PFUser *profile = [PFUser currentUser];
[profile setObject:nameTextField.text forKey:#"name"];
[profile setObject:titleTextField.text forKey:#"title"];
[profile setObject:locationTextField.text forKey:#"location"];
// Profile image
NSData *imageData = UIImageJPEGRepresentation(profileImageView.image, 0.8);
NSString *filename = [NSString stringWithFormat:#"%#", nameTextField.text];
PFFile *imageFile = [PFFile fileWithName:filename data:imageData];
[profile setObject:imageFile forKey:#"profileimageFile"];
// Show progress
MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
hud.mode = MBProgressHUDModeIndeterminate;
hud.labelText = #"Updating";
[hud show:YES];
// Upload profile to Parse
if(nameTextField.text.length==0 && titleTextField.text.length==0 && locationTextField.text.length==0)
[hud hide:YES];
[profile saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
if (error) {
[[[UIAlertView alloc] initWithTitle:#"Profile Information" message:#"Fill in atleast one field" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil]show];
[hud hide:YES];
}
else {
// Show success message
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"" message:#"Successfully updated profile" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[alert show];
[hud hide:YES];
[self dismissViewControllerAnimated:YES completion:nil];
[self performSegueWithIdentifier:#"profile" sender:self];
}
}];
}
- (IBAction)Cancel:(id)sender {
[self dismissViewControllerAnimated:YES completion:nil];
[self performSegueWithIdentifier:#"profile" sender:self];
}

1
Test if your one letter theory is true. Change:
NSString *filename = [NSString stringWithFormat:#"%#", nameTextField.text];
To:
NSString *filename = [NSString stringWithFormat:#"file%#", nameTextField.text];
2
Or just avoid it if it's blank. So this:
NSString *filename = [NSString stringWithFormat:#"%#", nameTextField.text];
PFFile *imageFile = [PFFile fileWithName:filename data:imageData];
[profile setObject:imageFile forKey:#"profileimageFile"];
Becomes:
if (nameTextField.text) {
NSString *filename = [NSString stringWithFormat:#"%#", nameTextField.text];
PFFile *imageFile = [PFFile fileWithName:filename data:imageData];
[profile setObject:imageFile forKey:#"profileimageFile"];
}
3
Also, what is this:
if(nameTextField.text.length==0 && titleTextField.text.length==0 && locationTextField.text.length==0)
It's doesn't appear to be connected to anything?
4
You call this twice in quick succession, and then again right after the file saves. Is there something in the method that makes the repetitive calls necessary?
[hud hide:YES];
5
Your if statement doesn't appear to be connected to anything:
if(nameTextField.text.length==0 && titleTextField.text.length==0 && locationTextField.text.length==0)
I'm assuming you want:
if(nameTextField.text.length==0 && titleTextField.text.length==0 && locationTextField.text.length==0) {
[hud hide:YES];
[profile saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
if (error) {
[[[UIAlertView alloc] initWithTitle:#"Profile Information" message:#"Fill in atleast one field" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil]show];
[hud hide:YES];
}
else {
// Show success message
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"" message:#"Successfully updated profile" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[alert show];
[hud hide:YES];
[self dismissViewControllerAnimated:YES completion:nil];
[self performSegueWithIdentifier:#"profile" sender:self];
}
}];
}

Related

How to pause a main thread until a block is finished Objective-C

I have a problem.
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
UIImage* image = [info objectForKey:UIImagePickerControllerOriginalImage];
UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil);
[self dismissViewControllerAnimated:YES completion:^{
if (image == nil){
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Try again !" message:#"Please try again." delegate:self cancelButtonTitle:#"OK" otherButtonTitles: nil];
[alert show];
[self presentViewController:self.imagePicker animated:NO completion:nil];
}else{
NSData *fileData;
NSString *fileName;
NSString *fileType;
fileData = UIImagePNGRepresentation(image);
fileName = #"profilePic.png";
fileType = #"Image";
PFFile *file = [PFFile fileWithName:fileName data:fileData];
[file saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
if (error) {
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"An error occurred!"
message:[NSString stringWithFormat:#"Please try sending your message again. %#",error.userInfo]
delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alertView show];
}else{
[[PFUser currentUser]setObject:file forKey:#"profilePic"];
[[PFUser currentUser] saveInBackgroundWithBlock:^(BOOL succeed, NSError* error){
if (!error) {
NSLog(#"New profile pic loaded.");
[self.activity stopAnimating];
[self.reloadPicBtn setHidden:NO];
}else{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Try again !" message:#"Please try again. Failed to load your new profile pic :(" delegate:self cancelButtonTitle:#"OK" otherButtonTitles: nil];
[alert show];
}
}];
}
}];
}
}];
}
Well, reloadPicBtn is shown, but if I call a function which reloads a picture, It fails. And when I try to understand WTF is going on using NSLog it logs out a string. So code has been executed. But there is no result on screen. The function is the same which is called in viewDidLoad. But it works when it is called from viewDidLoad. And when it is called again there is no result.
That reload function:
- (void) loadProfilePic{
PFQuery* query = [PFUser query];
[query getObjectInBackgroundWithId:[PFUser currentUser].objectId block:^(PFObject* object, NSError* error){
if(!error){
PFFile* imageFile = object[#"profilePic"];
[imageFile getDataInBackgroundWithBlock:^(NSData* data, NSError* error){
if (!error) {
self.activity.hidden = NO;
[self.activity startAnimating];
self.profilePic.image = [UIImage imageWithData:data];
NSLog(#"Profile pic shown");
}
else{
NSLog(#"Error 2: %#",error);
}
}];
}else{
self.profilePic.image = [UIImage imageNamed:#"profile#2.png"];
NSLog(#"Fail 1 : %#",error);
}
}];
}
Please help me.
It prints out profile pic shown. But it doesn't even use network to download an image.

fetching 1 image from parse.com

Ive seen many posting on here with phenomenal answers by the community. Unfortunately none have been able to help or guide me to what i need help with. Im trying to "fetch" the image that the "current user" uploaded to parse on the same "UIImageView"
below is the example of how i uploaded the photo
myaccount.h
#property (strong, nonatomic) IBOutlet UIImageView *imageView;
- (IBAction)UploadPhoto:(id)sender;
- (IBAction)selectPhoto:(id)sender;
myaccount.m
- (IBAction)UploadPhoto:(UIButton *)sender {
PFObject *User = [PFUser currentUser];
NSData *imageData = UIImageJPEGRepresentation(_imageView.image, 0.8);
NSString *filename = [NSString stringWithFormat:#"%#.png", _username.text];
PFFile *imageFile = [PFFile fileWithName:filename data:imageData];
[User setObject:imageFile forKey:#"ProfilePicture"];
// Show progress
MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
hud.mode = MBProgressHUDModeIndeterminate;
hud.labelText = #"Uploading";
[hud show:YES];
// Upload Profile Picture to Parse
[User saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
[hud hide:YES];
if (!error) {
// Show success message
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Upload Complete" message:#"Successfully uploaded profile picture" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[alert show];
// Dismiss the controller
//[self dismissViewControllerAnimated:YES completion:nil];
} else {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Upload Failure" message:[error localizedDescription] delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[alert show];
}
}];
}
i honestly have no idea where to go from here! the photo uploads perfectly to the class on parse.com... but i cannot get it to show everytime the app viewdidloads this controller.
i tried
- (void)viewDidLoad {
[super viewDidLoad];
PFFile * myPFFile = [[PFUser currentUser] objectForKey:#"ProfilePicture"];
[myPFFile getDataInBackgroundWithBlock:^(NSData *data, NSError *error) {
if (!error) {
UIImage *image = [UIImage imageWithData:data];
// image can now be set on a UIImageView
}
}];
but i get unused variable for "image" on UIImage *image = [UIImage imageWithData:data];
what am i doing wrong. Someone please help me with any codes I'm missing. I've been at this for 3 months now and its stopping me from moving forward.... PPPPLLZZZ help
What am I missing? Do you put the image inside an imageView?
(thats why you get 'unused variable for "image"')
in your case:
[imageView setImage:image];

Saving textField data to a property in an NSObject Class

I am quite new to iOS development so please be nice :) I am developing an app at the moment. A user will register by filling in a form which is just a bunch of TextFields.
Once the user registers they will be redirected to their homePage where a UIImageView and a UILabel will display there data they used when registering.
Now my issue is how to ensure that this UIImageView and UILabel display the same data everytime that same user logs in. I tried this using NSUserDefaults but when the user logs in it would display the users data that i just registered with. Any suggestions would be great and also I am using parse for my data base.
Here is the code for when a user registers
NSLog(#"Registering user");
MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
hud.labelText = #"Registering";
PFObject *parent = [PFObject objectWithClassName:#"Parent"];
UIImage *image = form.profilePhoto;
NSData *imageData = UIImageJPEGRepresentation(image, 0.6);
PFFile *imageFile = [PFFile fileWithName:#"image.jpeg" data:imageData];
parent[#"Name"] = form.name;
parent[#"Email"] = form.email;
parent[#"Password"] = form.password;
parent[#"Location"] = form.location;
parent[#"ImageFile"] = imageFile;
[parent saveInBackground];
[parent saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
if (!error) {
[hud hide:YES];
currentUser = YES;
//saveData to parentUser
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
[prefs setObject:form.name forKey:#"Name"];
//Send user to parent home page
PHomeViewController *lvc=[self.storyboard instantiateViewControllerWithIdentifier:#"Phome"];
SlideNavigationController *navcontroller = [[SlideNavigationController alloc] initWithRootViewController:lvc];
ParentMenu *leftMenu = (ParentMenu*)[self.storyboard instantiateViewControllerWithIdentifier: #"LeftMenuViewController"];
[self.navigationController pushViewController:lvc animated:YES];
navcontroller.leftMenu = leftMenu;
//save data to nsuserdefualts
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
UIImage *uploadPhoto = form.profilePhoto;
[defaults setObject:form.name forKey:#"Name"];
[defaults setObject:UIImageJPEGRepresentation(uploadPhoto, 0.6) forKey:#"ImageFile"];
[defaults synchronize];
NSLog(#"Data has been saved");
}
else {
NSLog(#"There was an error in registration");
}
}];
}
}
And this is the code that runs when a user logs in
(IBAction)login:(id)sender {
MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
hud.labelText = #"Loading...";
PFQuery *query = [PFQuery queryWithClassName:#"Parent"];
[query whereKey:#"Email" equalTo:_Email.text];
[query whereKey:#"Password" equalTo:_Password.text];
[query getFirstObjectInBackgroundWithBlock:^(PFObject *object, NSError *error) {
if (object) {
NSLog(#"User logged in successfully");
//Send user to parent home page
PHomeViewController *lvc=[self.storyboard instantiateViewControllerWithIdentifier:#"Phome"];
SlideNavigationController *navcontroller = [[SlideNavigationController alloc] initWithRootViewController:lvc];
ParentMenu *leftMenu = (ParentMenu*)[self.storyboard instantiateViewControllerWithIdentifier: #"LeftMenuViewController"];
[self.navigationController pushViewController:lvc animated:YES];
navcontroller.leftMenu = leftMenu;
} else {
// LOGIN ERROR
UIAlertView *ALERT = [[UIAlertView alloc]initWithTitle:#"Error" message:#"There was an error logging in please try again later." delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles:nil, nil];
[ALERT show];
_Email.text = [NSString stringWithFormat:#""];
_Password.text = [NSString stringWithFormat:#""];
[MBProgressHUD hideHUDForView:self.view animated:YES];
}
}];
}
Thanks!

PFObject does not reflect "successfully" saved changes in the Parse Data Browser

I am trying to update a PFObject called message. This PFObject has already been retrieved from the Parse Database and passed over from another view controller. I know that the PFObject is passed over correctly because I can NSLog it's value and it is correct.
With the following code, I add an object to one of the PFObject's keys:
[self.message addObject:#"blah" forKey:#"didRespond"];
I then try saving the updated PFObject to the Parse Database:
[self.message saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
if (error) {
NSLog(#"An error has occurred.");
}
}];
The above method always calls back with a succeeded value of 1, and there are never any errors. However, when I go and look at the PFObject in the Parse Data Browser, it's key does not contain the newly added object. It is still completely empty.
They key is an array, so I know I should be using addObject: and not setObject:
I have several other Parse saves happening in this same view controller, and throughout my app, and they all work perfectly fine, but for some reason this one will not. I have tried every type of save method Parse offers, including the synchronous save method, but nothing works.
What is even more strange, is this is a new version of my app and I am refactoring the code. My old version contains a giant mess of code, but what's amazing is the same PFObject is successfully updated in this old code! I even tried copying and pasting this code to my new version and it will not work, even though it will in the old version.
Here is the giant mess of code from my old version. If you search for the following code statement you will be able to locate it quickly:
[self.message addObject:currentUsersObjectId forKey:#"didRespond"];
Here is the full chunk of code, where the save is working and being reflected in the Data Browser. It consists of several nested asynchronous Parse saves:
-(void)uploadPhoto {
NSLog(#"self.image.size right before upload: %#", NSStringFromCGSize(self.image.size));
NSString *fileType;
NSString *halfOrFull;
if(self.image != nil) {
fileType = #"image";
halfOrFull = #"full";
NSData *imageData = UIImageJPEGRepresentation(self.image, 0.7);
PFFile *imageFile = [PFFile fileWithName:#"Image.jpg" data:imageData];
NSString *originalSender = [[NSString alloc]init];
originalSender = [self.message objectForKey:#"senderId"];
NSLog(#"PFFile has been created: %#", imageFile);
[imageFile saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
if(error) {
NSLog(#"There has been an error: %# %#", error, [error userInfo]);
UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:#"An error occurred!" message:#"Please try sending your message again." delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alertView show];
} else {
[self.afterPhotoView setHidden:YES];
PFObject *returnMessage = [PFObject objectWithClassName:#"Messages"];
[returnMessage setObject:imageFile forKey:#"file"];
[returnMessage setObject:fileType forKey:#"fileType"];
[returnMessage addObject:originalSender forKey:#"recipientIds"];
[returnMessage setObject:[[PFUser currentUser]objectId] forKey:#"senderId"];
[returnMessage setObject:[[PFUser currentUser]username]forKey:#"senderName"];
[returnMessage setObject:halfOrFull forKey:#"halfOrFull"];
NSString *originalSender = [[NSString alloc]init];
originalSender = [self.message objectForKey:#"senderName"];
[returnMessage setObject:originalSender forKey:#"originalSender"];
[returnMessage saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
if(error) {
NSLog(#"There was an error: %# %#", error, [error userInfo]);
UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:#"An error occurred!" message:#"Please try sending your message again." delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alertView show];
} else {
//Everything was successful.
NSLog(#"Everything was successful.");
if(succeeded == 1) {
NSLog(#"Succeeded value right before 2nd save: %d", succeeded);
NSString *currentUsersObjectId = [[NSString alloc]init];
PFUser *user = [PFUser currentUser];
currentUsersObjectId = user.objectId;
[self.message addObject:currentUsersObjectId forKey:#"didRespond"];
[self.message saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
if(error) {
NSLog(#"There was an error: %# %#", error, [error userInfo]);
self.uploadPhotoAlertView = [[UIAlertView alloc]initWithTitle:#"An error occurred!" message:#"Please try sending your message again." delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[self.uploadPhotoAlertView show];
} else {
//Everything was successful.
NSLog(#"Everything was successful.");
if(succeeded == 1) {
//[self performSegueWithIdentifier:#"segueToInbox" sender:self];
NSString *originalSender2 = [[NSString alloc]init];
originalSender2 = [self.message objectForKey:#"senderName"];
self.photoUploadAlertViewMessage = [[NSString alloc]initWithFormat:#"You just finished going halfsies with %#!", originalSender2];
//PFFile *imageFile = [self.message objectForKey:#"file"];
self.finishedImageFile = imageFile;
self.finishedImageFileURL = [[NSURL alloc]initWithString:self.finishedImageFile.url];
self.uploadPhotoAlertView = [[UIAlertView alloc]initWithTitle:nil message:self.photoUploadAlertViewMessage delegate:self cancelButtonTitle:#"Sweet!" otherButtonTitles:nil];
[self.uploadPhotoAlertView show];
//[self.sharePhotoView setHidden:NO];
}
//[self performSegueWithIdentifier:#"segueToInbox" sender:self];
}
}];
}
}
}];
}
}];
}
}

Showing UIActivityIndicator when calling a webservice

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

Resources