我想检查一下我是否可以在iOS上使用Cocoa Touch库或在macOS上使用Cocoa库连接互联网。
我想出了一个方法来做这个使用NSURL。我的方法似乎有点不可靠(因为即使谷歌也可能有一天宕机,依赖第三方似乎很糟糕),虽然如果谷歌没有响应,我可以检查其他一些网站的响应,但这似乎是浪费和不必要的应用程序开销。
- (BOOL)connectedToInternet {
NSString *URLString = [NSString stringWithContentsOfURL:[NSURL URLWithString:@"http://www.google.com"]];
return ( URLString != NULL ) ? YES : NO;
}
是我做得不好,(更不用说stringWithContentsOfURL已弃用在iOS 3.0和macOS 10.4),如果是这样,有什么更好的方法来实现这一点?
很简单的…试试下面这些步骤:
步骤1:将SystemConfiguration框架添加到项目中。
步骤2:将以下代码导入到头文件中。
#import <SystemConfiguration/SystemConfiguration.h>
第三步:使用以下方法
类型1:
- (BOOL) currentNetworkStatus {
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
BOOL连接;
BOOL与;
Const char *host = "www.apple.com";
SCNetworkReachabilityRef reachabilityreachabilitycreatewithname (NULL, host);
SCNetworkReachabilityFlags旗帜;
connected = SCNetworkReachabilityGetFlags(可达性,&flags);
isConnected = NO;
isConnected = connected && (flags & kSCNetworkFlagsReachable) && !(flags & kSCNetworkFlagsConnectionRequired);
CFRelease(可达性);
返回与;
}
类型2:
导入头文件:# Import "Reachability.h"
(保龄球)currentNetworkStatus
{
可达性*可达性=[互联网连接的可达性];
NetworkStatus NetworkStatus =[可达性currentReachabilityStatus];
返回networkStatus !=不可访问;
}
第四步:使用方法:
- (void)CheckInternet
{
BOOL network = [self currentNetworkStatus];
if (network)
{
NSLog(@"Network Available");
}
else
{
NSLog(@"No Network Available");
}
}
以下是我在我的应用程序中是如何做到的:虽然200状态响应代码不能保证任何东西,但对我来说已经足够稳定了。这并不需要像NSData回答一样多的加载,因为我的只是检查HEAD响应。
银行的国际代码
func checkInternet(flag:Bool, completionHandler:(internet:Bool) -> Void)
{
UIApplication.sharedApplication().networkActivityIndicatorVisible = true
let url = NSURL(string: "http://www.google.com/")
let request = NSMutableURLRequest(URL: url!)
request.HTTPMethod = "HEAD"
request.cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringLocalAndRemoteCacheData
request.timeoutInterval = 10.0
NSURLConnection.sendAsynchronousRequest(request, queue:NSOperationQueue.mainQueue(), completionHandler:
{(response: NSURLResponse!, data: NSData!, error: NSError!) -> Void in
UIApplication.sharedApplication().networkActivityIndicatorVisible = false
let rsp = response as! NSHTTPURLResponse?
completionHandler(internet:rsp?.statusCode == 200)
})
}
func yourMethod()
{
self.checkInternet(false, completionHandler:
{(internet:Bool) -> Void in
if (internet)
{
// "Internet" aka Google URL reachable
}
else
{
// No "Internet" aka Google URL un-reachable
}
})
}
objective - c代码
typedef void(^connection)(BOOL);
- (void)checkInternet:(connection)block
{
NSURL *url = [NSURL URLWithString:@"http://www.google.com/"];
NSMutableURLRequest *headRequest = [NSMutableURLRequest requestWithURL:url];
headRequest.HTTPMethod = @"HEAD";
NSURLSessionConfiguration *defaultConfigObject = [NSURLSessionConfiguration ephemeralSessionConfiguration];
defaultConfigObject.timeoutIntervalForResource = 10.0;
defaultConfigObject.requestCachePolicy = NSURLRequestReloadIgnoringLocalAndRemoteCacheData;
NSURLSession *defaultSession = [NSURLSession sessionWithConfiguration:defaultConfigObject delegate:self delegateQueue: [NSOperationQueue mainQueue]];
NSURLSessionDataTask *dataTask = [defaultSession dataTaskWithRequest:headRequest
completionHandler:^(NSData *data, NSURLResponse *response, NSError *error)
{
if (!error && response)
{
block([(NSHTTPURLResponse *)response statusCode] == 200);
}
}];
[dataTask resume];
}
- (void)yourMethod
{
[self checkInternet:^(BOOL internet)
{
if (internet)
{
// "Internet" aka Google URL reachable
}
else
{
// No "Internet" aka Google URL un-reachable
}
}];
}
下载Reachability文件,https://gist.github.com/darkseed/1182373
在framework中添加CFNetwork.framework和'SystemConfiguration.framework'
导入“Reachability.h”
首先:在framework中添加CFNetwork.framework
代码:ViewController.m
- (void)viewWillAppear:(BOOL)animated
{
Reachability *r = [Reachability reachabilityWithHostName:@"www.google.com"];
NetworkStatus internetStatus = [r currentReachabilityStatus];
if ((internetStatus != ReachableViaWiFi) && (internetStatus != ReachableViaWWAN))
{
/// Create an alert if connection doesn't work
UIAlertView *myAlert = [[UIAlertView alloc]initWithTitle:@"No Internet Connection" message:NSLocalizedString(@"InternetMessage", nil)delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil];
[myAlert show];
[myAlert release];
}
else
{
NSLog(@"INTERNET IS CONNECT");
}
}