点步

导航

网络中常用方法

// 1.实例化一个请求对象

    

    NSURL *url = [NSURL URLWithString:@"http://localhost/demo.json"];

    

    NSURLRequest *request = [NSURLRequest requestWithURL:url];

    

    // 2.发送请求

    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {

        // response: 服务器的响应:包含了给我们响应的数据信息(数据格式/数据长度).做文件下载的时候,会使用response ,主要就是得到文件的大小.

        

        // data:服务器响应给我们的数据.

        

        // connectionError:连接错误.

if (connectionError || !data) {

            NSLog(@"连接错误/亲,您的网络不好,请重新尝试连接");

            return ;

        }else

        {

            // <#(NSData *)#>:json数据/

            // 0 .数据解析的时候,效率最高

            // NULL  nil也不会报错

            

            // 将json数据解析成 OC 数据.

            NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:0 error:NULL];

            

            NSLog(@"%@",dict);

 

// id 可以作为一个属性名.完全没问题

            // 接收数字的时候,都用 NSNumber.

            // 解析 JSON数据的时候,用NSJSONSerialization.

            CZWeather *weather = [CZWeather CZWeatherWithDict:dict];

            

            NSLog(@"%@,%@,%@",weather.id,weather.message,weather.messageId);

// 得到二进制数据的字符串

//            NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];

//            

//            NSLog(@"%@",str);

 

        

 

posted on 2015-11-05 13:44  点步  阅读(141)  评论(0编辑  收藏  举报