从服务器接收数据

 1  
 2 - (void)viewDidLoad
 3 {
 4     [super viewDidLoad];
 5     // Do any additional setup after loading the view.
 6     
 7     /*2013/8/19
 8      同步/异步下载数据
 9      */
10     
11    
12 }
13 //从服务器取得数据-同步下载方式
14 - (void)loadDataFromServer:(NSInteger)page andCount:(NSInteger)number
15 {
16     //创建服务器地址
17     NSString * strSever = [NSString stringWithFormat:@"http://192.168.88.8/sns/my/user_list.php?page=%d&number=%d",page, number];
18     //根据服务器地址创建一个url对象,通过此对象进行服务器的数据交互
19     NSURL * url = [NSURL URLWithString:strSever];
20     //访问服务器数据,get方式获取数据,同步下载方式,对主线程造成阻塞
21     NSString * strContent = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:nil];
22     //将字符串转化为数据流
23     NSData * data = [strContent dataUsingEncoding:NSUTF8StringEncoding];
24     //json数据解析结果返回
25     NSDictionary * dic = [data JSONValue];
26 }
27 //NSURLConnectionDataDelegate  服务器连接数据协议
28 - (void)loadDataFromServer1:(NSInteger)page andCount:(NSInteger)number
29 {
30     //创建服务器地址
31     NSString * strSever = [NSString stringWithFormat:@"http://192.168.88.8/sns/my/user_list.php?page=%d&number=%d",page,number];
32     //创建URL
33     NSURL * url = [NSURL URLWithString:strSever];
34     //创建一个url连接请求
35     NSURLRequest * request = [NSURLRequest requestWithURL:url];
36     //创建连接对服务器,并启动连接,自动创建连接过程
37     mConnection = [NSURLConnection connectionWithRequest:request delegate:self];
38     //初始化数据流
39     mData = [[NSMutableData alloc]initWithCapacity:0];
40 }
41 //服务器应答后调用,返回respose,服务器状态
42 - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
43 {
44     //将应带转行为http应答格式
45     NSHTTPURLResponse * httpRes = (NSHTTPURLResponse *)response;
46     
47     switch ([httpRes statusCode])
48     {
49         case 200:
50             NSLog(@"连接成功");
51             break;
52         case 440:
53             NSLog(@"资源不存在");
54             break;
55         case 500:
56             NSLog(@"服务器宕机");
57             break;
58         default:
59             break;
60     }
61     
62     //数据清空
63     [mData setLength:0];
64 }
65 //接收数据调用
66 - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
67 {
68     //将接收的数据添加到mData尾部
69     [mData appendData:data];
70 }
71 //当数据下载结束之后调用
72 - (void)connectionDidFinishLoading:(NSURLConnection *)connection
73 {
74     NSDictionary * dic = [mData JSONValue];
75 }

 

posted on 2013-08-19 23:04  完美的超哥  阅读(978)  评论(0编辑  收藏  举报