I'm wondering why I don't get alert when I disconnect my internet connection. When I'm connected everything is going great, but when there is no connection, simply nothing appears, I'm pretty new in objective-c but I think this code looks correct.
Thanks for help anyway.
- (void)viewDidLoad
{
webView.hidden = YES;
NSURL *url = [NSURL URLWithString:#"https://url"];
webView.scrollView.scrollEnabled = NO;
NSURLRequest *requestURL = [NSURLRequest requestWithURL:url];
[webView loadRequest:requestURL];
if ([[webView stringByEvaluatingJavaScriptFromString:#"document.readyState"] isEqualToString:#"complete"]) {
webView.hidden = NO;
}
self.canDisplayBannerAds = YES;
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
-(void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"No Internet Connection!"
message:#"Can't connect. Please check your internet Connection"
delegate:self
cancelButtonTitle:#"Close"
otherButtonTitles:nil];
[alert show]; }
- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex {
exit(0);
}
If you want to check the connectivity with internet then you have to check it in your code. For this you can go through Apple's Reachbility code.
The method webView:didFailLoadWithError: will called if page could not be loaded due to some reason. This means it's not connectivity issue, this may be due to some internal errors at server.
Related
I am trying to convert my paid app to free version with IAP , so basically I need to check if users bought previous version then unlock IAP item , I am not sure I am doing right here or not ! even is it possible to check and track 'appStoreReceiptURL' in development process ? here is my code :
NSURL* url = [[NSBundle mainBundle] appStoreReceiptURL];
NSLog(#"receiptUrl %#",[url path]);
NSError* err = nil;
if (![url checkResourceIsReachableAndReturnError:&err]){
SKReceiptRefreshRequest* request = [[SKReceiptRefreshRequest alloc] initWithReceiptProperties:nil];
request.delegate = self;
[request start];
}
-(void)requestDidFinish:(SKRequest*)request{
if([request isKindOfClass:[SKReceiptRefreshRequest class]]){
NSLog(#"YES, You purchased this app");
}
}
-(void)request:(SKRequest*)request didFailWithError:(NSError *)error{
NSLog(#"NO, you need to buy it ");
}
Now I am able to login with my Apple ID,and after I signed in it tells me YES, You purchased this app", and yes I really bought my app ! , I am going to make sure everything is alright .
Does this process should happen in every update ?
Here is a simple solution
#import <StoreKit/StoreKit.h>
Don't forget to add its delegates
<SKPaymentTransactionObserver, SKProductsRequestDelegate>
Payment Validation
- (IBAction)boughtIt:(id)sender {
NSURL* url = [[NSBundle mainBundle] appStoreReceiptURL];
NSLog(#"receiptUrl %#",[url path]);
NSError* err = nil;
if (![url checkResourceIsReachableAndReturnError:&err]){
SKReceiptRefreshRequest* request = [[SKReceiptRefreshRequest alloc] initWithReceiptProperties:nil];
request.delegate = self;
[request start];
_activity.hidden = NO;
}
}
-(void)requestDidFinish:(SKRequest*)request{
if([request isKindOfClass:[SKReceiptRefreshRequest class]]){
NSLog(#"YES, You purchased this app");
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"Congrats !" message:#"Welcome To The World Of Dinosaurs" delegate:self
cancelButtonTitle:#"Cancel" otherButtonTitles:nil, nil];
[alert show];
[[NSUserDefaults standardUserDefaults] setBool:YES forKey:#"isPurchased"];
[[NSUserDefaults standardUserDefaults] synchronize];
_activity.hidden = YES;
[self dismissViewControllerAnimated:YES completion:nil];
}
}
- (void)request:(SKRequest*)request didFailWithError:(NSError *)error{
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"Sorry !" message:#"It seems you did not purchase this app before, if you like to unlock all content and features please purchase Paleontologist Pack" delegate:self
cancelButtonTitle:#"Cancel" otherButtonTitles:nil, nil];
[alert show];
_activity.hidden = YES;
// [self dismissViewControllerAnimated:YES completion:nil];
NSLog(#"NO, you need to buy it ");
}
This works only if a user PURCHASED the application , it doesn't work for redeem codes
I am creating a rather simple tab-based app with a few UIWebViews. To pass App Store Approval, I need to implement an error if there is no network connection. I'm a beginner, but I tried this and nothing happened.
-(void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Error"
message:#"Can't connect. Please check your internet Connection"
delegate:self
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
}
I've tried Reachability, but its complicated, and I'm not sure exactly how to implement it into a UIAlertView. Could this code work with tweaking or is it trash?
I suggest you to use delegate methods of webView and implement it in ViewController.
There are mainly three delegate methods of webView.
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
- (void)webViewDidFinishLoad:(UIWebView *)webView
In didFailLoadWithError method you can identify error code using [error code]. You can use any of these as per your requirement.
// Error codes for CFURLConnection and CFURLProtocol
kCFURLErrorUnknown = -998,
kCFURLErrorCancelled = -999,
kCFURLErrorBadURL = -1000,
kCFURLErrorTimedOut = -1001,
kCFURLErrorUnsupportedURL = -1002,
kCFURLErrorCannotFindHost = -1003,
kCFURLErrorCannotConnectToHost = -1004,
kCFURLErrorNetworkConnectionLost = -1005,
kCFURLErrorDNSLookupFailed = -1006,
kCFURLErrorHTTPTooManyRedirects = -1007,
kCFURLErrorResourceUnavailable = -1008,
kCFURLErrorNotConnectedToInternet = -1009,
These error codes are available in CFNetworkError.h. In my application i have used in this way.
if ([error code] == kCFURLErrorNotConnectedToInternet) {
// if we can identify the error, we can present a more precise message to the user.
UIAlertView *alertView=[[[UIAlertView alloc] initWithTitle:APP_NAME message:#"Sorry, there doesn’t seem to be an internet connection." delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles: nil]autorelease];
[alertView show];
}
This is working fine for me.
The viewcontroller which you have assigned delegate for the UIWebView; (in the code of viewcontroller where you have set the webview.delegate=self), you need to commit in the header (.h) file to the UIWebViewDelegate protocol. Only then your method :
-(void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
will be triggered. I guess you are missing this otherwise your process is correct.
So, add the UIWebViewDelegate in your .h file.
Hope this will help.
You can check Network Connection using Reachability Code at ViewDidLoad or ViewWillAppear ..Download them using below link
https://github.com/tonymillion/Reachability
Reachability *reach = [Reachability reachabilityForInternetConnection];
NetworkStatus netStatus = [reach currentReachabilityStatus];
if (netStatus != NotReachable)
{
NSLog(#"Async.....Network is Available");
}
else
{
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Network Error" message:#"No Network Available" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil , nil];
[alertView show];
}
Or You can Put alert on below delegate method of UIWebView
(void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
Hope it helps you...!
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])
{
.............
}
I have been stumped by this Semantic Issue warning for a week now, and it is becoming frustrating.
Anyone willing to take a look at it? Any advice will be graciously taken. <3
WebViewController.m
#import "WebViewController.h"
#import "Reachability.h"
#implementation WebViewController
#synthesize webView;
#synthesize backbtn;
#synthesize forwardbtn;
#synthesize webAddy;
#synthesize activityIndicator;
#synthesize loadingLabel;
- (void)viewDidLoad {
loadingLabel.hidden = YES;
backbtn.enabled = NO;
forwardbtn.enabled = NO;
webView.scalesPageToFit = YES;
activityIndicator.hidesWhenStopped = YES;
if([Reachability currentReachabilityStatus] == NotReachable)
{
UIAlertView *av = [[[UIAlertView alloc]
initWithTitle:#"Sorry"
message:#"You are not connected to the internet. Please Try again"
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil] autorelease];
[av setDelegate:self];
[av show];
}
else
{
NSURL *url = [NSURL URLWithString:webAddy];
NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
[webView loadRequest:requestObj];
}
[super viewDidLoad];
}
The Warning redirects me to the 20th line.
The compiler tells me:
"Class method '+currentReachabilityStatus" not found (return type defaults to 'id')"
If more information is needed, please let me know. Thanks again everyone!
See here.
The - (NetworkStatus) currentReachabilityStatus; is not a class method.
Use [[Reachability reachabilityForInternetConnection] currentReachabilityStatus] instead of [Reachability currentReachabilityStatus].
currentReachabilityStatus is an instance method, so you need an instance first.
So I make alert view detects if there in a active internet connection.
This is the Code:
- (void)viewDidLoad
{
[super viewDidLoad];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(reachabilityChanged:)
name:kReachabilityChangedNotification
object:nil];
Reachability * reach = [Reachability reachabilityWithHostname:#"www.google.com"];
reach.reachableBlock = ^(Reachability * reachability)
{
dispatch_async(dispatch_get_main_queue(), ^{
blockLabel.text = #"";
});
};
reach.unreachableBlock = ^(Reachability * reachability)
{
dispatch_async(dispatch_get_main_queue(), ^{
blockLabel.text = #"You are not connected to the Internet";
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Please connect to Internet"
message:nil
delegate:self
cancelButtonTitle:nil
otherButtonTitles:nil];
UIActivityIndicatorView *progress= [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(125, 50, 30, 30)];
progress.activityIndicatorViewStyle = UIActivityIndicatorViewStyleWhiteLarge;
[alert addSubview:progress];
[progress startAnimating];
[alert show];
});
};
[reach startNotifier];
// Do any additional setup after loading the view, typically from a nib.
}
So my application detects if there is a internet connection. But the issue is that if I turn on internet on the iPhone and open the application it still saying there is not internet connection. What should I do…
Well i fix the issue by using notifications.. Code for Reference
-(void)reachabilityChanged:(NSNotification*)note
{
Reachability * reach = [note object];
if([reach isReachable])
{
notificationLabel.text = #"Notification Says Reachable";
NSLog(#"Internet is Up");
}
else
{
notificationLabel.text = #"Notification Says Unreachable";
NSLog(#"Internet is Down");
}
}
You could always implement a non-stop checking for host reachability (or internet connectivity) by signing up for reachability notifications.
One of best examples on how to do this can be found here on SO: How to check for an active Internet Connection on iPhone SDK?
This way your app will always know if the host is reachable or not.
There is no telling what your sparse code does as it does not even look like your Reachability class is Apple's Reachability sample code wrapper around the SystemConfiguration API , you can find that at http://developer.apple.com/library/ios/#samplecode/Reachability/Introduction/Intro.html
The simplest and most definitive check is just a uncached NSURLRequest for a specific url (not just a hostname which merely tests if DNS resolution is working which is not a definitive test and could even be cached)