//
// NLViewController.m
// NetWorkTest
//
// Created by Nono on 12⑸⑴6.
// Copyright (c) 2012年 NonoWithLilith. All rights reserved.
//
#import "NLViewController.h"
@interface NLViewController ()
@end
@implementation NLViewController
@synthesize label = _label;
@synthesize data = _data;
@synthesize connection = _connection;
- (void)dealloc{
[self.label release];
[self.data release];
[super dealloc];
}
- (void)viewDidLoad
{
[super viewDidLoad];
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10.0, 10.0, 300.0, 400)];
self.label = label;
label.textAlignment = UITextAlignmentCenter;
[label setNumberOfLines:0];
label.lineBreakMode = UILineBreakModeWordWrap;
self.label.text = @"正在在要求數據";
[self.view addSubview:label];
[label release];
//step 1:要求地址
NSString *urlString = @"http://www.google.com";
NSURL *url = [NSURL URLWithString:urlString];
//step 2:實例化1個request
NSURLRequest *requrst = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30.0];
//step 3:創建鏈接
self.connection = [[NSURLConnection alloc] initWithRequest:requrst delegate:self];
if ( self.connection) {
NSLog(@"鏈接成功");
}else {
NSLog(@"鏈接失敗");
}
[url release];
[urlString release];
[requrst release];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)viewDidUnload
{
self.label = nil;
self.data = nil;
[super viewDidUnload];
// Release any retained subviews of the main view.
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}
#pragma mark-
#pragma NSUrlConnectionDelegate methods
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
//接受1個服務端回話,再次1般初始化接受數據的對象
NSLog(@"返回數據類型:%@",[response textEncodingName]);
NSMutableData *d = [[NSMutableData alloc] init];
self.data = d;
[d release];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
//接受返回數據,這個方法可能會被調用屢次,因此將屢次返回數據加起來
NSUInteger datalength = [data length];
NSLog(@"返回數據量:%d",datalength);
[self.data appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
//連接結束
NSLog(@"%d:",[self.data length]);
NSStringEncoding enc = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000);
NSString *mystr = [[NSString alloc] initWithData:_data encoding:enc];
// string i
NSLog(@"最后的結果:%@",mystr);
self.label.text = mystr;
[mystr release];
[self.connection release];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
//鏈接毛病
}
@end