http://code.google.com/p/json-framework
我们通过json来解析天气情况
//
// ViewController.m
// IosWeather
//
// Created by cloud on 13-4-2.
// Copyright (c) 2013年 cloud. All rights reserved.
//
#import "ViewController.h"
#import "JSON.h"
#import "UIImageView+WebCache.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad
{
[superviewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
//连接网站获取json
NSString *url=[@"http://www.weather.com.cn/data/cityinfo/101270101.html"stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSError *error=nil;
NSString *json=[NSStringstringWithContentsOfURL:[NSURLURLWithString:url] encoding:NSUTF8StringEncodingerror:&error];
if (error) {
UIAlertView *alert=[[[UIAlertViewalloc] initWithTitle:@"出错了"message:[error description]delegate:nilcancelButtonTitle:@"OK"otherButtonTitles:nil]autorelease];
[alertshow];
}
//解析json
NSMutableDictionary *jsonObj=[json JSONValue];
NSMutableDictionary *jsonSub=[jsonObj objectForKey:@"weatherinfo"];
_city.text=[NSStringstringWithFormat:@"%@", [jsonSubobjectForKey:@"city"]];
_highTemp.text=[NSStringstringWithFormat:@"%@", [jsonSubobjectForKey:@"temp1"]];
_lowTemp.text=[NSStringstringWithFormat:@"%@", [jsonSubobjectForKey:@"temp2"]];
_weather.text=[NSStringstringWithFormat:@"%@", [jsonSubobjectForKey:@"weather"]];
_time.text=[NSStringstringWithFormat:@"%@", [jsonSubobjectForKey:@"ptime"]];
NSString *img1=[jsonSub objectForKey:@"img1"];
NSString *img2=[jsonSub objectForKey:@"img2"];
//当前时间
NSDate *date = [NSDatedate];
NSCalendar *calendar = [NSCalendarcurrentCalendar];
NSUInteger unitFlags =NSYearCalendarUnit|NSMonthCalendarUnit | NSDayCalendarUnit |NSHourCalendarUnit |NSMinuteCalendarUnit;
NSDateComponents *components = [calendar components:unitFlags fromDate:date];
NSInteger hour = [components hour];
BOOL night=YES;
if (hour>6&&hour<19) {
night=NO;
}
//转换图片格式,如d3.gif转换为d03.gif
if (img1.length<7) {
NSMutableString *tmp=[NSMutableStringstringWithFormat:@"%@",img1];
[tmp insertString:@"0"atIndex:1];
img1=tmp;
}
if (img2.length<7) {
NSMutableString *tmp=[NSMutableStringstringWithFormat:@"%@",img2];
[tmp insertString:@"0"atIndex:1];
img2=tmp;
}
NSString *imgAddress=nil;
if (night) {
imgAddress=[NSStringstringWithFormat:@"http://www.weather.com.cn/m/i/icon_weather/42x30/%@",img2];
}
else
{
imgAddress=[NSStringstringWithFormat:@"http://www.weather.com.cn/m/i/icon_weather/42x30/%@",img1];
}
//动态更新图片
if(imgAddress)
{
NSString *imgurl=[imgAddressstringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
[_imgViewsetImageWithURL:[NSURLURLWithString:imgurl]];
}
}
- (void)didReceiveMemoryWarning
{
[superdidReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void)dealloc {
[_cityrelease];
[_highTemp release];
[_lowTemprelease];
[_weatherrelease];
[_timerelease];
[_imgViewrelease];
[superdealloc];
}
@end
源码地址:http://download.csdn.net/detail/cloud95/5212498