新建一个SingleViewApplication应用, 在storyboard中拖2个label,然后创建他们的弱链接,得到如下的代码:
@property (weak, nonatomic) IBOutlet UILabel *label;
@property (weak, nonatomic) IBOutlet UILabel *labelResult;
.m文件的整体变量申明代码如下:
#import "ViewController.h"
@interface ViewController ()
@property (retain, nonatomic) NSURLConnection * connection;
@property (retain, nonatomic) NSMutableData * data;
@property (weak, nonatomic) IBOutlet UILabel *label;
@property (weak, nonatomic) IBOutlet UILabel *labelResult;
@end
在viewDidLoad中添加以下代码:
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
self.label.text = @"正在请求数据";
//访问服务器获取json数据
NSString *urlSring = @"http://www.weather.com.cn/data/cityinfo/101020100.html";
NSURL *url = [NSURL URLWithString:urlSring];
//step2:实例化一个request
NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30.0];
//创建链接
self.connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if (self.connection) {
NSLog(@"创建成功");
}else{
NSLog(@"创建失败");//(@"创建失败“);
}
}
添加如下函数:
-(void) connection:(NSURLConnection *) connection didReceiveResponse:(NSURLResponse *)response{
//接受一个服务端回话,再次一般初始化接受数据的对象
NSMutableData *data = [NSMutableData alloc];
self.data = data;
NSLog(@"接受服务端回话");
}
-(void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
//接受返回数据,这个方法可能会被调用多次,因此将多次返回数据加起来
NSInteger datalength = [data length];
NSLog(@"返回数据量: %ld", (long)datalength);
[self.data appendData:data];
}
-(NSString *)dataFilePath:(NSString *)fileName{
NSArray *path = NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory, NSUserDomainMask, YES);
NSString *document = [path objectAtIndex:0];
NSLog(@"path: %@",path);
return [document stringByAppendingPathComponent:fileName];
}
-(void) connectionDidFinishLoading:(NSURLConnection *)connection{
//NSLog(@"%d", [self.datalength]);
self.label.text = @"请求结束";
NSString *mystr = [[NSString alloc]initWithData:self.data encoding:NSUTF8StringEncoding];
[mystr writeToFile:[self dataFilePath:@"百度图片-全球最大中文图片库.html"] atomically:YES encoding:NSUTF8StringEncoding error:nil];
NSLog(@"最后的结果%@", mystr);
self.label.text = @"最后的结果";
self.labelResult.text = mystr;
// NSDictionary *weather = [NSJSONSerialization JSONObjectWithData:self.data options:NSJSONReadingMutableContainers error:nil];
// NSLog(@"%@",weather);
// [weather writeToFile:[self dataFilePath:@"weather.plist"] atomically:YES];
// NSLog(@"%@",weather);
}
-(void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
self.label.text = @"链接失败";
}
v
好了,现在运行即可。结果: