Handling NSError with error.code - ios

I am trying to handle specific NSErrors with UIAlertView but none of the codes in the if statements are called when the webview didFailLoadWithError is called. Below is my condition statement:
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
{
loadFailedBool = YES;
NSLog(#"Error code %ld", (long)[error code]);
if ([error code] != -999) {
//loading was cancelled and another one initiated. Don't show alert
return;
}
else if ([error code] == NSURLErrorTimedOut || [error code] == kCFURLErrorTimedOut) {
//connection timed out
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Alert" message:#"Network Connection timed out" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[alert show];
alert.tag = 1;
}
else if ([error code] == -1005) {
//connection lost
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Alert" message:#"Network Connection to the host is lost" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[alert show];
alert.tag = 1;
}
else if ([error code] == kCFURLErrorNotConnectedToInternet || [error code] == -1009) {
//no internet connection
NSLog(#"Error here");
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Alert" message:#"Looks like you are not connected to the internet" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[alert show];
alert.tag = 1;
}
else if ([error.domain isEqualToString:#"WebKitErrorDomain"] && error.code == 102) {
return;
}
}
My question is, how do i get the condition called because the log prints -1009 sometimes when there is no internet. Thanks

The thing is that you will never get past this line:
if ([error code] != -999) {
return;
}
So if the error code is -1009, or anything but -999, it's too late - you have already said return and the whole thing is over. The later code won't execute.

Related

Multiple if-else conditions in ios [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Improve this question
I have a sign-up view controller that contains multiple text fields to register the user.
I need to validate all the text fields such as not empty, valid email, username, password etc. and display the alert message for all different condition.
Now I following the approach as:
if (condition) {
if (condition) {
if (condition) {
} else {
[alert show];
}
} else {
[alert show];
}
} else {
[alert show];
}
I know this is not the best approach. So guys please suggest an appropriate way to do that task.
Thanks,
Multiple If else Condition
NSString *emailRegEx = #"[A-Z0-9a-z._%+-]+#[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
NSPredicate *emailTest = [NSPredicate predicateWithFormat:#"SELF MATCHES %#", emailRegEx];
NSString *mobileRegex = #"[0-9]{6,14}$";
NSPredicate *mobileTest = [NSPredicate predicateWithFormat:#"SELF MATCHES %#", mobileRegex]
if (txtName.text.length == 0)
{
[[[UIAlertView alloc]initWithTitle:#"Alert" message:#"Please Enter Name" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil, nil] show];
}
else if (txtMobile.text.length == 0)
{
[[[UIAlertView alloc]initWithTitle:#"Alert" message:#"Please Enter Mobile Number" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil, nil] show];
}
else if ([mobileTest evaluateWithObject:txtMobile.text] == NO)
{
[[[UIAlertView alloc]initWithTitle:#"Alert" message:#"Please Enter valid Mobile Number" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil, nil] show];
}
else if (txtMobile.text.length < 10)
{
[[[UIAlertView alloc]initWithTitle:#"Alert" message:#"Please Enter valid Phone Number" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil, nil] show];
}
else if (txtMobile.text.length > 10)
{
[[[UIAlertView alloc]initWithTitle:#"Alert" message:#"Please Enter valid Phone Number" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil, nil] show];
}
else if (txtEmail.text.length == 0)
{
[[[UIAlertView alloc]initWithTitle:#"Alert" message:#"Please Enter Email" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil, nil] show];
}
else if ([emailTest evaluateWithObject:txtEmail.text] == NO)
{
[[[UIAlertView alloc]initWithTitle:#"Alert" message:#"Please Enter valid Email" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil, nil] show];
}
else
{
//success Code
}
Here isAllFieldsAreValid() will validate all the fields you can add all the validation here.
showAlert is a method to show alert about error.
allTrim() is a macro that will trim whitespace.
- (BOOL)isAllFieldsAreValid {
//here only empty string is checked you can add other if-else to validate email, phno, etc.
if ([allTrim(self.txtFname.text) isEqualToString:#""]) {
[self showAlert:#"Please enter first name."];
return false;
} else if ([allTrim(self.txtLname.text) isEqualToString:#""]) {
[self showAlert:#"Please enter last name."];
return false;
} else if ([allTrim(self.txtEmail_SignUp.text) isEqualToString:#""]) {
[self showAlert:#"Please enter email id."];
return false;
} else if ([allTrim(self.txtPassword_SignUp.text) isEqualToString:#""]) {
[self showAlert:#"Please enter password."];
return false;
}
return true;
}
You can call this on button click and upon true and false you can take action.
- (IBAction)buttonTappedInLoginView:(UIButton *)sender {
if ([self isAllFieldsAreValid]) {
// do stuff
}
}
Use this code,
if (firstnametf.text.length==0 || lastnametf.text.length==0 || emailtf.text.length==0 || myimageView.image == nil || commenttf.text.length==0 || [commenttf.text isEqualToString:#"Comment"])
{
[self validatetextfield];
}
else if (![emailtf.text isEqualToString:#""])
{
NSString *emailRegEx = #"[A-Z0-9a-z._%+-]+#[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
NSPredicate *emailTest = [NSPredicate predicateWithFormat:#"SELF MATCHES %#", emailRegEx];
//Valid email address
if ([emailTest evaluateWithObject:emailtf.text] == YES)
{
//All conditions are checked, you will set the function
}
else if ()
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Test!" message:#"Please Enter Valid Email Address. \nex. fdsjfkd#mail.com" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
}
}
}
Method:
-(void) validatetextfield
{
if (firstnametf.text.length==0) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Firstname Field Empty!" message:#"Please Enter the Valid Details" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
[firstnametf becomeFirstResponder];
}
else if (lastnametf.text.length==0)
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Lastname Field Empty!" message:#"Please Enter the Valid Details" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
[lastnametf becomeFirstResponder];
}
else if (emailtf.text.length==0)
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Email Field Empty!" message:#"Please Enter the Valid Details" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
[emailtf becomeFirstResponder];
}
else if(commenttf.text.length==0)
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Comment Field Empty!" message:#"Please Enter the Valid Details" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
[commenttf becomeFirstResponder];
}
else if ([commenttf.text isEqualToString:#"Comment"])
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Comment Field Empty!" message:#"Please Enter the Valid Details" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
[commenttf becomeFirstResponder];
}
else if (myimageView.image == nil)
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Image not Upload!" message:#"Please Upload Image" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
}
}
Change the Alert condition, hope its helpful

UIAlertView query. Returning to where the UIAlertView was called within a loop

I am trying to use an UIAlertView within a loop and respond to the choice made at that time within the loop. This does not happen as is demonstrated by the following test code:
- (IBAction)testAction:(id)sender {
for(loop=0; loop<5; loop++)
{
NSLog(#"Loop: %d", loop);
if (loop==1)
{
UIAlertView *alert = [[UIAlertView alloc]initWithTitle: #"" message:[NSString stringWithFormat:#"%d?", loop] delegate: self cancelButtonTitle:#"0" otherButtonTitles:#"1", nil];
[alert setTag:1];
[alert show];
NSLog(#"Pressed: %d", alertPressed);
}
if (loop==4)
{
UIAlertView *alert = [[UIAlertView alloc]initWithTitle: #"" message:[NSString stringWithFormat:#"%d?", loop] delegate: self cancelButtonTitle:#"3" otherButtonTitles:#"4", nil];
[alert setTag:2];
[alert show];
NSLog(#"Pressed: %d", alertPressed);
}
}
}
-(void) alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
if (alertView.tag == 1)
{
alertPressed=buttonIndex;
}
if (alertView.tag == 2)
{
alertPressed=buttonIndex+2;
}
}
The log looks like this:
alerttest[893:18299] Loop: 0
alerttest[893:18299] Loop: 1
alerttest[893:18299] Pressed: 0
alerttest[893:18299] Loop: 2
alerttest[893:18299] Loop: 3
alerttest[893:18299] Loop: 4
alerttest[893:18299] Pressed: 0
The loop runs to its completion before the alert is shown on the screen, and it clearly doesn't post the value of alertPressed since the it doesn't return to where the UIAlertView was called at runtime. While this test has helped me understand what is actually happening is there a solution to this?
I strongly suggest refactoring your code to properly leverage the event system if you're trying to get user responses. However, you could change your code to do this (if you really want to):
- (IBAction)testAction:(id)sender {
for(; loop<5; loop++)
{
NSLog(#"Loop: %d", loop);
if (loop==1)
{
UIAlertView *alert = [[UIAlertView alloc]initWithTitle: #"" message:[NSString stringWithFormat:#"%d?", loop] delegate: self cancelButtonTitle:#"0" otherButtonTitles:#"1", nil];
[alert setTag:1];
[alert show];
break;
}
if (loop==4)
{
UIAlertView *alert = [[UIAlertView alloc]initWithTitle: #"" message:[NSString stringWithFormat:#"%d?", loop] delegate: self cancelButtonTitle:#"3" otherButtonTitles:#"4", nil];
[alert setTag:2];
[alert show];
break;
}
}
}
-(void) alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
if (alertView.tag == 1)
{
alertPressed=buttonIndex;
NSLog(#"Pressed: %d", alertPressed);
loop++;
[self testAction:nil];
}
if (alertView.tag == 2)
{
alertPressed=buttonIndex+2;
NSLog(#"Pressed: %d", alertPressed);
loop=0;
[self testAction:nil];
}
}

Xcode forgot password Parse

- (IBAction)forgotPassword:(id)sender {
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Direccion de Correo" message:#"Introduzca su correo electronico:" delegate:self cancelButtonTitle:#"Cancelar" otherButtonTitles:#"Aceptar", nil];
alertView.alertViewStyle = UIAlertViewStylePlainTextInput;
[alertView show];
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
if(buttonIndex ==1){
NSLog(#"ok button clicked in forgot password alert view");
NSString *email=[alertView textFieldAtIndex:0].text;
if ([email isEqualToString:#"email"]) {
UIAlertView *display;
display=[[UIAlertView alloc] initWithTitle:#"Email" message:#"Please enter password for resetting password" delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles: nil];
[display show];
}else{
[PFUser requestPasswordResetForEmailInBackground:email block:^(BOOL succeeded, NSError *error) {
UIAlertView *display;
if(succeeded){
display=[[UIAlertView alloc] initWithTitle:#"Correo electronico enviado" message:#"Por favor, revise su correo para resetear contraseƱa" delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles: nil];
}else{
display=[[UIAlertView alloc] initWithTitle:#"Correo fallido" message:#"el correo electronico no coincide con ninguno en la base de datos" delegate:nil cancelButtonTitle:#"Cancel" otherButtonTitles: nil];
}
[display show];
}];
}
}
}
Why you are going for multiple queries first to find User details if found send ResetPasswordRequest instead use completion handler for Reset Request.
[PFUser requestPasswordResetForEmailInBackground:self.txtEmail.text block:^(BOOL succeeded,NSError *error)
{
if (!error) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:kAlertTitle message:[NSString stringWithFormat: #"Link to reset the password has been send to specified email"] delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles:nil];
[alert show];
return;
}
else
{
NSString *errorString = [error userInfo][#"error"];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:kAlertTitle message:[NSString stringWithFormat: #"Password reset failed: %#",errorString] delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles:nil];
[alert show];
return;
}
}];
If user is not present Parse will respond with an error "Error: no user found with email xxxxxxxxx#xxx.com"
Regards,
Amit
In your below code,
//Here you fire the query to check for email address in your parse backend
[query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
if (!error) { //If no error in your query then will enter below block
//the objects is array of object it gets from your parse but in your case it return's zero which implies that there is no object with that email in your parse db.
if (objects.count ==0) {
//As objects.count is zero that means no email exist so in that case you don't send email for password recovery and show a alert as below to user that email is invalid(meaning not exist)
UIAlertView *alertView =[[UIAlertView alloc]initWithTitle:#"Correo enviado" message:#"Por favor, revise su correo para resetear su contraseƱa" delegate:self cancelButtonTitle:#"Cancelar" otherButtonTitles:nil];
[alertView show];
} else {
//In this, else case will enter when there is objects.count greater than zero which means that email exist on db. So, in that case you would request for password recovery as below.
//Also could show a alert to let user know that request for password recovery was sent successfully.
[self sendEmail:emailTextField.text];
//the query was successful, but found 0 results
//email does not exist in the database, dont send the email
//show your alert view here
}
} else {
NSLog(#"Error: %# %#", error, [error userInfo]);
}
}];
Why are again checking condition(objects == nil) as your doing in first condition(object.count == 0). Both are same so no point in showing alert for one reason. Also I ran your code and I was getting one alert to enter some text followed by a alert with title "Correo enviado".
If I misunderstand your query or anything else then please let me know.

retrying a request after it failed

I am using the default classes provided by app to do my networking tasks in my app.
At some point, some of my requests time out (regardless of the reason for the timeout)
I would like to retry some of these requests
I have subclassed the NSURLConnection class and added some parameters to it.
However, in the method "connection:didFailWithError:"
con.retries seems to always be 1, never incremented. Why ?
- (void)connection:(NSURLConnection*) connection didFailWithError:(NSError *)error
{
[[UIApplication sharedApplication]setNetworkActivityIndicatorVisible:NO];
NSLog(#"%#",[NSString stringWithFormat:#"Did recieve error: %#", [error description]]);
NSLog(#"%#",[NSString stringWithFormat:#"%#", [[error userInfo]description]]);
WBURLConnection *con = (WBURLConnection *)connection;
if([con shouldRetryRequest:error]){
con.retries ++;
[con start];
}else{
[con cancel];
[con.data setLength:0];
if(!self.alert){
self.alert = [[UIAlertView alloc]initWithTitle:#"Alert" message:[error localizedDescription] delegate:nil cancelButtonTitle:#"OK" otherButtonTitles: nil];
[self.alert show];
}else {
if(![self.alert isVisible]){
[self.alert show];
}
}
}
}
-(BOOL)shouldRetryRequest:(NSError *)error{
[self.retryCount appendString:[NSString stringWithFormat:#"%#:%ld",error,(long)self.retries]];
LogInfo(#"retries:%#",self.retryCount);
if([error code] == -1004){
return NO;
}
return self.retries<3;
}

iOS Incompatible block pointer types issue

I have an implementation problem with a project using MKStoreKit. I am trying to implement an UIAlertView with various purchase options.
Here is the code where I do various things and call up UIAlertView:
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
{
if(FALSE == payWallFlag)
{
// Display Alert Dialog
UIAlertView *message = [[UIAlertView alloc] initWithTitle:#"Subscription Options"
message:#"You do not have an active subscription. Please purchase one of the options below."
delegate:self
cancelButtonTitle:#"Cancel"
otherButtonTitles:nil];
[message addButtonWithTitle:#"7 Day Subscription $0.99"];
[message show];
return FALSE;
} else if(TRUE == payWallFlag)
{
// Load content
}
}
This is the physical alertView with the code which I am trying to call:
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
NSString *title = [alertView buttonTitleAtIndex:buttonIndex];
if([title isEqualToString:#"Cancel"])
{
NSLog(#"Cancel Button was selected.");
}
else if([title isEqualToString:#"7 Day Subscription $0.99"])
{
NSLog(#"7 Day Subscription button pressed.");
//Buy a 7 day subscription
if([SKPaymentQueue canMakePayments]) {
[[MKStoreManager sharedManager] buyFeature:kFeatureAId onComplete:^(NSString* purchasedFeature)
{
NSLog(#"Purchased: %#", purchasedFeature);
// Send an alert to the user
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Purchase Successful"
message:#"Thank you. You have successfully purchased a 7 Day Subscription."
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert autorelease];
[alert show];
// Show the user the content now
payWallFlag = TRUE;
return TRUE;
}
onCancelled:^
{
// Send an alert to the user
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Purchase Failed"
message:#"Unfortunately you have cancelled your purchase of a 7 Day Subscription. Please try again."
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert autorelease];
[alert show];
// Block the content again
payWallFlag = FALSE;
}];
}
else
{
NSLog(#"Parental control enabled");
// Send an alert to the user
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Purchase Failed"
message:#"Unfortunately Parental Controls are preventing you from purchasing a subscription. Please try again."
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert autorelease];
[alert show];
// Block the content again
payWallFlag = FALSE;
}
}
}
The issue is I get the following Xcode error message in the UIAlertView:
Incompatible block pointer types sending 'int (^)(NSString *)' to parameter of type 'void (^)(NSString *)'
It appears the problems are: onComplete:^(NSString* purchasedFeature) and onCancelled:^ but I have no idea how to fix this.
You should not return TRUE; from that block, because then the compiler assumes that block returns an int, while it should return void (hence incompatible block types).
...onComplete:^(NSString* purchasedFeature) {
NSLog(#"Purchased: %#", purchasedFeature);
// Send an alert to the user
UIAlertView *alert = [[UIAlertView alloc] ...];
[alert autorelease];
[alert show];
// Show the user the content now
payWallFlag = TRUE;
return TRUE; // <--- Remove this line.
}...
For the second block (the onCancelled one), you probably missed the NSString* parameter, or whatever it expects.

Resources