环境 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 = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
TestViewController *rootController = [[TestViewController alloc]init];
self.window.rootViewController = rootController;
self.window.backgroundColor = [UIColor whiteColor];
[self.window makeKeyAndVisible];
[rootController release];
return YES;
}
7、在TestViewController.h 中添加两个变量
@interface TestViewController : UIViewController{
NSMutableData * pageData ;
UIWebView *webView;
}
8、在TestViewController.m 中添加按钮和 UIWebView
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[self.view addSubview:button];
[button setTitle:@"start" forState:UIControlStateNormal];
[button setFrame:CGRectMake(10,20, 300, 40)];
[button addTarget:self action:@selector(openUrl) forControlEvents:UIControlEventTouchUpInside];
webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 50, 320, 400)];
[webView setUserInteractionEnabled:NO];
[webView setBackgroundColor:[UIColor clearColor]];
[webView setOpaque:NO];
[self.view addSubview:webView];
}
9、实现按钮点击的事件
-(void)openUrl
{
NSURL *url = [NSURL URLWithString:@"http://www.baidu.com"];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc ]initWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:60];
pageData = [[NSMutableData alloc]init];
[request setHTTPMethod:@"GET"];
[request addValue:@"text/html" forHTTPHeaderField:@"Content-Type"];
NSURLConnection *conn = [[NSURLConnection alloc]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 = [[NSString alloc] initWithData:pageData encoding:NSUTF8StringEncoding];
[webView loadHTMLString:results baseURL:nil];
}