How to set validation in UITextFields - ios

I am using some text fields, and text field validations. I have shown below my code, In this code click button event and all text field text save on web server, In this code validation running only on empty text field. But i want to correct email address validation and all text field character length fixed.I tried to many times but some time condition wrong and some time don't show alert view and some time don't save text field text. How it possible please help, Thank you
My code
- (IBAction)submit:(id)sender {
if(self.txname == nil || [self.txname.text isEqualToString:#""])
{
UIAlertView *ErrorAlert = [[UIAlertView alloc] initWithTitle:#"Name"message:#"All Fields are mandatory." delegate:nil cancelButtonTitle:#"OK"otherButtonTitles:nil, nil];
[ErrorAlert show];
}
else if(self.txemail == nil || [self.txemail.text isEqualToString:#""])
{
UIAlertView *ErrorAlert = [[UIAlertView alloc] initWithTitle:#"Email"message:#"All Fields are mandatory." delegate:nil cancelButtonTitle:#"OK"otherButtonTitles:nil, nil];
[ErrorAlert show];
}
else if(self.tx_phone == nil || [self.tx_phone.text isEqualToString:#""])
{
UIAlertView *ErrorAlert = [[UIAlertView alloc] initWithTitle:#"Phone"message:#"All Fields are mandatory." delegate:nil cancelButtonTitle:#"OK"otherButtonTitles:nil, nil];
[ErrorAlert show];
}
else if(self.txcomment == nil || [self.txcomment.text isEqualToString:#""])
{
UIAlertView *ErrorAlert = [[UIAlertView alloc] initWithTitle:#"Comment"message:#"All Fields are mandatory." delegate:nil cancelButtonTitle:#"OK"otherButtonTitles:nil, nil];
[ErrorAlert show];
}
else
{
//Here YOUR URL
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:#"MY URL"]];
//create the Method "GET" or "POST"
[request setHTTPMethod:#"POST"];
//Pass The String to server(YOU SHOULD GIVE YOUR PARAMETERS INSTEAD OF MY PARAMETERS)
NSString *userUpdate =[NSString stringWithFormat:#"name=%#&email=%#&phone=%#& comment=%#&",_txname.text,_txemail.text,_tx_phone.text,_txcomment.text,nil];
//Check The Value what we passed
NSLog(#"the data Details is =%#", userUpdate);
//Convert the String to Data
NSData *data1 = [userUpdate dataUsingEncoding:NSUTF8StringEncoding];
//Apply the data to the body
[request setHTTPBody:data1];
//Create the response and Error
NSError *err;
NSURLResponse *response;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
NSString *resSrt = [[NSString alloc]initWithData:responseData encoding:NSASCIIStringEncoding];
//This is for Response
NSLog(#"got response==%#", resSrt);
if(resSrt)
{
NSLog(#"got response");
}
else
{
NSLog(#"faield to connect");
}
{
UIAlertView *ErrorAlert = [[UIAlertView alloc] initWithTitle:#"Success"message:#"All Fields are mandatory." delegate:nil cancelButtonTitle:#"OK"otherButtonTitles:nil, nil];
[ErrorAlert show];
}
[self.view endEditing:YES];
self.txname.text=#"";
self.txemail.text=#"";
self.tx_phone.text=#"";
self.txcomment.text=#"";
}
}

do like
- (IBAction)submit:(id)sender {
if (![txname hasText]) {
[self showAlertView:#"Alert" message:#"name is empty"];
}
else if (![txemail hasText])
{
[self showAlertView:#"Alert" message:#"email is empty"];
}
else if ([self isValidEmailAddress:txemail.text] == NO)
{
[self showAlertView:#"Alert" message:#"Invaildemail"];
}
else
{
// call webservice for succes
}
Create the alertcontroller
- (void)showAlertView:(NSString*)title message:(NSString*)message
{
UIAlertController* alertMessage = [UIAlertController
alertControllerWithTitle:title
message:message
preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction* yesButton = [UIAlertAction
actionWithTitle:#"OK"
style:UIAlertActionStyleDefault
handler:^(UIAlertAction* action){
}];
[alertMessage addAction:yesButton];
[self presentViewController:alertMessage animated:YES completion:nil];
}
for email validation
- (BOOL)isValidEmailAddress:(NSString *)emailAddress
{
//Create a regex string
NSString *stricterFilterString = #"[A-Z0-9a-z._%+-]+#[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}" ;
//Create predicate with format matching your regex string
NSPredicate *emailTest = [NSPredicatepredicateWithFormat:
#"SELF MATCHES %#", stricterFilterString];
//return true if email address is valid
return [emailTest evaluateWithObject:emailAddress];
}
updated
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
if (textField == self.txname)
{
// Prevent crashing undo bug – see note below.
if(range.length + range.location > textField.text.length)
{
return NO;
}
NSUInteger newLength = [textField.text length] + [string length] - range.length;
return newLength <= 25;
}
return YES;
}

I did it in my code, Do like following Way:
- (IBAction)submit:(id)sender {
if (![self isFormValid]) {
return;
}
NSError *error;
if (!error)
{
UIAlertView *signupalert = [[UIAlertView alloc]initWithTitle:#"Congratulations" message:#"Record Added Successfully" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[signupalert show];
}
}
-(BOOL)isFormValid
{
NSString *emailRegEx =#"[A-Z0-9a-z._%+-]+#[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
NSPredicate *emailTest =[NSPredicate predicateWithFormat:#"SELF MATCHES %#",emailRegEx];
if (txname.text && txname.text.length==0)
{
[self showErrorMessage:#"Please enter name"];
return NO;
}
else if (tx_phone.text && tx_phone.text.length!=10)
{
[self showErrorMessage:#"Please enter valid phone number"];
return NO;
}
else if([emailTest evaluateWithObject: txemail.text]==NO)
{
[self showErrorMessage:#"Please enter Valid Email_id"];
return NO;
}
else if (txcomment.text && txcomment.text.length==0)
{
[self showErrorMessage:#"Please enter comment"];
return NO;
}
return YES;
}
-(void)showErrorMessage:(NSString *)message
{
UIAlertView *alertmessage = [[UIAlertView alloc]initWithTitle:#"Error" message:message delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[alertmessage show];
}

-(BOOL) NSStringIsValidEmail:(NSString *)checkEmail
{
BOOL stricterFilter = NO;
NSString *filter = #"^[A-Z0-9a-z\\._%+-]+#([A-Za-z0-9-]+\\.)+[A-Za-z]{2,4}$";
NSString *lstring = #"^.+#([A-Za-z0-9-]+\\.)+[A-Za-z]{2}[A-Za-z]*$";
NSString *emailRegex = stricterFilter ? stricterFilterString : laxString;
NSPredicate *emailTest = [NSPredicate predicateWithFormat:#"SELF MATCHES %#", emailRegex];
return [emailTest evaluateWithObject:checkEmail];
}

Related

i can't perform segue

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]

How to send app invitation to facebook friends from ios app

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

Priority execution of methods i iOS

I'm developing an application that should login to a remote service in the first view controller I create a UI to insert username and password.
When I press on the button login I make the following check:
I check if the field aren't empty with a simple if
From my button starts a segue to the internal view controller, before it shows me the internal view controller I added a method that should check if the user can login or not. In this method I call an external class in which I do the connection to the server to authenticate the user
The method to call the external class is the follow:
- (BOOL)loginSuccessWith:(NSString*)userName and:(NSString*)password {
ConnectionHandler *connectionHandler = [[ConnectionHandler alloc]init];
if ([connectionHandler startConnectionToServer:#"serverAddress" andUsername:userName withPassword:password andInstallationId:[[NSUserDefaults standardUserDefaults] objectForKey:#"instId"]]) {
return YES;
} else {
return NO;
}
}
As you can see if the method return YES or NO if the user can be logged or not.
In the ConnectionHandler class I wrote the following code:
#import "ConnectionHandler.h"
#interface ConnectionHandler() {
BOOL authenticated;
}
#end
#implementation ConnectionHandler
- (BOOL)startConnectionToServer:(NSString *)address andUsername:(NSString *)username withPassword:(NSString *)password andInstallationId:(NSString*) installationId {
if (![self sendRequestToURL:address withMethod:#"POST" withUsername:username withPassword:password andInstallationId: installationId]) {
NSLog(#"Impossibile connettersi");
return NO;
} else {
if (authenticated) {
return YES;
} else {
return NO;
}
}
}
- (id)sendRequestToURL:(NSString *)url withMethod:(NSString *)method withUsername:(NSString*)username withPassword:(NSString*)password andInstallationId:(NSString*)installationId {
NSURL *finalURL = [[NSURL alloc]init];
if ([method isEqualToString:#"POST"]) {
finalURL = [NSURL URLWithString:url];
} else {
NSLog(#"Metodo no previsto");
}
NSString *post = [NSString stringWithFormat:#"username=%#&password=%#&installationId=%#", username, password, installationId];
NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding];
NSString *postLength = [NSString stringWithFormat:#"%lu", (unsigned long)postData.length];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]init];
[request setURL:finalURL];
[request setHTTPMethod:method];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSURLConnection *connection = [NSURLConnection connectionWithRequest:request delegate:self];
if (connection) {
[connection start];
}
return connection;
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
self.responseData = [[NSMutableData alloc]init];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[self.responseData appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
// Parsing della risposta dal server parlare con Giancarlo per vedere che tipo di risposta ottengo
NSDictionary *json;
NSError *err;
json = [NSJSONSerialization JSONObjectWithData:self.responseData options:NSJSONReadingMutableLeaves error:&err];
if (err) {
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"AT Brain" message:#"Impossibile satbilire una connessione con il server" delegate:nil cancelButtonTitle:nil otherButtonTitles:#"OK", nil];
[alert show];
} else {
NSString *error_code = [NSString stringWithFormat:#"%#", [json objectForKey:#"error_code"]];
int success = [[json objectForKey:#"success"] intValue];
NSString *error_desc = [NSString stringWithFormat:#"%#", [json objectForKey:#"error_desc"]];
if ([self autenthicationOkWithErrorCode:error_code withSuccess:success andErrorDesc:error_desc]) {
authenticated = YES;
} else {
authenticated = NO;
}
}
}
- (BOOL)autenthicationOkWithErrorCode:(NSString*)error_code withSuccess:(int)success andErrorDesc:(NSString*)error_desc {
int errCode = [error_code intValue];
if (success == 1) {
return YES;
} else if (success == 0) {
if (errCode == 2) {
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"AT Brain" message:#"Controlla di aver inserito username, password e di avere un installationId" delegate:nil cancelButtonTitle:nil otherButtonTitles:#"OK", nil];
[alert show];
return NO;
}
if (errCode == 3) {
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"AT Brain" message:#"Credenziali non valide, inserisci username e password corrette" delegate:nil cancelButtonTitle:nil otherButtonTitles:#"OK", nil];
[alert show];
return NO;
}
if (errCode == 4) {
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"AT Brain" message:#"Utente non autorizzato ad accedere al servizio" delegate:nil cancelButtonTitle:nil otherButtonTitles:#"OK", nil];
[alert show];
return NO;
}
if (errCode == 5) {
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"AT Brain" message:#"L'utenza a cui stai cercando di accedere è già associata ad un utente diverso" delegate:nil cancelButtonTitle:nil otherButtonTitles:#"OK", nil];
[alert show];
return NO;
}
if (errCode == 6) {
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"AT Brain" message:#"Installation ID errato" delegate:nil cancelButtonTitle:nil otherButtonTitles:#"OK", nil];
[alert show];
return NO;
}
}
return NO;
}
I can connect to the server without problem, but before the - (void)connectionDidFinishLoading:(NSURLConnection *)connection is called it execute all the code in the - (BOOL)startConnectionToServer:(NSString *)address andUsername:(NSString *)username withPassword:(NSString *)password andInstallationId:(NSString*) installationId and it returns NO so the segue in the login view controller doesn't work because the method -(BOOL)shouldPerformSegueWithIdentifier:(NSString *)identifier sender:(id)sender returns NO.
So my problem is how to wait the execution of the method - (void)connectionDidFinishLoading:(NSURLConnection *)connection is done before execute the else section in method - (BOOL)startConnectionToServer:(NSString *)address andUsername:(NSString *)username withPassword:(NSString *)password andInstallationId:(NSString*) installationId?
I hope you understand my issue and I hope you will help me to fix it, thank you
NSURLConnection is asynchronous. You kick it off and it immediately returns. You get callbacks (such as connectionDidFinishLoading) when it completes. That's the point at which you can check for success and move onto the next step.
I assume that loginSuccessWith:and: is called on the main thread (this is a very strange name for a method; you probably meant loginWithUsername:password:). So it can't block waiting for a network request that may take a very long time to complete. You'd hang the entire UI.
The URL Loading System Programming Guide has a great deal of information on how to design this. Look first at NSURLSession, and if it doesn't meet your needs, then use the lower-level NSURLConnection. With NSURLSession, you can pass completion blocks that will run whenever the operation completes.

"Username already taken" double tap

When using the sign up flow in my app the alert view shows "Username already taken" when I double tap the signup button fast even though it's not taken. Is there a way to make sure that it want show the alert view when this happens or any other solution?
See my code below:
NSString *username = [self.usernameField.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
NSString *password = [self.passwordField.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
NSString *email = [self.emailField.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
if ([username length] == 0 || [password length] == 0 || [email length] == 0) {
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Oops!"
message:#"Make sure you enter a username, password, and email address with at least 5 characters!"
delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alertView show];
}
else {
PFUser *newUser = [PFUser user];
newUser.username = username;
newUser.password = password;
newUser.email = email;
[newUser signUpInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
if (error) {
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Sorry!"
message:[error.userInfo objectForKey:#"error"]
delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alertView show];
}
else
{
[self saveUserDefaults];
[self dismissViewControllerAnimated:YES completion:nil];
[self performSegueWithIdentifier:#"setupProfile" sender:self];
}
}];
}
}
set
setUserInteractionEnabled:NO
to your button on the First tap.
Which wont allow any tap until you set it
setUserInteractionEnabled:YES

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

Resources