没有互联网连接xcode警报视图

r1wp621o  于 2023-05-19  发布在  其他
关注(0)|答案(3)|浏览(116)

我是一个应用程序开发新手,已经做了一个应用程序,它使用了几个带有uiwebviews的viewcontrollers。我想添加一个alertview当iPhone没有连接到互联网。我已经尝试实现不同的代码,但警报视图不会弹出。
这是我的代码。

//
//  ViewControllersocialgo.h
//  GO!SocialMedia
//
//  Created by Adam Rais on 28/11/2012.
//  Copyright (c) 2012 SocialGO. All rights reserved.
//

#import <UIKit/UIKit.h>
#import "Reachability.h"

@interface ViewControllersocialgo : UIViewController <UIWebViewDelegate>
@property (strong, nonatomic) IBOutlet UIWebView *socialgo;

@end

和ViewControllerpractical.m

//
//  ViewControllerpractical.m
//  GO!SocialMedia
//
//  Created by Adam Rais on 28/11/2012.
//  Copyright (c) 2012 SocialGO. All rights reserved.
//

#import "ViewControllersocialgo.h"
#import <sys/socket.h>
#import <netinet/in.h>
#import <SystemConfiguration/SystemConfiguration.h>



@interface ViewControllersocialgo ()

@end

@implementation ViewControllersocialgo

-(BOOL) isInternetAvailable {
    struct sockaddr_in zeroAddress;
    bzero(&zeroAddress, sizeof(zeroAddress));
    zeroAddress.sin_len = sizeof(zeroAddress);
    zeroAddress.sin_family = AF_INET;

    SCNetworkReachabilityRef reachability =        SCNetworkReachabilityCreateWithAddress(kCFAllocatorDefault, (const struct     sockaddr*)&zeroAddress);
if(reachability != NULL) {
    //NetworkStatus retVal = NotReachable;
    SCNetworkReachabilityFlags flags;
    if (SCNetworkReachabilityGetFlags(reachability, &flags)) {
        if ((flags & kSCNetworkReachabilityFlagsReachable) == 0)
        {
            // if target host is not reachable
            return NO;
        }

        if ((flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0)
        {
            // if target host is reachable and no connection is required
            //  then we'll assume (for now) that your on Wi-Fi
            return YES;
        }

        if ((((flags & kSCNetworkReachabilityFlagsConnectionOnDemand ) != 0) ||
             (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0))
        {
            // ... and the connection is on-demand (or on-traffic) if the
            //     calling application is using the CFSocketStream or higher APIs

            if ((flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0)
            {
                // ... and no [user] intervention is needed
                return YES;
            }
        }

        if ((flags & kSCNetworkReachabilityFlagsIsWWAN) ==     kSCNetworkReachabilityFlagsIsWWAN)
        {
            // ... but WWAN connections are OK if the calling application
            //     is using the CFNetwork (CFSocketStream?) APIs.
            return YES;
        }
    }
}

return NO;

}



- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
    // Custom initialization
}
return self;
}

- (void)viewDidLoad
{
[super viewDidLoad];
[_socialgo setDelegate:self];
NSString *fullURL=@"http://adam182testing.comoj.com/socialgo.html";
NSURL *url=[NSURL URLWithString:fullURL];
NSURLRequest *requestOBJ=[NSURLRequest requestWithURL:url];
[_socialgo loadRequest:requestOBJ];
}

- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}

@end

谢谢

wbrvyc0a

wbrvyc0a1#

不要等到出现错误才告诉用户他没有互联网连接。使用Apple自己的方法来检测连通性- Apple示例项目或使用ARC的this version。它会立即告诉你,如果用户失去连接。

t98cgbkg

t98cgbkg2#

你的视图控制器必须实现UIWebViewDelegate,试试这个代码
ViewControllerpractical.h

//
//  ViewControllerpractical.h
//  GO!SocialMedia
//
//  Created by Adam Rais on 28/11/2012.
//  Copyright (c) 2012 SocialGO. All rights reserved.
//

#import <UIKit/UIKit.h>

@interface ViewControllerpractical : UIViewController <UIWebViewDelegate>
@property (strong, nonatomic) IBOutlet UIWebView *practical;

@end

ViewControllerpractical.m

//
//  ViewControllerpractical.m
//  GO!SocialMedia
//
//  Created by Adam Rais on 28/11/2012.
//  Copyright (c) 2012 SocialGO. All rights reserved.
//

#import "ViewControllerpractical.h"

@interface ViewControllerpractical ()

@end

@implementation ViewControllerpractical

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

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
    // Custom initialization
}
return self;
}

- (void)viewDidLoad
{
[super viewDidLoad];
[_practical setDelegate:self];
NSString *fullURL=@"http://adam182testing.comoj.com/practical.html";
NSURL *url=[NSURL URLWithString:fullURL];
NSURLRequest *requestOBJ=[NSURLRequest requestWithURL:url];
[_practical loadRequest:requestOBJ];
}

- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}

@end

正如Eli Ganem所说,使用可达性更好。
我在我的项目中使用这个函数:

-(BOOL) isInternetAvailable {
    struct sockaddr_in zeroAddress;
    bzero(&zeroAddress, sizeof(zeroAddress));
    zeroAddress.sin_len = sizeof(zeroAddress);
    zeroAddress.sin_family = AF_INET;

    SCNetworkReachabilityRef reachability = SCNetworkReachabilityCreateWithAddress(kCFAllocatorDefault, (const struct sockaddr*)&zeroAddress);
    if(reachability != NULL) {
        //NetworkStatus retVal = NotReachable;
        SCNetworkReachabilityFlags flags;
        if (SCNetworkReachabilityGetFlags(reachability, &flags)) {
            if ((flags & kSCNetworkReachabilityFlagsReachable) == 0)
            {
                // if target host is not reachable
                return NO;
            }

            if ((flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0)
            {
                // if target host is reachable and no connection is required
                //  then we'll assume (for now) that your on Wi-Fi
                return YES;
            }

            if ((((flags & kSCNetworkReachabilityFlagsConnectionOnDemand ) != 0) ||
                 (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0))
            {
                // ... and the connection is on-demand (or on-traffic) if the
                //     calling application is using the CFSocketStream or higher APIs

                if ((flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0)
                {
                    // ... and no [user] intervention is needed
                    return YES;
                }
            }

            if ((flags & kSCNetworkReachabilityFlagsIsWWAN) == kSCNetworkReachabilityFlagsIsWWAN)
            {
                // ... but WWAN connections are OK if the calling application
                //     is using the CFNetwork (CFSocketStream?) APIs.
                return YES;
            }
        }
    }

    return NO;

}
ux6nzvsh

ux6nzvsh3#

试试这个,这个可能管用……
导入UIKit导入网络
//剩余代码
override func viewDidLoad(){ super.viewDidLoad()
//需要添加的代码

let monitor = NWPathMonitor()
    monitor.pathUpdateHandler = { [weak self] path in
        if path.status == .satisfied {
            // We have internet connection
        } else {
            DispatchQueue.main.async {
                let alert = UIAlertController(title: "No Internet Connection !", message: "Please check your connection and try again...", preferredStyle: .alert)
                alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
                self?.present(alert, animated: true, completion: nil)
            }
        }
    }
    let queue = DispatchQueue(label: "Monitor")
    monitor.start(queue: queue)
}

//剩余代码
}

相关问题