技术文章分类(180)

技术随笔(11)

iOS获取天气情况

第一个部分关于数据获取。

            通过网络获取数据的方法,有两种,一种是通过NSRUL,NSURLREQUEST,NSURLCONNECTION的方法获取。另一种方法是直接通过NSData的initContentwithURLdataWithContentsOfURL的方法。

 

描述如下:

方法1:

发送json请求:http://m.weather.com.cn/data/101250101.html   其中这里的cityId=101250101(长沙)

ios获取json数据的方法:

NSError*error;
//加载一个NSURL对象
NSURLRequest*request=[NSURLRequestrequestWithURL:[NSURLURLWithString:@"http://m.weather.com.cn/data/101180601.html"]];
//将请求的url数据放到NSData对象中
NSData*response=[NSURLConnectionsendSynchronousRequest:requestreturningResponse:nilerror:nil];
//iOS5自带解析类NSJSONSerialization从response中解析出数据放到字典中
NSDictionary*weatherDic=[NSJSONSerializationJSONObjectWithData:responseoptions:NSJSONReadingMutableLeaveserror:&error];
//weatherDic字典中存放的数据也是字典型,从它里面通过键值取值
NSDictionary*weatherInfo=[weatherDicobjectForKey:@"weatherinfo"];
NSLog(@"今天是%@%@%@的天气状况是:%@%@",[weatherInfoobjectForKey:@"date_y"],[weatherInfoobjectForKey:@"week"],[weatherInfoobjectForKey:@"city"],[weatherInfoobjectForKey:@"weather1"],[weatherInfoobjectForKey:@"temp1"]);
//打印出weatherInfo字典所存储数据
NSLog(@"weatherInfo字典里面的内容是--->%@",[weatherInfodescription]);

如果你所在城市不在长沙,我这里有一份所有cityId(所有中国城市 cityid 对应 城市名)表,你可以下载后进行对比。下载链接:http://download.csdn.net/download/li841538513/7480721

 

 

posted @ 2014-06-11 09:57  坤哥MartinLi  阅读(551)  评论(0编辑  收藏  举报