[iOS]天气查询
来源:互联网 发布:java 培训 被辞退 编辑:程序博客网 时间:2024/06/05 20:28
[iOS]天气查询
天气查询API:http://apistore.baidu.com/apiworks/servicedetail/112.html
Demo:http://download.csdn.net/download/u012881779/9474529
需导入库:CoreLocation.framework、libsqlite3.tbd、Foundation.framework、Mapkit.framework、CoreGraphics.framework
定位当前位置需要在info中进行设置:
NSLocationAlwaysUsageDescription String YES
NSLocationWhenInUseUsageDescription String YES
#import <Foundation/Foundation.h>#import "MVPublicMethod.h"#import <CoreLocation/CoreLocation.h>#import <UIKit/UIKit.h>@interface DMShareWeatherData : NSObject<CLLocationManagerDelegate>@property (strong, nonatomic) CLLocationManager *locationManager;//单例初始化+(id)sharedWeatherAction;//设置城市+(void)setCityNameAction:(NSString *)theCityName;//获取城市+(NSMutableDictionary *)getCityNameAction;//天气接口请求+(void)netWeatherInfoRequest;+(UIImage *)loadWeatherImage:(id)weatherCode;//开始定位-(void)startLocation;@end
#import "DMShareWeatherData.h"#define WEATHERAPPKEY @"去百度天气申请"static DMShareWeatherData *sharedWeather = nil;static NSMutableArray *shareMutable;static NSMutableDictionary *shareCityNameDict;@implementation DMShareWeatherData@synthesize locationManager;//单例初始化+(id)sharedWeatherAction{ @synchronized (self){ if(!sharedWeather){ sharedWeather = [[DMShareWeatherData alloc] init]; shareMutable = [[NSMutableArray alloc] init]; shareCityNameDict = [[NSMutableDictionary alloc] init]; [shareCityNameDict setObject:@"上海" forKey:@"name"]; } return sharedWeather; } return sharedWeather;}//设置城市+(void)setCityNameAction:(NSString *)theCityName{ if(theCityName && [MVPublicMethod IsChinese:theCityName]){ [shareCityNameDict removeAllObjects]; [shareCityNameDict setObject:theCityName forKey:@"name"]; }}//获取城市+(NSMutableDictionary *)getCityNameAction{ return shareCityNameDict;}//天气接口请求+(void)netWeatherInfoRequest{ NSMutableDictionary *nameDict = [DMShareWeatherData getCityNameAction]; NSString *theCityName = [nameDict objectForKey:@"name"]; if(!theCityName){ return; } NSString *theCityID = [DMShareWeatherData getCityIDFromCityName:theCityName]; if (theCityID == nil) { theCityID = @"101020100"; theCityName = @"上海"; } NSString *httpUrl = @"http://apis.baidu.com/apistore/weatherservice/recentweathers"; NSString *httpArg = [NSString stringWithFormat:@"cityname=%@&cityid=%@",theCityName,theCityID]; [self request: httpUrl withHttpArg: httpArg];}+(void)request: (NSString*)httpUrl withHttpArg: (NSString*)HttpArg { NSString *urlStr = [[NSString alloc]initWithFormat: @"%@?%@", httpUrl, HttpArg]; urlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; NSURL *url = [NSURL URLWithString: urlStr]; NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL: url cachePolicy: NSURLRequestUseProtocolCachePolicy timeoutInterval: 10]; [request setHTTPMethod: @"GET"]; [request addValue: WEATHERAPPKEY forHTTPHeaderField: @"apikey"]; [NSURLConnection sendAsynchronousRequest: request queue: [NSOperationQueue mainQueue] completionHandler: ^(NSURLResponse *response, NSData *data, NSError *error){ if (error) { } else { NSError *errorJSON = [[NSError alloc] init]; NSDictionary *tempDict = (NSDictionary *)[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&errorJSON]; if(tempDict){ NSDictionary *dataDict = [tempDict objectForKey:@"retData"]; if(dataDict){ //处理信息 [self processingInfomation:dataDict]; } } } }];}//处理信息+(void)processingInfomation:(NSDictionary *)theDict{ if([[theDict class] isSubclassOfClass:[NSDictionary class]] && theDict && theDict.count >0){ [shareMutable removeAllObjects]; NSArray *forecastArr = (NSArray *)[theDict objectForKey:@"forecast"]; NSDictionary *firstDict = [theDict objectForKey:@"today"]; NSDictionary *secondDict; NSDictionary *thirdDict; if(forecastArr.count > 0){ secondDict = [forecastArr objectAtIndex:0]; } if(forecastArr.count > 1){ thirdDict = [forecastArr objectAtIndex:1]; } //1 NSMutableDictionary *oneDict = [[NSMutableDictionary alloc] init]; //城市 [oneDict setObject:[theDict objectForKey:@"city"] forKey:@"city"]; [oneDict setObject:[theDict objectForKey:@"cityid"] forKey:@"cityid"]; //星期几 [oneDict setObject:[firstDict objectForKey:@"week"] forKey:@"week"]; //日期 [oneDict setObject:[self dateAction:[firstDict objectForKey:@"date"]] forKey:@"date"]; //天气状况描述 [oneDict setObject:[firstDict objectForKey:@"type"] forKey:@"weatherinfo"]; //天气状况代码 [oneDict setObject:[self getWeatherCodeFrom:[firstDict objectForKey:@"type"]] forKey:@"weathercode"]; //温度 [oneDict setObject:[self curTmpAction:[firstDict objectForKey:@"curTemp"]] forKey:@"curTemp"]; //温度范围 [oneDict setObject:[self tmpAction:firstDict] forKey:@"tmprange"]; //风力 [oneDict setObject:[firstDict objectForKey:@"fengli"] forKey:@"fengli"]; [shareMutable addObject:oneDict]; //2 NSMutableDictionary *twoDict = [[NSMutableDictionary alloc] init]; [twoDict setObject:[theDict objectForKey:@"city"] forKey:@"city"]; [twoDict setObject:[theDict objectForKey:@"cityid"] forKey:@"cityid"]; [twoDict setObject:[secondDict objectForKey:@"week"] forKey:@"week"]; [twoDict setObject:[self dateAction:[secondDict objectForKey:@"date"]] forKey:@"date"]; [twoDict setObject:[secondDict objectForKey:@"type"] forKey:@"weatherinfo"]; [twoDict setObject:[self getWeatherCodeFrom:[secondDict objectForKey:@"type"]] forKey:@"weathercode"]; [twoDict setObject:@"" forKey:@"curTemp"]; [twoDict setObject:[self tmpAction:secondDict] forKey:@"tmprange"]; [twoDict setObject:[secondDict objectForKey:@"fengli"] forKey:@"fengli"]; [shareMutable addObject:twoDict]; //3 NSMutableDictionary *threeDict = [[NSMutableDictionary alloc] init]; [threeDict setObject:[theDict objectForKey:@"city"] forKey:@"city"]; [threeDict setObject:[theDict objectForKey:@"cityid"] forKey:@"cityid"]; [threeDict setObject:[thirdDict objectForKey:@"week"] forKey:@"week"]; [threeDict setObject:[self dateAction:[thirdDict objectForKey:@"date"]] forKey:@"date"]; [threeDict setObject:[thirdDict objectForKey:@"type"] forKey:@"weatherinfo"]; [threeDict setObject:[self getWeatherCodeFrom:[thirdDict objectForKey:@"type"]] forKey:@"weathercode"]; [threeDict setObject:@"" forKey:@"curTemp"]; [threeDict setObject:[self tmpAction:thirdDict] forKey:@"tmprange"]; [threeDict setObject:[thirdDict objectForKey:@"fengli"] forKey:@"fengli"]; [shareMutable addObject:threeDict]; //缓存 NSUserDefaults *weatherDefaults = [NSUserDefaults standardUserDefaults]; [weatherDefaults setObject:shareMutable forKey:@"weatherdata"]; [weatherDefaults synchronize]; //通知 NSNotification *tempNF = [[NSNotification alloc] initWithName:@"weatherdatanf" object:nil userInfo:[[NSDictionary alloc] initWithObjectsAndKeys:shareMutable,@"info", nil]]; [[NSNotificationCenter defaultCenter] postNotification:tempNF]; }}//风速+(NSString *)windspdAction:(NSString *)thespd{ NSString *spd = [NSString stringWithFormat:@"%@m/s",thespd]; return spd;}//温度+(NSString *)curTmpAction:(NSString *)thetmp{ NSString *tmp = [NSString stringWithFormat:@"%@",thetmp]; return tmp;}//日期+(NSString *)dateAction:(NSString *)theDate{ NSArray *subsArr = [theDate componentsSeparatedByString:@"-"]; NSString *dateStr = [subsArr componentsJoinedByString:@"/"]; return dateStr;}//温度+(NSString *)tmpAction:(NSDictionary *)theTmpDict{ //NSString *tmpStr = [NSString stringWithFormat:@"%2d°~%2d°",[theTmpDict objectForKey:@"max"],[theTmpDict objectForKey:@"min"]]; NSString *tmpStr = [NSString stringWithFormat:@"%@~%@",[theTmpDict objectForKey:@"lowtemp"],[theTmpDict objectForKey:@"hightemp"]]; return tmpStr;}//根据天气状态 转换天气码+(NSString *)getWeatherCodeFrom:(NSString *)theType{ NSString *tempCode = @"0"; if([theType isEqualToString:@"晴"]){ tempCode = @"0"; } if([theType isEqualToString:@"多云"]){ tempCode = @"1"; } if([theType isEqualToString:@"阴"]){ tempCode = @"2"; } if([theType isEqualToString:@"阵雨"]){ tempCode = @"3"; } if([theType isEqualToString:@"雷阵雨"]){ tempCode = @"4"; } if([theType isEqualToString:@"雷阵雨伴有冰雹"]){ tempCode = @"5"; } if([theType isEqualToString:@"雨夹雪"]){ tempCode = @"6"; } if([theType isEqualToString:@"小雨"]){ tempCode = @"7"; } if([theType isEqualToString:@"中雨"]){ tempCode = @"8"; } if([theType isEqualToString:@"大雨"]){ tempCode = @"9"; } if([theType isEqualToString:@"暴雨"]){ tempCode = @"10"; } if([theType isEqualToString:@"大暴雨"]){ tempCode = @"11"; } if([theType isEqualToString:@"特大暴雨"]){ tempCode = @"12"; } if([theType isEqualToString:@"阵雪"]){ tempCode = @"13"; } if([theType isEqualToString:@"小雪"]){ tempCode = @"14"; } if([theType isEqualToString:@"中雪"]){ tempCode = @"15"; } if([theType isEqualToString:@"大雪"]){ tempCode = @"16"; } if([theType isEqualToString:@"暴雪"]){ tempCode = @"17"; } if([theType isEqualToString:@"雾"]){ tempCode = @"18"; } if([theType isEqualToString:@"冻雨"]){ tempCode = @"19"; } if([theType isEqualToString:@"沙尘暴"]){ tempCode = @"20"; } if([theType isEqualToString:@"小到中雨"]){ tempCode = @"21"; } if([theType isEqualToString:@"中到大雨"]){ tempCode = @"22"; } if([theType isEqualToString:@"大到暴雨"]){ tempCode = @"23"; } if([theType isEqualToString:@"暴雨到大暴雨"]){ tempCode = @"24"; } if([theType isEqualToString:@"大暴雨到特大暴雨"]){ tempCode = @"25"; } if([theType isEqualToString:@"小到中雪"]){ tempCode = @"26"; } if([theType isEqualToString:@"中到大雪"]){ tempCode = @"27"; } if([theType isEqualToString:@"大到暴雪"]){ tempCode = @"28"; } if([theType isEqualToString:@"浮尘"]){ tempCode = @"29"; } if([theType isEqualToString:@"扬沙"]){ tempCode = @"30"; } if([theType isEqualToString:@"强沙尘暴"]){ tempCode = @"31"; } if([theType isEqualToString:@"霾"]){ tempCode = @"53"; } if([theType isEqualToString:@"无"]){ tempCode = @"99"; } return tempCode;}+(UIImage *)loadWeatherImage:(id)weatherCode{ UIImage *image; NSString *imagePath; int code=0; @try { code=[weatherCode intValue]; } @catch (NSException *exception) { code=0; } NSInteger timestamp = [MVPublicMethod cNowTimestamp]; NSString *dd = [MVPublicMethod cStringFromTimestampHH:[NSString stringWithFormat:@"%ld",(long)timestamp]]; //7:00 19:00 if([dd intValue]>=7 && [dd intValue]<=19){ //白天 imagePath=[[NSString alloc] initWithFormat:@"weather_d%d.png",code]; }else{ //晚上 imagePath=[[NSString alloc] initWithFormat:@"weather_n%d.png",code]; } image=[UIImage imageNamed:imagePath]; return image;}//开始定位-(void)startLocation{ locationManager=[[CLLocationManager alloc] init]; locationManager.delegate=self; locationManager.desiredAccuracy=kCLLocationAccuracyBest; locationManager.distanceFilter=1000.0f; float version = [[[UIDevice currentDevice] systemVersion] floatValue]; if(version >= 8){ [locationManager requestWhenInUseAuthorization];//使用程序其间允许访问位置数据(iOS8定位需要) } [locationManager startUpdatingLocation];//开启定位}#pragma mark - CoreLocation Delegate-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations{ CLLocation *currentLocation = [locations lastObject]; CLGeocoder *geocoder = [[CLGeocoder alloc] init]; [geocoder reverseGeocodeLocation:currentLocation completionHandler:^(NSArray *array, NSError *error) { if (array.count > 0) { CLPlacemark *placemark = [array objectAtIndex:0]; //获取城市 NSString *city = placemark.locality; if (!city) { city = placemark.administrativeArea; } //获取定位天气预报 [DMShareWeatherData setCityNameAction:city]; [DMShareWeatherData netWeatherInfoRequest]; [manager stopUpdatingLocation]; } }];}//根据城市名获取城市ID+(NSString *)getCityIDFromCityName:(NSString *)theCityName{ NSMutableDictionary *zuzhuangDict = [[NSMutableDictionary alloc] init]; NSString *filePath = [[NSBundle mainBundle] pathForResource:@"weatherRegion" ofType:@"txt"]; NSString *placeStr = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil]; NSArray *tempArr = [placeStr componentsSeparatedByString:@"\n"]; for (int i = 0; i < tempArr.count ; i ++) { NSString *componentStr = [tempArr objectAtIndex:i]; if([MVPublicMethod judgeStringIsNull:componentStr]){ NSArray *componentArr = [componentStr componentsSeparatedByString:@"="]; NSString *valueStr = [NSString stringWithFormat:@"%@",[componentArr firstObject]]; NSString *keyStr = [NSString stringWithFormat:@"%@",[componentArr lastObject]]; [zuzhuangDict setObject:keyStr forKey:valueStr]; } } if(theCityName.length > 2){ NSMutableString * tempMutStr = [theCityName mutableCopy]; theCityName = [tempMutStr stringByReplacingOccurrencesOfString:@"市" withString:@""]; tempMutStr = [theCityName mutableCopy]; theCityName = [tempMutStr stringByReplacingOccurrencesOfString:@"省" withString:@""]; } //101100101 NSString *tempCode; NSArray *keysArr = [zuzhuangDict allKeys]; for (int i = 0; i < keysArr.count ; i ++) { NSString *tempKeyStr = [keysArr objectAtIndex:i]; NSString *tempValueStr = [zuzhuangDict objectForKey:tempKeyStr]; if([tempValueStr isEqualToString:theCityName]){ tempCode = tempKeyStr; } } return tempCode;}@end
示意图:
0 0
- [iOS]天气查询
- 天气查询
- 天气查询
- 查询天气
- 天气查询
- 天气查询
- 查询天气
- 查询天气
- Sol° for iOS--天气查询开源项目
- iOS项目开发实战(Swift)—查询天气小应用
- PHP天气查询1
- PHP天气查询2
- VB实现天气查询
- AJAX 的天气查询
- 城市天气情况查询
- wp7查询天气
- 根据城市查询天气
- 天气查询接口
- 判断table是否已经应用了tablejs插件
- linux lcd设备驱动剖析三
- spring mvc 与struts2比较
- CoordinatorLayou eclipse中使用出现的问题
- JVM--类加载机制
- [iOS]天气查询
- inline和宏的优点和缺点
- GenyMotion离线下载
- 正则表达式 课堂笔记
- Java开发者必备十大学习网站
- cocos动作使用示例(2)
- linux lcd设备驱动剖析四
- 在table上面得加一个提示层,可加任何HTML
- hdu 1978 How many ways (记忆化搜索)