xcode 4.6 使用NSURLConnection 获取网页内容(iOS6.1,纯手工编码,无xib,无storyboard)

环境 iOS   6.1, xcode 4.6

 

一、创建新项目

 

1、打开 xcode,File --> New --> Project... -->Empty Application

2、项目名称 NSURLConnectionDemo,下面所有选项全部不选,完成创建。

 

二、创建视图控制器

 

3、File-->New-->File-->Objective-C class

4、创建UIViewController的子类,命名 TestViewController

 

三、创建视图控制器实例

 

5、在 AppDelegate.m中引入 

#import "TestViewController.h"

6、添加TestViewController到窗体

 

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions

{

    self.window = [[[UIWindowalloc] initWithFrame:[[UIScreenmainScreen] bounds]] autorelease];

    TestViewController *rootController = [[TestViewControlleralloc]init];

    self.window.rootViewController = rootController;

    self.window.backgroundColor = [UIColorwhiteColor];

    [self.windowmakeKeyAndVisible];

    [rootController release];

    returnYES;

}

 

7、在TestViewController.h 中添加两个变量

 

@interface TestViewController : UIViewController{

    NSMutableData * pageData ;

    UIWebView *webView;

}

 

8、在TestViewController.m 中添加按钮和 UIWebView

 

- (void)viewDidLoad

{

    [superviewDidLoad];

// Do any additional setup after loading the view.

    UIButton *button = [UIButtonbuttonWithType:UIButtonTypeRoundedRect];

    [self.view addSubview:button];

    [button setTitle:@"start"forState:UIControlStateNormal];

    [button setFrame:CGRectMake(10,20, 300, 40)];

    [button addTarget:selfaction:@selector(openUrl) forControlEvents:UIControlEventTouchUpInside];

    

     webView = [[UIWebViewalloc] initWithFrame:CGRectMake(0, 50, 320, 400)];

    [webViewsetUserInteractionEnabled:NO];

    [webViewsetBackgroundColor:[UIColorclearColor]];

    [webView setOpaque:NO];

    

    

    [self.view addSubview:webView];

}

 

9、实现按钮点击的事件

 

-(void)openUrl

{

 

    NSURL *url = [NSURLURLWithString:@"http://www.baidu.com"];

    NSMutableURLRequest *request = [[NSMutableURLRequestalloc ]initWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheDatatimeoutInterval:60];

    pageData = [[NSMutableData alloc]init];

    [request setHTTPMethod:@"GET"];

    [request addValue:@"text/html"forHTTPHeaderField:@"Content-Type"];

    NSURLConnection *conn = [[NSURLConnectionalloc]initWithRequest:request delegate:self];

    [request release];

    [conn release];

}

 

10、实现 NSURLConnection 代理的两个方法

 

- (void)connection:(NSURLConnection *)aConn didReceiveData:(NSData *)data {

[pageData appendData:data];

}

 

- (void)connectionDidFinishLoading:(NSURLConnection *)aConn {

    NSString *results = [[NSStringalloc] initWithData:pageDataencoding:NSUTF8StringEncoding];

[webViewloadHTMLString:results baseURL:nil];

    

}


<END>

你可能感兴趣的:(urlconnection)