Why I am not getting UIAlertView [duplicate] - ios

This question already has answers here:
Why isn't UIAlertView Showing?
(4 answers)
Closed 7 years ago.
I am using parse for sign-in/sign-up process.
Everything is working fine. Until user gives wrong details.
In else part of Parse Login I have written:
self.view.userInteractionEnabled = YES;
[SVProgressHUD dismiss];
// The login failed. Check error to see why.
NSString *message = [NSString stringWithFormat:#"%#",[error valueForKey:#"Error"]];
UIAlertView *myalert = [[UIAlertView alloc]initWithTitle:#"SO" message:message delegate:self cancelButtonTitle:#"Cancel" otherButtonTitles: nil];
[myalert show];
I checked after putting breakpoints in every line.
After executing the 3rd Line i.e. NSSString *message the control doesn't go for alert it directly shows me UI without any alert box.
And In Log I am getting
[Error]: invalid login parameters (Code: 101, Version: 1.7.5)
I doesn't know what to do ? I have written only this code in else part.
I am using Parse Code :
[user signUpInBackgroundWithBlock:^(BOOL succeeded, NSError *error)
{
if (!error)
{
// Hooray! Let them use the app now.
}
else
{
NSString *errorString = [error userInfo][#"error"]; // Show the errorString somewhere and let the user try again.
}
}];
and In else part I want to show and alertView

Try this :
UIAlertView *myalert = [[UIAlertView alloc]initWithTitle:#"SO" message:message delegate:self cancelButtonTitle:#"Cancel" otherButtonTitles: nil];
dispatch_async(dispatch_get_main_queue(), ^(void){
[myalert show];
});

Try this code
NSString *errorString;
UIAlertView *AV;
[user signUpInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
if (!error) { // Hooray! Let them use the app now.
} else { errorString = [error userInfo][#"error"]; // Show the errorString somewhere and let the user try again.
AV = [[UIAlertView alloc]initWithTitle:#"SO" message:errorString delegate:nil cancelButtonTitle:#"Cancel" otherButtonTitles:nil, nil];
[AV show];
}
}];

try to call main thread first then create the UIAlert in it
coz mostly thats happen when you are not in the main thread
hope this solve your problem goodluck

Related

System hangs when showing a UIAllertView inside a SLRequestHandler

I am using SLRequest to send user's video to twitter. After finishing the post request, I want to inform the user whether the upload is successful. But if I show a UIAlertView inside the SLRequestHandler, the system simply hangs and doesn't show the alert view at all. Is it a no-go to have a UIAlertView inside the SLRequestHandler? What is the better way to show a custom message based on the result of the post request?
Here is my sample code:
SLRequest *postRequest2 = [SLRequest
requestForServiceType:SLServiceTypeTwitter
requestMethod:SLRequestMethodPOST
URL:requestURL2 parameters:message2];
postRequest2.account = twitterAccount;
[postRequest2
performRequestWithHandler:^(NSData *responseData,
NSHTTPURLResponse *urlResponse, NSError *error)
{
if (error != nil) {
NSLog(#"error: %#", error);
}
else {
UIAlertView *theAlert = [[UIAlertView alloc] initWithTitle:#"Success!"
message:#"Your video is now available in your Twitter account"
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[theAlert show];
}
}];
All UI related operations must be on the main thread.
Would you try to dispatch on the main thread your alert view?
dispatch_async(dispatch_get_main_queue(), ^{
UIAlertView *theAlert = [[UIAlertView alloc] initWithTitle:#"Success!" message:#"Your video is now available in your Twitter account" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[theAlert show];
});
Please note that UIAlertView is deprecated since iOS 8, and the use of UIAlertViewController is recommended.
You are trying to show the alert message in a block.
Alerts are UI Thread (main thread) controls. So, modify else part and show your alert in dispatch_async, it will work.
dispatch_async(dispatch_get_main_queue(), ^{
[theAlert show];
});

Touch ID for login iOS

I'm making an iOS application (Obj-c) with a login form. I'm trying to figure out if there is a way to use Touch ID to login. This will be an amazing feature for my app, but I can't find a way to do it.
In the last PayPal update they include the Touch ID login - so there is a way to do it.
EDIT: I know how to get if the user enter the correct Touch ID, but I don't know what to do after that.
What if the user enter his username and then add the Touch ID correctly? How could I know this user have this Touch ID?
Okay first create an action like so:
We need more detail tough, as I do not know if you mean Obj-C or swift, I'll just post both.
Obj-C
Firstly import the local authentication framework
#import <LocalAuthentication/LocalAuthentication.h>
Then we create an IBAction and add the following code:
- (IBAction)authenticateButtonTapped:(id)sender {
LAContext *context = [[LAContext alloc] init];
NSError *error = nil;
if ([context canEvaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics error:&error]) {
[context evaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics
localizedReason:#"Are you the device owner?"
reply:^(BOOL success, NSError *error) {
if (error) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Error"
message:#"There was a problem verifying your identity."
delegate:nil
cancelButtonTitle:#"Ok"
otherButtonTitles:nil];
[alert show];
return;
}
if (success) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Success"
message:#"You are the device owner!"
delegate:nil
cancelButtonTitle:#"Ok"
otherButtonTitles:nil];
[alert show];
} else {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Error"
message:#"You are not the device owner."
delegate:nil
cancelButtonTitle:#"Ok"
otherButtonTitles:nil];
[alert show];
}
}];
} else {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Error"
message:#"Your device cannot authenticate using TouchID."
delegate:nil
cancelButtonTitle:#"Ok"
otherButtonTitles:nil];
[alert show];
}
}
The just connect your IBAction to a button that will prompt authentication.
However in Swift you would use:
Add the following framework to your project: LocalAuthentication
Then import it in your swift file:
import LocalAuthentication
Then create the following method that will prompt you to use touch id:
func authenticateUser() {
// Get the local authentication context.
let context = LAContext()
// Declare a NSError variable.
var error: NSError?
// Set the reason string that will appear on the authentication alert.
var reasonString = "Authentication is needed to access your notes."
// Check if the device can evaluate the policy.
if context.canEvaluatePolicy(LAPolicy.DeviceOwnerAuthenticationWithBiometrics, error: &error) {
[context .evaluatePolicy(LAPolicy.DeviceOwnerAuthenticationWithBiometrics, localizedReason: reasonString, reply: { (success: Bool, evalPolicyError: NSError?) -> Void in
if success {
}
else{
// If authentication failed then show a message to the console with a short description.
// In case that the error is a user fallback, then show the password alert view.
println(evalPolicyError?.localizedDescription)
switch evalPolicyError!.code {
case LAError.SystemCancel.rawValue():
println("Authentication was cancelled by the system")
case LAError.UserCancel.rawValue():
println("Authentication was cancelled by the user")
case LAError.UserFallback.rawValue():
println("User selected to enter custom password")
self.showPasswordAlert()
default:
println("Authentication failed")
self.showPasswordAlert()
}
}
})]
}
else{
// If the security policy cannot be evaluated then show a short message depending on the error.
switch error!.code{
case LAError.TouchIDNotEnrolled.rawValue():
println("TouchID is not enrolled")
case LAError.PasscodeNotSet.rawValue():
println("A passcode has not been set")
default:
// The LAError.TouchIDNotAvailable case.
println("TouchID not available")
}
// Optionally the error description can be displayed on the console.
println(error?.localizedDescription)
// Show the custom alert view to allow users to enter the password.
self.showPasswordAlert()
}
}
Lastly from the func viewDidLoad call the function like so: authenticateUser()
Hope that helps. Keep coding.
Sources:
Swift:
App Coda iOS 8 Touch ID Api
Objective-C:
tutPlus iOS Touch ID
Thanks to Matt Logan for the updated swift code.
I think I understand what I have to do!
After the first user Login I'll save his password (at NSUserdefaults for example).
If the user want to use his Touch ID at the next login - I'll ask him for the Touch ID and if it's correct i'll let him in with the password saved at the beginning.
Thanks to Julian :)

How to show an alert in ios for paper out error from zebra printer?

I'm trying to show an alert from my app. When my app is successfully connected with zebra printer and then if the printer doesnot have paper at the time of printing.. i want to show an alert in my app about the paper out error... please sunbmit your answers if anybody knows...
What exactly you are looking for? Do you want to know the code for how to create and show an alert? or do you want to interact with printer and get the status so as to show alert?
If you are looking for code that shows an alert here you go..
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Printer Warning" message:#"Printer running out of paper" delegate:self cancelButtonTitle:#"OK" otherButtonTitles: nil];
[alertView show];
have u used this block?
void (^completionhandler)(UIPrintInteractionController *, BOOL, NSError *) = ^(UIPrintInteractionController *print, BOOL completed, NSError *error)
{
if (!completed && error)
{
NSLog(#"%#", error.localisedDescription);
}
};
if any error occurs, the error will be logged and u can also use it in AlertView.
if(!completed && error)
{
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:error.localisedDescription cancelButtonTitle:nil otherButtons:#"OK", nil];
[alertview show];
}

Parse - Sign Up and Login at the same time

Using Parse (iOS framework), I am able to sign up and login successfully using two API.
When user log in, it will cache the user and so accessing "currentUser" will return appropriate object. But sign up API is not caching.
Is there any way that sign up itself will cache the user and avoid separate log in functionality?
It should automatically log you in as well. For example, if in your completion block in signUpInBackground, you have a segue to your main screen and in your main screen, it is supposed to show information related to the user, then it will because [PFUser currentUser] is set to the user that registered.
here is an example
[user signUpInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
if (error) {
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:[[error userInfo] objectForKey:#"error"] message:nil delegate:self cancelButtonTitle:nil otherButtonTitles:#"Ok", nil];
[alertView show];
// Bring the keyboard back up, because they'll probably need to change something.
[_usernameField becomeFirstResponder];
}
else{
// Success!
[self performSegueWithIdentifier:#"goToMain" sender:self];
}
}];

Using case switch instead of multiple if statements for error handling

I am building an application which has a login through a mobile SAAS - Parse.
There are multiple error codes that could be returned from a login request. At the moment run an if statement for each error code and display a relevant alert view like this:
if (error == nil) {
// Something went wrong
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(#"LoginAlertErrorTitle", #"Login Error Alert View Title") message:NSLocalizedString(#"LoginStandardError", #"Login error message text - standard error") delegate:self cancelButtonTitle:nil otherButtonTitles:NSLocalizedString(#"GlobalOKButtonTitle", #"Global Ok button title"), nil];
[alertView show];
} else if ([error code] == kPFErrorObjectNotFound) {
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(#"LoginAlertErrorTitle", #"Login Error Alert View Title") message:NSLocalizedString(#"LoginErrorObjectNotFound", #"Login error message text - object not found") delegate:self cancelButtonTitle:nil otherButtonTitles:NSLocalizedString(#"GlobalOKButtonTitle", #"Global Ok button title"), nil];
[alertView show];
} else if ([error code] == kPFErrorConnectionFailed) {
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(#"LoginAlertErrorTitle", #"Login Error Alert View Title") message:NSLocalizedString(#"LoginAlertErrorConnection", #"Login error message text - connection failed") delegate:self cancelButtonTitle:nil otherButtonTitles:NSLocalizedString(#"GlobalOKButtonTitle", #"Global Ok button title"), nil];
[alertView show];
} else {
NSLog(#"A Login error occurred: %i",[error code]);
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(#"LoginAlertErrorTitle", #"Login Error Alert View Title") message:[[error userInfo] objectForKey:#"error"] delegate:self cancelButtonTitle:nil otherButtonTitles:NSLocalizedString(#"GlobalOKButtonTitle", #"Global Ok button title"), nil];
[alertView show];
}
Is there a more efficient way to do the same with case/switching?
The actual error codes are setup like this:
/*! #abstract 100: The connection to the Parse servers failed. */
extern NSInteger const kPFErrorConnectionFailed;
Which makes me think I can setup this in a case statement. Would this be the correct/best way to approach this? Should it be in a separate method like handleErrorAlert: possibly?
How would I code this switch in the example above?
Whether you use a switch statement or a series of if-else if is really just a matter of taste in this case. Yes, the switch statement is slightly more efficient, but in a case like this, it really doesn't matter (it's not like you call this thousands of times per second). Use what you find more readable.
You might want to refactor your alert view code a little though – you're doing the same thing in all cases with only the error message being different, so there's quite a bit of repeated code. You could refactor it like this:
NSString *errorMessage = nil;
if (error == nil) {
errorMessage = NSLocalizedString(#"LoginStandardError", #"Login error message text - standard error");
} else {
switch ([error code]) {
case kPFErrorObjectNotFound:
errorMessage = NSLocalizedString(#"LoginErrorObjectNotFound", #"Login error message text - object not found");
break;
case kPFErrorConnectionFailed:
errorMessage = NSLocalizedString(#"LoginAlertErrorConnection", #"Login error message text - connection failed");
break;
default:
errorMessage = [[error userInfo] objectForKey:#"error"];
}
}
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(#"LoginAlertErrorTitle", #"Login Error Alert View Title")
message:errorMessage
delegate:self
cancelButtonTitle:nil
otherButtonTitles:NSLocalizedString(#"GlobalOKButtonTitle", #"Global Ok button title"), nil];
[alertView show];
A typedef enum being used on a switch, I think it would be the cleanest way. Something like this:
typedef enum
{
kServerError,
kInternetError,
kUnknowError
} kTypeError;
switch (aTypeError)
{
.
.
.
}
In your specific case, you take care about the message inside the switch... The UIAlertView is a common part. So:
NSString *aTitle = nil;
NSString *aMessage = nil;
switch (aTypeError)
{
case kUnknowError:
{
aTitle = ...;
aMessage = ...;
}
break;
}
UIAlertView *alertView = [UIAlertView alloc] ...
if (!error) {
// Handle error (?).
}
switch ([error code]) {
case kPFErrorObjectNotFound:
// Handle error.
break;
case kPFErrorConnectionFailed:
// Handle error.
break;
default:
// Handle error.
}
This only works if the value returned by -code can be used in a switch test expression. AFAIK, int is supported—I don't know about other types.

Resources