UIWebView and authentication challenge unable to authenticate - ios

http://m-qa-www.comixology.net/ this is the url when i am loading it on safari it works great.
but when i load it on uiwebview it does not do anything because of authentication challenge so i added support for authentication it works in for some url but it does not work for this above url.following is the code i am using for it.
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType;
{
[self showNetworkIndicator];
if (!authed && !conectionAlready) {
authed = NO;
conectionAlready=YES;
urlCon=[[NSURLConnection alloc] initWithRequest:request delegate:self];
return YES;
}
return YES;
}
- (void)webViewDidStartLoad:(UIWebView *)webView
{
NSLog(#"webViewDidStartLoad");
[webView stringByEvaluatingJavaScriptFromString:#"window.alert=null;"];
[self showNetworkIndicator];
authed=NO;
}
-(void) webViewDidFinishLoad:(UIWebView *)webView
{
//conectionAlready=NO;
//[iWebView stringByEvaluatingJavaScriptFromString:#"window.alert=null;"];
NSString *currentURL = webView.request.URL.absoluteString;
NSLog(#"current url %#",currentURL);
URLBar.text=currentURL;
if([iWebView canGoBack])
{
[backButton setEnabled:true];
}
else
{
[backButton setEnabled:false];
}
if([iWebView canGoForward])
{
[fwdButton setEnabled:true];
}
else
{
[fwdButton setEnabled:false];
}
[self hideNetworkIndicator];
}
-(void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
{
NSLog(#"url error ->%#",error.localizedDescription);
[self hideNetworkIndicator];
NSString *errorStr=error.localizedDescription;
if ([errorStr rangeOfString:#"NSURLErrorDomain"].location==NSNotFound) {
UIAlertView *alert=[[UIAlertView alloc] initWithTitle:nil message:#"A server with the specified hostname could not be found." delegate:self cancelButtonTitle:#"Ok" otherButtonTitles:nil, nil];
[alert show];
}
}
-(void) showNetworkIndicator
{
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
}
-(void) hideNetworkIndicator
{
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
}
- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge;
{
authed = YES;
authChallenge=challenge;
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Aithentication Required"
message:scRequest.URL.absoluteString
delegate:self cancelButtonTitle:#"Cancel"
otherButtonTitles:#"Log In", nil];
[alert setAlertViewStyle:UIAlertViewStyleLoginAndPasswordInput];
[alert show];
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response;
{
[connection cancel];
conectionAlready=NO;
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
if ([response respondsToSelector: # selector (allHeaderFields)]) {
NSDictionary * dictionary = [httpResponse allHeaderFields];
NSLog (# "dictionary =%#", dictionary);
}
if (authed)
{
NSLog(#"remote url returned error %d %#",[httpResponse statusCode],[NSHTTPURLResponse localizedStringForStatusCode:[httpResponse statusCode]]);
NSLog(#"The response is =%#",response);
authed=YES;
NSString *newUrl = [NSString stringWithFormat:#"%#", response.URL];
NSLog(#"newURL%#",newUrl);
scURL =[NSURL URLWithString:newUrl];
scRequest=[NSMutableURLRequest requestWithURL:scURL];
conectionAlready=NO;
[iWebView loadRequest:scRequest];
}
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
[self hideNetworkIndicator];
authed=NO;
conectionAlready=NO;
NSLog(#"oops localizedDescription:%#",error.localizedDescription);
NSLog(#"oops localizedFailureReason:%#",error.localizedFailureReason);
}
- (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)buttonIndex
{
//NSLog(#"textFieldAtIndex0 %#",[alert textFieldAtIndex:0].text);
//NSLog(#"textFieldAtIndex1 %#",[alert textFieldAtIndex:1].text);
if (buttonIndex==0) {
[[authChallenge sender] cancelAuthenticationChallenge:authChallenge];
}
else
{
[[authChallenge sender] useCredential:[NSURLCredential credentialWithUser:[[alert textFieldAtIndex:0] text] password:[[alert textFieldAtIndex:1] text] persistence:NSURLCredentialPersistenceNone] forAuthenticationChallenge:authChallenge];
}
}
- (BOOL)connectionShouldUseCredentialStorage:(NSURLConnection *)connection;
{
return YES;
}

Remember the webView is not so competent as a native browser. The native browser handles internally many exception which the webView is not at all competent of. I would suggest if you have the code for the link that you are hitting than try traversing the code and find errors for which the webView doesn't load. I encountered the same issue where some of my JS file were non-responsive. There is no other way you can find bugs in a webView,as it provides limited set of delegated to actually traverse. :)

Related

IOS- XMPP - Authenticate and alertview on login button

Currently i am working on XMPP protocol in ios for chatting application. i want to put alert view and authentication on Login button. if authentication will successful then user can see homescreen screen else alert view will appear please check username and password i show chat secure open source project but i can't understand.
//appdelegate.m file .//
- (BOOL)connect
{
if (![xmppStream isDisconnected]) {
return YES;
// isauthenticate=YES;
}
NSString *myJID = [[NSUserDefaults standardUserDefaults] stringForKey:kXMPPmyJID];
NSString *myPassword = [[NSUserDefaults standardUserDefaults] stringForKey:kXMPPmyPassword];
//
// If you don't want to use the Settings view to set the JID,
// uncomment the section below to hard code a JID and password.
//
// myJID = #"user#gmail.com/xmppframework";
// myPassword = #"";
if (myJID == nil || myPassword == nil) {
return NO;
}
[xmppStream setMyJID:[XMPPJID jidWithString:myJID]];
password = myPassword;
NSError *error = nil;
if (![xmppStream connectWithTimeout:XMPPStreamTimeoutNone error:&error])
{
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Error connecting"
message:#"See console for error details."
delegate:nil
cancelButtonTitle:#"Ok"
otherButtonTitles:nil];
[alertView show];
DDLogError(#"Error connecting: %#", error);
return NO;
}
return YES;
}
- (void)disconnect
{
[self goOffline];
[xmppStream disconnect];
}
#pragma mark UIApplicationDelegate
- (void)applicationDidEnterBackground:(UIApplication *)application
{
DDLogVerbose(#"%#: %#", THIS_FILE, THIS_METHOD);
#if TARGET_IPHONE_SIMULATOR
DDLogError(#"The iPhone simulator does not process background network traffic. "
#"Inbound traffic is queued until the keepAliveTimeout:handler: fires.");
#endif
if ([application respondsToSelector:#selector(setKeepAliveTimeout:handler:)])
{
[application setKeepAliveTimeout:600 handler:^{
DDLogVerbose(#"KeepAliveHandler");
// Do other keep alive stuff here.
}];
}
}
- (void)applicationWillEnterForeground:(UIApplication *)application
{
DDLogVerbose(#"%#: %#", THIS_FILE, THIS_METHOD);
}
- (void)applicationWillTerminate:(UIApplication *)application
{
DDLogVerbose(#"%#: %#", THIS_FILE, THIS_METHOD);
[self teardownStream];
}
#pragma mark XMPPStream Delegate
- (void)xmppStream:(XMPPStream *)sender socketDidConnect:(GCDAsyncSocket *)socket
{
DDLogVerbose(#"%#: %#", THIS_FILE, THIS_METHOD);
}
- (void)xmppStream:(XMPPStream *)sender willSecureWithSettings:(NSMutableDictionary *)settings
{
DDLogVerbose(#"%#: %#", THIS_FILE, THIS_METHOD);
NSString *expectedCertName = [xmppStream.myJID domain];
if (expectedCertName)
{
settings[(NSString *) kCFStreamSSLPeerName] = expectedCertName;
}
if (customCertEvaluation)
{
settings[GCDAsyncSocketManuallyEvaluateTrust] = #(YES);
}
}
- (void)xmppStream:(XMPPStream *)sender didReceiveTrust:(SecTrustRef)trust
completionHandler:(void (^)(BOOL shouldTrustPeer))completionHandler
{
DDLogVerbose(#"%#: %#", THIS_FILE, THIS_METHOD);
// The delegate method should likely have code similar to this,
// but will presumably perform some extra security code stuff.
// For example, allowing a specific self-signed certificate that is known to the app.
dispatch_queue_t bgQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(bgQueue, ^{
SecTrustResultType result = kSecTrustResultDeny;
OSStatus status = SecTrustEvaluate(trust, &result);
if (status == noErr && (result == kSecTrustResultProceed || result == kSecTrustResultUnspecified)) {
completionHandler(YES);
}
else {
completionHandler(NO);
}
});
}
- (void)xmppStreamDidSecure:(XMPPStream *)sender
{
DDLogVerbose(#"%#: %#", THIS_FILE, THIS_METHOD);
}
- (void)xmppStreamDidConnect:(XMPPStream *)sender
{
DDLogVerbose(#"%#: %#", THIS_FILE, THIS_METHOD);
isXmppConnected = YES;
NSError *error = nil;
if (![[self xmppStream] authenticateWithPassword:password error:&error])
{
DDLogError(#"Error authenticating: %#", error);
}
}
- (void)xmppStreamDidAuthenticate:(XMPPStream *)sender
{
isauthenticate=YES;
DDLogVerbose(#"%#: %#", THIS_FILE, THIS_METHOD);
[self goOnline];
}
- (void)xmppStream:(XMPPStream *)sender didNotAuthenticate:(NSXMLElement *)error
{
DDLogVerbose(#"%#: %#", THIS_FILE, THIS_METHOD);
}
i have tried with setting BOOL(isauthenticate) in xmppStreamDidAuthenticate method but not success. i can redirect to homepage but if i wrote wrong detail still it will redirect to homepage. i want to set it if username or password are wrong and did not authenticate by server.
//view controller.m file //
#import "ViewController.h"
#import "AppDelegate.h"
#interface ViewController ()<MBProgressHUDDelegate>
{
MBProgressHUD *HUD;
IBOutlet UITextField *mViewEmail;
IBOutlet UITextField *mViewPassword;
}
#end
NSString *const kXMPPmyJID = #"kXMPPmyJID";
NSString *const kXMPPmyPassword = #"kXMPPmyPassword";
#implementation ViewController
- (IBAction)checkLogin:(id)sender {
NSLog(#"Email: %# Password: %#",mViewEmail.text,mViewPassword.text);
[self setField:mViewEmail forKey:kXMPPmyJID];
[self setField:mViewPassword forKey:kXMPPmyPassword];
// if (appdelegate.connect==YES) {
if([ [self appDelegate] connect]) {
// if (appdelegate.isauthenticate==YES) {
HUD = [MBProgressHUD showHUDAddedTo:self.navigationController.view animated:YES] ;
HUD.delegate = self;
HUD.color = [UIColor blackColor];
HUD.labelText = #"Please Wait";
HUD.dimBackground = YES;
// HUD.detailsLabelText = #"Close chat";
[self showHome];
//}
}
//}
else
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Sorry"
message:#"Please Check Username or Password"
delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
}
}
- (void)showHome{
[self performSegueWithIdentifier:#"signIn" sender:self];
}
ok. so finaly my problem is solved. and i am posting my answer. first of all my mistake is i forgot to write
appdelegate = (AppDelegate*)[[UIApplication sharedApplication]delegate];
appdelegate.viewController = self; // very imp when you call method in app delegate.h
in my view controller. so when i call viewcontroller's method in appdelegate it call's but do not execute due to above method is missing (Second line). and then i have call view controller's segue method in - (void)xmppStreamDidAuthenticate:(XMPPStream *)sender method. and then work perfectly. so my final solution is
//app delegate.m file//
- (BOOL)connect
{
// Setup HUD(Activity Indicator) when Connect method call //
HUD = [[MBProgressHUD alloc] initWithWindow:[UIApplication sharedApplication].keyWindow]; [self.window.rootViewController.view addSubview:HUD];
[HUD setDetailsLabelText:#"Please wait..."];
[HUD setDimBackground:YES];
[HUD setOpacity:0.5f];
[HUD show:YES];
if (![xmppStream isDisconnected]) {
return YES;
}
NSString *myJID = [[NSUserDefaults standardUserDefaults] stringForKey:kXMPPmyJID];
NSString *myPassword = [[NSUserDefaults standardUserDefaults] stringForKey:kXMPPmyPassword];
if (myJID == nil || myPassword == nil) {
return NO;
}
[xmppStream setMyJID:[XMPPJID jidWithString:myJID]];
password = myPassword;
NSError *error = nil;
if (![xmppStream connectWithTimeout:XMPPStreamTimeoutNone error:&error])
{
HUD.hidden=YES;
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Error connecting"
message:#"See console for error details."
delegate:nil
cancelButtonTitle:#"Ok"
otherButtonTitles:nil];
[alertView show];
DDLogError(#"Error connecting: %#", error);
return NO;
}
return YES;
}
- (void)disconnect
{
[self goOffline];
[xmppStream disconnect];
}
#pragma mark UIApplicationDelegate
- (void)applicationDidEnterBackground:(UIApplication *)application
{
DDLogVerbose(#"%#: %#", THIS_FILE, THIS_METHOD);
#if TARGET_IPHONE_SIMULATOR
DDLogError(#"The iPhone simulator does not process background network traffic. "
#"Inbound traffic is queued until the keepAliveTimeout:handler: fires.");
#endif
if ([application respondsToSelector:#selector(setKeepAliveTimeout:handler:)])
{
[application setKeepAliveTimeout:600 handler:^{
DDLogVerbose(#"KeepAliveHandler");
// Do other keep alive stuff here.
}];
}
}
- (void)applicationWillEnterForeground:(UIApplication *)application
{
DDLogVerbose(#"%#: %#", THIS_FILE, THIS_METHOD);
}
- (void)applicationWillTerminate:(UIApplication *)application
{
DDLogVerbose(#"%#: %#", THIS_FILE, THIS_METHOD);
[self teardownStream];
}
#pragma mark XMPPStream Delegate
- (void)xmppStream:(XMPPStream *)sender socketDidConnect:(GCDAsyncSocket *)socket
{
DDLogVerbose(#"%#: %#", THIS_FILE, THIS_METHOD);
}
- (void)xmppStream:(XMPPStream *)sender willSecureWithSettings:(NSMutableDictionary *)settings
{
DDLogVerbose(#"%#: %#", THIS_FILE, THIS_METHOD);
NSString *expectedCertName = [xmppStream.myJID domain];
if (expectedCertName)
{
settings[(NSString *) kCFStreamSSLPeerName] = expectedCertName;
}
if (customCertEvaluation)
{
settings[GCDAsyncSocketManuallyEvaluateTrust] = #(YES);
}
}
- (void)xmppStream:(XMPPStream *)sender didReceiveTrust:(SecTrustRef)trust
completionHandler:(void (^)(BOOL shouldTrustPeer))completionHandler
{
DDLogVerbose(#"%#: %#", THIS_FILE, THIS_METHOD);
dispatch_queue_t bgQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(bgQueue, ^{
SecTrustResultType result = kSecTrustResultDeny;
OSStatus status = SecTrustEvaluate(trust, &result);
if (status == noErr && (result == kSecTrustResultProceed || result == kSecTrustResultUnspecified)) {
completionHandler(YES);
}
else {
completionHandler(NO);
}
});
}
- (void)xmppStreamDidSecure:(XMPPStream *)sender
{
DDLogVerbose(#"%#: %#", THIS_FILE, THIS_METHOD);
}
- (void)xmppStreamDidConnect:(XMPPStream *)sender
{
DDLogVerbose(#"%#: %#", THIS_FILE, THIS_METHOD);
isXmppConnected = YES;
NSError *error = nil;
if (![[self xmppStream] authenticateWithPassword:password error:&error])
{
DDLogError(#"Error authenticating: %#", error);
}
}
- (void)xmppStreamDidAuthenticate:(XMPPStream *)sender
{
HUD.hidden=YES; //Hud Will be hide when User Authenticated
DDLogVerbose(#"%#: %#", THIS_FILE, THIS_METHOD);
[self.viewController showHome]; // view controllers method to go to next view controller //
[self goOnline];
}
- (void)xmppStream:(XMPPStream *)sender didNotAuthenticate:(NSXMLElement *)error
{
// HUD will be hidden and alertview will be shown //
HUD.hidden=YES;
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Sorry"
message:#"Please Check Username or Password"
delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
isauthenticate=NO;
DDLogVerbose(#"%#: %#", THIS_FILE, THIS_METHOD);
{
NSLog(#"error = %#", error);
}
}
and in viewcontroller.m we have show that viewcontroller is also appdelegate controller. so we have to declare it in - (void)viewDidLoad method.
// viewcontroller.m file//
- (void)viewDidLoad
{
[super viewDidLoad];
appdelegate = (AppDelegate*)[[UIApplication sharedApplication]delegate];
appdelegate.viewController = self;
}
- (AppDelegate *)appDelegate
{
return (AppDelegate *)[[UIApplication sharedApplication] delegate];
}
- (IBAction)checkLogin:(id)sender {
[self dismissKeyboard];
NSLog(#"Email: %# Password: %#",mViewEmail.text,mViewPassword.text);
[self setField:mViewEmail forKey:kXMPPmyJID];
[self setField:mViewPassword forKey:kXMPPmyPassword];
[[self appDelegate ]connect];//call when loginbutton pressed
}
//call in appdelegate.h // segue(push) to next view
- (void)showHome
{
[self performSegueWithIdentifier:#"signIn" sender:self];
}
Note: I have tried to explain as much as i can.
If username and password are correct then xmppStreamDidAuthenticate method call and if one of them is incorrect then didNotAuthenticate method call.
- (void)xmppStreamDidAuthenticate:(XMPPStream *)sender
{
}
- (void)xmppStream:(XMPPStream *)sender didNotAuthenticate:(NSXMLElement *)error
{
NSLog(#"error = %#", error);
}
Here print error and display this error in UIALertview as you required.
Actually you are checking XMPP connection that is not means Authenticate User. if your User Name and password is correct then you received response in xmppStreamDidAuthenticate method. where you can write the code to push to HomeViewController once user is verified.
Below two methods, you can used to show alert or push to another view once user varified.
- (void)xmppStreamDidAuthenticate:(XMPPStream *)sender
{
}
- (void)xmppStream:(XMPPStream *)sender didNotAuthenticate:(NSXMLElement *)error
{
NSLog(#"Error");
}
this is XMPP Delegate methods
Hope this help you.

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

NSURLConnection Authentication Challenge even if it is not supposed to

I can do authentication with NSURL and user can assign username and password. However, I got another problem. If I open this, http://html5test.com/ , it also pop up and ask username and password. I got authentication even if it is not supposed to get. I would like to know how to do.
-(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
if(!_auth)
{
connection_for_auto = [[NSURLConnection alloc] initWithRequest:request delegate:self];
firsttimeonly=TRUE;
[connection_for_auto start];
NSLog(#"Request >> %# and !firsttimeonly",request);
return NO;
}
self.lbl_error.hidden = YES; //hide error message label
return YES;
}
- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
{
checkTochangeUIalert=TRUE;
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Login"
message:nil
delegate:self
cancelButtonTitle:#"Cancel"
otherButtonTitles:#"OK",#"Auto", nil];
alertView.transform=CGAffineTransformMakeScale(1.0, 0.75);
alertView.alertViewStyle = UIAlertViewStyleLoginAndPasswordInput;
[alertView show];
}
I think I have found a way to do. I need to check what kind of authentication method I use.
if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodHTTPBasic] || [challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodNTLM])
{
.............
}

Login and Password Input with NSURLConnection

I am a newbie in the development of iOS applications.
I need to reach different url loaded from a remote XML file,
some of these url require a http basic authentication.
Authentication with NSURLCredential, it works correctly.
Now, I want to require the user to enter their credentials.
When the connection fails I visualize the interface
login UIAlertView with setAlertViewStyle:UIAlertViewStyleLoginAndPasswordInput.
At this point I verify the correspondence
username and password entered by the user with textFieldAtIndex: 0 and 1
but I can and use them for a new connection attempt with NSURLConnection.
Can someone help me?
This is my code:
- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge {
if ([challenge previousFailureCount] == 0)
{
NSLog(#"received authentication challenge");
NSURLCredential *newCredential;
newCredential=[NSURLCredential credentialWithUser:#""
password:#""
persistence:NSURLCredentialPersistenceForSession];
NSLog(#"credential created");
[[challenge sender] useCredential:newCredential forAuthenticationChallenge:challenge];
NSLog(#"responded to authentication challenge");
}
else
{
NSLog(#"previous authentication failure");
UIAlertView *message = [[UIAlertView alloc] initWithTitle:#"Login"
message:#"Enter your username & password"
delegate:self
cancelButtonTitle:#"Cancel"
otherButtonTitles:#"Login", nil];
[message setAlertViewStyle:UIAlertViewStyleLoginAndPasswordInput];
[message show];
}
}
- (BOOL)alertViewShouldEnableFirstOtherButton:(UIAlertView *)alertView
{
NSString *inputText = [[alertView textFieldAtIndex:0] text];
if( [inputText length] >= 1 )
{
return YES;
}
else
{
return NO;
}
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
NSString *title = [alertView buttonTitleAtIndex:buttonIndex];
if([title isEqualToString:#"Login"])
{
UITextField *username = [alertView textFieldAtIndex:0];
UITextField *password = [alertView textFieldAtIndex:1];
NSLog(#"Username: %#\npassword: %#", username.text, password.text);
if ([username.text isEqualToString:#"myname"] && [password.text isEqualToString:#"1234"])
NSLog(#"Success");
}
[xmlDataBuffer setLength:0];
}

ios - Network / Internet Connection

After hours of searching on google I still cant find a single topic about this one:
1. I need to put error handling functions if the user does not have internet connection.
2. the user have internet connection but cant connect to the server .
And where can I put these? I tried one topic but it don't show the alert view message.
Here is my code:
- (IBAction)getDataPressed
{
if([myRequest_ isExecuting])
{
return;
}
if(myRequest_ != nil)
{
[myRequest_ release];
}
myRequest_ = [[ASIHTTPRequest alloc]initWithURL:[NSURL URLWithString:URL_PATH]];
myRequest_.delegate = self;
[myRequest_ startAsynchronous];
}
#pragma ASI Delegate methods
- (void)requestFinished:(ASIHTTPRequest *)request
{
NSLog(#"Request finished successfully");
NSLog(#"%#",[request responseString]);
NSDictionary *responseDictionary = [[request responseString]JSONValue];
NSDictionary *arrayElement = [responseDictionary objectForKey:#"user"];
NSString *ID = [arrayElement valueForKeyPath:#"id"];
NSLog(#"id: %#",ID);
NSString *usr = [arrayElement valueForKeyPath:#"usr"];
NSLog(#"usr: %#",usr);
NSString *gd = [arrayElement valueForKeyPath:#"gd"];
NSLog(#"gd: %#",gd);
NSString *ag = [arrayElement valueForKeyPath:#"ag"];
NSLog(#"ag: %#",ag);
NSString *st = [arrayElement valueForKeyPath:#"st"];
NSLog(#"st: %#",st);
NSString *lf = [arrayElement valueForKeyPath:#"lf"];
NSLog(#"lf: %#",lf);
NSString *da = [arrayElement valueForKeyPath:#"da"];
NSLog(#"da: %d",da);
for(NSString *value in [arrayElement allValues]){
NSLog(#"Found Value %#",value);
label.text = [value stringByAppendingFormat:#",%#,%#,%#,%#,%#,%#,",ID,usr,gd,ag,st,lf];
}
}
- (void)requestFailed:(ASIHTTPRequest *)request
{
NSLog(#"Error %#", [request error]);
if([request error])
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Error" message:#"Destination Unreachable" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
[alert release];
}
}
-(void) dealloc
{
[super dealloc];
}
Thanks to those who will help ^_^
I think you could try the Reachbility application to help you out checking if you have internet or not. As for the server itself, you can use the NSUrlConnection Delegate methods to check if there was a problem with your request (by seeing the kind of HTTP code that comes)

Resources