下面代码直接复制到自己的ViewController里面便可测试,希望帮到大家(代码来源于网络
)
#import "ViewController.h"
#define URL @"https://itunesconnect.apple.com/"
@interface ViewController ()
{
NSURLConnection *theConnection;
}
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
UIWebView *myWebview = [[UIWebView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
[self.view addSubview:myWebview];
NSURL *url = [NSURL URLWithString:URL];
NSURLRequest *request =[NSURLRequest requestWithURL:url
cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
timeoutInterval:0.5];
[myWebview loadRequest:request];
if (theConnection)
{
[theConnection cancel];
//SAFE_RELEASE(theConnection);
NSLog(@"safe release connection");
}
theConnection= [[NSURLConnection alloc]initWithRequest:request delegate:self startImmediately:YES];
}
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
if (theConnection) {
//SAFE_RELEASE(theConnection);
NSLog(@"safe release connection");
}
if ([response isKindOfClass:[NSHTTPURLResponse class]]){
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*)response;
if ((([httpResponse statusCode]/100) == 2)){
NSLog(@"connection ok");
}
else{
NSError *error = [NSError errorWithDomain:@"HTTP" code:[httpResponse statusCode] userInfo:nil];
if ([error code] == 404){
NSLog(@"404");
}
}
}
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
if (theConnection) {
//SAFE_RELEASE(theConnection);
NSLog(@"safe release connection");
}
// if (loadNotFinishCode == NSURLErrorCancelled) {
// return;
// }
if (error.code == 22) //The operation couldn’t be completed. Invalid argument
{
NSLog(@"22");
}
else if (error.code == -1001) //The request timed out. webview code -999的时候会收到-1001,这里可以做一些超时时候所需要做的事情,一些提示什么的
{
NSLog(@"-1001");
}
else if (error.code == -1005) //The network connection was lost.
{
NSLog(@"-1005");
}
else if (error.code == -1009){ //The Internet connection appears to be offline
//do nothing
NSLog(@"-1009");
}
}
网友评论