Data (char*) appears corrupt when logged after pressing button - ios

I'm quite newbie to iphone programming.
The problem is when I push a button, a data will be destroyed.
I can't find where my code is wrong and why. Please help me.
This is overview of my program.
1. load text data from "sample.txt"
2. log the data
3. When I push a button, it logs the data again.
AppDelegate.h
#import <UIKit/UIKit.h>
#interface AppDelegate : UIResponder <UIApplicationDelegate>
#property (strong, nonatomic) UIWindow *window;
#property (strong, nonatomic) UIButton *myButton1;
#property (assign) unsigned char* bytePtr;
#end
AppDelegate.m:
~snip~
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
// Override point for customization after application launch.
self.window.backgroundColor = [UIColor whiteColor];
[self.window makeKeyAndVisible];
self.myButton1 = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[self.myButton1 setFrame:CGRectMake(0, 0, 100 ,100)];
[self.myButton1 addTarget:self action:#selector(button1DidPushed) forControlEvents:UIControlEventTouchUpInside];
[self.myButton1 setTitle:#"push" forState:UIControlStateNormal];
[self.window addSubview:self.myButton1];
[self load];
return YES;
}
- (void) load
{
NSString* path = [[NSBundle mainBundle] pathForResource:#"sample" ofType:#"txt"];
NSData* data = [NSData dataWithContentsOfFile:path];
self.bytePtr = (unsigned char *)[data bytes];
NSLog(#"%s", self.bytePtr);
}
- (void)button1DidPushed
{
UIAlertView *alerView = [[UIAlertView alloc] initWithTitle:#"Enter something..." message:#"" delegate:self cancelButtonTitle:#"Cancel" otherButtonTitles:#"OK", nil];
alerView.alertViewStyle = UIAlertViewStylePlainTextInput;
[alerView show];
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
NSString *title = [alertView buttonTitleAtIndex:buttonIndex];
if([title isEqualToString:#"OK"])
{
}
NSLog(#"%s", self.bytePtr);
}
~snip~
sample.txt:
abcdefghijklmnopqrstuvwxyz
output:
abcdefghijklmnopqrstuvwxyz
<----- When I push the button the mark similar to "?" will appear on output window.(I couldn't show it here(It's probabily ascii code 2(STX))) That is why I think the data is destroyed.
Environment:
xcode 6.0.1
Thanks.

The issue is that you are not retaining the NSData object:
- (void) load
{
NSString* path = [[NSBundle mainBundle] pathForResource:#"sample" ofType:#"txt"];
NSData* data = [NSData dataWithContentsOfFile:path]; // here
self.bytePtr = (unsigned char *)[data bytes];
NSLog(#"%s", self.bytePtr);
}
Once that method returns the NSData object will be destroyed and therefore the buffer pointed to by self.bytePtr is no longer valid.
To solve this issue change self.bytePtr to an NSData object and store that instead.

First of all, in order to receive your alertView:clickedButtonAtIndex: method call, you need to set your UIAlertView delegate to self.
[alertView setDelegate:self] // make sure you set UIAlertViewDelegate protocol on the method owner
Otherwise you should use an NSString object initialized using initWithData:encoding:.

Related

Why doesn’t iOS AWS Cognito login yield errors, yet doesn't execute its functions?

I'm trying to get my Cognito login to work.
The problem is that it's not working and I'm not getting error messages from AWS, or XCode. I've implemented it according to the tutorial and the AWS sample code (maybe wrongly?). I've tried to understand how the code works by adding a couple of NSlog's within the AWS cognito functions so that I know whether they get excecuted, but they do not show up in my console either. Why are these function not being run without even sending an error? Is there something obvious that I'm forgetting?
Here's the essential parts of my code
// loginviewcontroller.h
#import AWSCognitoIdentityProvider;
#interface LoginViewController : UIViewController <AWSCognitoIdentityPasswordAuthentication>
#property (nonatomic, strong) NSString * usernameText;
#end
loginviewcontroller.m file:
// loginviewcontroller.m
#property (nonatomic, strong) AWSTaskCompletionSource<AWSCognitoIdentityPasswordAuthenticationDetails*> *passwordAuthenticationCompletion;
- (IBAction)signInPressed:(UIButton *)sender {
self.passwordAuthenticationCompletion.result = [[AWSCognitoIdentityPasswordAuthenticationDetails alloc] initWithUsername:self.userName.text password:self.password.text];
NSLog(#"button pressed");};
-(void) getPasswordAuthenticationDetails: (AWSCognitoIdentityPasswordAuthenticationInput *) authenticationInput passwordAuthenticationCompletionSource: (AWSTaskCompletionSource<AWSCognitoIdentityPasswordAuthenticationDetails *> *) passwordAuthenticationCompletionSource {
//keep a handle to the completion, you'll need it continue once you get the inputs from the end user
self.passwordAuthenticationCompletion = passwordAuthenticationCompletionSource;}
-(void) didCompletePasswordAuthenticationStepWithError:(NSError*) error {
NSLog(#"didCompletePasswordAuthenticationStepWithError");
dispatch_async(dispatch_get_main_queue(), ^{
//present error to end user
if(error){
NSLog(#"Error");
[[[UIAlertView alloc] initWithTitle:error.userInfo[#"__type"]
message:error.userInfo[#"message"]
delegate:nil
cancelButtonTitle:nil
otherButtonTitles:#"Ok", nil] show];
}else{
NSLog(#"Success");
//dismiss view controller
[self dismissViewControllerAnimated:YES completion:nil];
}
});
appdelegate.h
//appdelegate.h
#import AWSCognitoIdentityProvider;
#interface AppDelegate : UIResponder <UIApplicationDelegate, AWSCognitoIdentityInteractiveAuthenticationDelegate>
#property(nonatomic,strong) LoginViewController* LoginViewController;
appdelegate.m:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
//setup AWS service config
AWSServiceConfiguration *serviceConfiguration = [[AWSServiceConfiguration alloc] initWithRegion:AWSRegionUSEast1 credentialsProvider:nil];
//create a pool
AWSCognitoIdentityUserPoolConfiguration *configuration = [[AWSCognitoIdentityUserPoolConfiguration alloc] initWithClientId:#"xxxxxx" clientSecret:#"xxxxxxx" poolId:#"us-east-1_xxxxxx"];
[AWSCognitoIdentityUserPool registerCognitoIdentityUserPoolWithConfiguration:serviceConfiguration userPoolConfiguration:configuration forKey:#"us-east-1_xxxxx"];
AWSCognitoIdentityUserPool *pool = [AWSCognitoIdentityUserPool CognitoIdentityUserPoolForKey:#"us-east-1_xxxxxx"];
pool.delegate = self;
return YES;
}
-(id<AWSCognitoIdentityPasswordAuthentication>) startPasswordAuthentication{
//implement code to instantiate and display login UI here
//return something that implements the AWSCognitoIdentityPasswordAuthentication protocol
NSLog(#"startpasswordauth AWS!");
return self.LoginViewController;
}
Also I did not understand this property line that's in the AWS github sample. The notation of *xxx I haven't see before. Here's the line:
#property (nonatomic, strong) AWSTaskCompletionSource<AWSCognitoIdentityPasswordAuthenticationDetails*> *passwordAuthenticationCompletion;
It's not mentioned in the tutorial, but without it
self.passwordAuthenticationCompletion.result = [[AWSCognitoIdentityPasswordAuthenticationDetails alloc] initWithUsername:self.userName.text password:self.password.text];
errors that the attribute is not found.
I have also tried this but delegate methods are not working.
Secondly, I tried with this code:
[AWSServiceManager.defaultServiceManager.defaultServiceConfiguration.credentialsProvider invalidateCachedTemporaryCredentials];
AWSCognitoIdentityUserPool *pool = [AWSCognitoIdentityUserPool CognitoIdentityUserPoolForKey:#"User"];
AppDelegate *delegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
self.user = [delegate.pool currentUser];
[[ self.user getSession:_userName.text password:_txtPassword.text validationData:nil ] continueWithSuccessBlock:^id _Nullable(AWSTask<AWSCognitoIdentityUserSession *> * _Nonnull task) {
//success, task.result has user session
dispatch_async(dispatch_get_main_queue(), ^{
if(task.error || task.isCancelled) {
[[[UIAlertView alloc] initWithTitle:task.error.userInfo[#"__type"]
message:task.error.userInfo[#"message"]
delegate:self
cancelButtonTitle:#"Ok"
otherButtonTitles:nil] show];
}else {
AWSCognitoIdentityUserSession *session = (AWSCognitoIdentityUserSession *) task.result;
NSString *tokenStr = [session.idToken tokenString];
[[NSUserDefaults standardUserDefaults]setObject:tokenStr forKey:#"token"];
[[NSUserDefaults standardUserDefaults]synchronize];
[self performSelectorOnMainThread:#selector(pushToDashbard) withObject:nil waitUntilDone:YES];
}});
return nil;
}]
If I am passing the right credentials then this is giving the token, with wrong credentials giving no error response.

'NSInternalInconsistencyException', reason: 'Could not load NIB in bundle: 'NSBundle in Xcode

I'm writing an iOS app that implements Google Cloud Messaging.
I want to receive the authorization token and print it on screen.
I installed everything necessary and I wrote the code following a tutorial on YouTube.
That's my code:
AppDelegate.h
#import <UIKit/UIKit.h>
#class ViewController;
#interface AppDelegate : UIResponder <UIApplicationDelegate>;
#property (strong, nonatomic) UIWindow *window;
#property (strong, nonatomic) ViewController *viewController;
#property (nonatomic) NSString *getton;
#end
AppDelegate.m
#import "AppDelegate.h"
#import "ViewController.h"
#import "GoogleCloudMessaging.h"
#implementation AppDelegate
#synthesize window = _window;
#synthesize viewController = _viewController;
#synthesize getton;
- (void) dealloc {
[_window release];
[_viewController release];
[super dealloc];
}
- (BOOL)application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
self.window = [[[UIWindow alloc] initWithFrame: [[UIScreen mainScreen] bounds]] autorelease];
[[UIApplication sharedApplication] registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge) categories:nil]];
[[UIApplication sharedApplication] registerForRemoteNotifications];
self.viewController = [[[ViewController alloc] initWithNibName:#"LaunchScreen.storyboard" bundle:nil] autorelease];
self.window.rootViewController = self.viewController;
[self.window makeKeyAndVisible];
return YES;
}
- (void)application:(UIApplication *)app didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
[self registerDeviceToken: deviceToken];
}
- (void) registerDeviceToken:(NSData *)deviceToken {
NSLog(#"Device Token: %#", deviceToken);
NSMutableString *string=[[NSMutableString alloc] init];
int length=[deviceToken length];
char const *bytes=[deviceToken bytes];
for (int i=0; i<length; i++) {
[string appendString:[NSString stringWithFormat:#"%02.2hhx",bytes[i]]];
}
NSLog(#"%#",string);
[self performSelectorInBackground:#selector(connectionWebRegister:)withObject:string];
[string release];
}
-(void) connectionWebRegister:(NSString *) deviceTokenString {
NSAutoreleasePool *pool = [NSAutoreleasePool new];
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"http://serviceProvider/registerTokenId?tokenId=%#&app=",deviceTokenString]];
NSLog(#"APNS URL : %#",url);
NSData * res = [NSData dataWithContentsOfURL:url];
getton=deviceTokenString;
if (res!=nil) {
NSString *response = [[NSString alloc] initWithBytes: [res bytes] lenght:[res length] encoding: NSUTF8StringEncoding];
NSLog(#"%#", response);
[response release];
}
[pool drain];
}
- (void)application:(UIApplication *)app didReceiveRemoteNotification:(NSDictionary *)userInfo
{
NSLog(#"test");
NSMutableDictionary * test = [userInfo objectForKey:#"aps"];
UIAlertView * alert = [[UIAlertView alloc] initWithTitle:#"MESSAGE"
message:[test objectForKey:#"alert"]
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
[alert release];
}
#end
ViewController.h and ViewController.m are both empty.
But when simulator starts, it crashes with this error:
<'NSInternalInconsistencyException', reason: 'Could not load NIB in
bundle: 'NSBundle' > with an < Thread 1: signal SIGABRT > error in
Main.m .
I have searched a lot on internet to solve that problem, but I could not solve it.
So, are there somebody, who can help me? Thanks!
If you storyboard with mentioned name in question exists then
You should use,
UIStoryboard *storyboardobj=[UIStoryboard storyboardWithName:#"LaunchScreen" bundle:nil];
self.viewController = [storyboardobj instantiateInitialViewController];
instead of
self.viewController = [[[ViewController alloc] initWithNibName:#"LaunchScreen.storyboard" bundle:nil] autorelease];

How to show username on each page of app,fetching it from a textfield on login page?

I want to show the username,of the user logged into the app from the login page/view, on all the views of the app. The code of the login page having two textfields and a button is shown below:
- (IBAction)btnLogin:(id)sender
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docsPath = [paths objectAtIndex:0];
NSString *path = [docsPath stringByAppendingPathComponent:#"contacts.db"];
FMDatabase *database = [FMDatabase databaseWithPath:path];
if ([txtUser.text length] == 0 || [txtPass.text length]== 0){
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"Error" message:#"Kindly enter details in all fields" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles: nil];
[alert show];
}
[database open];
BOOL success = NO;
NSInteger count = [database intForQuery:#"select count(*) from RegMembers where USERNAME = ? and PASSWORD = ?", txtUser.text, txtPass.text];
}
If it is just a single character you can use appDelegate to store the value and access it in all the view controllers. If you have more than one data, its better to use a singleton class
Just use
AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication]delegate];
EDIT : adding details about using appdelegate
In AppDelegate.h
#interface AppDelegate : UIResponder <UIApplicationDelegate>
#property (strong,nonatomic) NSString *username;
In AppDelegate.m
#implementation AppDelegate
#synthesize username;
In your LoginViewController.h, import the AppDelegate
#import "AppDelegate.h"
#interface LoginViewController : UIViewController
{
AppDelegate *appDelegate;
}
In your LoginViewController.m
- (void) viewDidLoad
{
[super viewDidLoad];
appDelegate = (AppDelegate *)[[UIApplication sharedApplication]delegate];
//Do other stuff
}
- (IBAction)btnLogin:(id)sender
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docsPath = [paths objectAtIndex:0];
NSString *path = [docsPath stringByAppendingPathComponent:#"contacts.db"];
FMDatabase *database = [FMDatabase databaseWithPath:path];
if ([txtUser.text length] == 0 || [txtPass.text length]== 0){
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"Error" message:#"Kindly enter details in all fields" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles: nil];
[alert show];
}
else
{
appDelegate.username = txtUser.text;
}
[database open];
BOOL success = NO;
NSInteger count = [database intForQuery:#"select count(*) from RegMembers where USERNAME = ? and PASSWORD = ?", txtUser.text, txtPass.text];
}
In anyOtherViewController where you want to access it, do the following in its .h file
import "AppDelegate.h"
#interface AnyOtherViewController : UIViewController
{
AppDelegate *appDelegate;
}
And in it's .m file do the following
-(void) viewDidLoad {
AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication]delegate];
NSLog (#"%#",appDelegate.username);
}
You access the username using
appDelegate.username;
EDIT 2: Displaying username
- (void) viewDidLoad
{
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(250, 0, 70, 30)];
[label setText:appDelegate.username];
[self.view addSubview : label];
}
Add the above code in the view controllers and you can see the username on the top rightside of that view controller when you run the app.
You are using Database.You can save it in a seperate table.
Or
save as a variable [NSString] in appdelgate and use it anywhere
OR
NSUserdefaults
Best Practise is to inherit UIViewController and have your own parent view controller
.h
#interface UIMainViewController : UIViewController {
}
#property(nonatomic,strong) UITextField *loggedInUsernameTextField;
#end
.m
#implementation UIMainViewController
- (void)viewDidLoad {
[super viewDidLoad];
_loggedInUsernameTextField = #"Whatever name";
}
#end
You can use NSUserDefaults
To Save:
-(IBAction)btnLogin:(id)sender
{
if(yourConditions)
{
...
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
[userDefaults setValue:self.txtLoginName.text forKey:#"loginName"];
[userDefaults synchronize];
}
}
To Retrieve:
- (void)viewDidLoad
{
[super viewDidLoad];
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
NSString *str = [userDefaults valueForKey:#"loginName"];
}
Developer Guid of NSUserDefaults: https://developer.apple.com...

i want navigate to another file in webview.

i want to call objective c file from javascript.
- (void)viewDidLoad
{
webview.delegate = self;
myButton.enabled = NO;
NSString *path=[[NSBundle mainBundle]pathForResource:#"1" ofType:#"html" inDirectory:#"files"];
NSURL *url=[NSURL fileURLWithPath:path];
NSURLRequest *request=[NSURLRequest requestWithURL:url];
[webview loadRequest:request];}
i am using this code to call my html page successfully and i use the below code to call shouldStartLoadWithRequest method in objective c.
<img src="cercle24px.png" />
now i went to call new TestViewController.m file how to i call this file, i used the below code.its print the nslog correctly and give alert box also.but doesn't navigate to next file.please help me if any one know.i am waiting for your valuable reply please.
- (BOOL)webView:(UIWebView*)webview shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType)navigationType
{
NSLog(#"what");
UIAlertView *tstAlert = [[UIAlertView alloc] initWithTitle:#"" message:#"Allowed only alphabets and numeric" delegate:self cancelButtonTitle:nil otherButtonTitles:#"Ok",nil];
[tstAlert show];
NSString *absoluteUrl = [[request URL] absoluteString];
NSLog(#"absolute%#",absoluteUrl);
if ([absoluteUrl isEqualToString:#"didtap://button1"]) {
NSLog(#"yes");
TestViewController *testview=[[TestViewController alloc]initWithNibName:#"TestViewController" bundle:nil];
[self.navigationController pushViewController:testview animated:YES];
return NO;
}
NSLog(#"no");
return YES;
}
Alright, I copy & tested your code, it works well, maybe somewhere else did wrong...
Create a new "Empty Template" Xcode project with ARC enabled, paste below into AppDelegat.m:
//
// AppDelegate.m
// WebTest
//
// Created by Elf Sundae on 8/5/13.
// Copyright (c) 2013 www.0x123.com. All rights reserved.
//
#import "AppDelegate.h"
#interface SampleViewController : UITableViewController
#end
#implementation SampleViewController
- (void)viewDidLoad
{
[super viewDidLoad];
self.title = #"Sample Controller";
}
#end
#pragma mark -
#interface WebViewController : UIViewController <UIWebViewDelegate>
#end
#implementation WebViewController
- (void)viewDidLoad
{
[super viewDidLoad];
UIWebView *web = [[UIWebView alloc] initWithFrame:self.view.bounds];
web.delegate = self;
[self.view addSubview:web];
[web loadHTMLString:#"<a href='didTap://button1'><img src='cercle24px.png' /></a>" baseURL:nil];
}
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request
navigationType:(UIWebViewNavigationType)navigationType
{
UIAlertView *alert = [[UIAlertView alloc]
initWithTitle:nil message:#"alert message" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[alert show];
NSString *urlString = request.URL.absoluteString;
if ([urlString caseInsensitiveCompare:#"didtap://button1"] == NSOrderedSame) {
#define __use_method 3 // it could be: 1/2/3
#if (__use_method == 1)
SampleViewController *controller = [[SampleViewController alloc] init];
[self.navigationController pushViewController:controller animated:YES];
#elif (__use_method == 2)
/* method 2 */
SampleViewController *controller = [[SampleViewController alloc] init];
[self.navigationController performSelector:#selector(pushViewController:animated:)
withObject:controller
withObject:#(YES)];
#elif (__use_method == 3)
/* method 3 */
__unsafe_unretained __typeof(self) _self = self;
double delayInSeconds = 0.01;
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
SampleViewController *controller = [[SampleViewController alloc] init];
[_self.navigationController pushViewController:controller animated:YES];
});
#endif
return NO;
}
return YES;
}
#end
#pragma mark -
#implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
[self.window makeKeyAndVisible];
self.window.rootViewController = [[UINavigationController alloc] initWithRootViewController:
[WebViewController new]];
return YES;
}
#end

Network Error Alert in Xcode Needed Urgently

I recently started an Xcode project, and its mostly web-based, in the sense it mostly works with UIWebView. I am a total noob at this. I would like to make an "No Internet Connection Alert". Basically An Alert that comes up if you have no internet connection. I have tried using the Reachability but since I'm such a noob, I didn't manage to figure ANYTHING out.. Heres my view controller:
This is my .h file: P.S: My WebView is called 'webone'.
#import <UIKit/UIKit.h>
#interface FirstViewController : UIViewController
-(IBAction)refreshClicks:(id)sender;
#property (weak, nonatomic) IBOutlet UIWebView *webone;
#end
And This is My .m file:
#import "FirstViewController.h"
#interface FirstViewController ()
#end
#implementation FirstViewController
#synthesize webone;
-(void)viewDidLoad {
NSURL *url = [NSURL URLWithString:#"http://www.lostcraft.net/mobile"];
NSURLRequest *req = [NSURLRequest requestWithURL:url];
[webone loadRequest:req];
[super viewDidLoad];
}
-(void)awakeFromNib{ //IGNORE
[self refreshClicks:self]; //IGNORE
}
-(IBAction)refreshClicks:(id)sender{//IGNORE
[webone loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:#"http://www.lostcraft.net/mobile"]]];//IGNORE
}
- (void)viewDidUnload
{
[self setWebone:nil];
[super viewDidUnload];
// Release any retained subviews of the main view.
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
} else {
return YES;
}
}
Place this in your .m file
Under Your IBAction:
NSString *web = #"http://YOUR WEB ADRESS HERE";
NSURL *url = [NSURL URLWithString:web];
NSURLRequest *requestUrl = [NSURLRequest requestWithURL:url];
[webdone loadRequest:requestUrl];
Then somewhere in your .m
-(void)webView:(UIWebView *)webdone didFailLoadWithError:(NSError *)error {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Error" message:#"Please check your internet connection" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
}
go into connections tab in interface builder in xcode
Right click from the delegate as shown in the picture (the top option) and drag it to your view contoller where you have your web view (webdone)

Resources